LLVM API Documentation

LLParser.cpp

Go to the documentation of this file.
00001 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the parser class for .ll files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "LLParser.h"
00015 #include "llvm/AutoUpgrade.h"
00016 #include "llvm/CallingConv.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/InlineAsm.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/LLVMContext.h"
00022 #include "llvm/Metadata.h"
00023 #include "llvm/Module.h"
00024 #include "llvm/Operator.h"
00025 #include "llvm/ValueSymbolTable.h"
00026 #include "llvm/ADT/SmallPtrSet.h"
00027 #include "llvm/ADT/StringExtras.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 using namespace llvm;
00031 
00032 namespace llvm {
00033   /// ValID - Represents a reference of a definition of some sort with no type.
00034   /// There are several cases where we have to parse the value but where the
00035   /// type can depend on later context.  This may either be a numeric reference
00036   /// or a symbolic (%var) reference.  This is just a discriminated union.
00037   struct ValID {
00038     enum {
00039       t_LocalID, t_GlobalID,      // ID in UIntVal.
00040       t_LocalName, t_GlobalName,  // Name in StrVal.
00041       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
00042       t_Null, t_Undef, t_Zero,    // No value.
00043       t_EmptyArray,               // No value:  []
00044       t_Constant,                 // Value in ConstantVal.
00045       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
00046       t_Metadata                  // Value in MetadataVal.
00047     } Kind;
00048     
00049     LLParser::LocTy Loc;
00050     unsigned UIntVal;
00051     std::string StrVal, StrVal2;
00052     APSInt APSIntVal;
00053     APFloat APFloatVal;
00054     Constant *ConstantVal;
00055     MetadataBase *MetadataVal;
00056     ValID() : APFloatVal(0.0) {}
00057   };
00058 }
00059 
00060 /// Run: module ::= toplevelentity*
00061 bool LLParser::Run() {
00062   // Prime the lexer.
00063   Lex.Lex();
00064 
00065   return ParseTopLevelEntities() ||
00066          ValidateEndOfModule();
00067 }
00068 
00069 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
00070 /// module.
00071 bool LLParser::ValidateEndOfModule() {
00072   if (!ForwardRefTypes.empty())
00073     return Error(ForwardRefTypes.begin()->second.second,
00074                  "use of undefined type named '" +
00075                  ForwardRefTypes.begin()->first + "'");
00076   if (!ForwardRefTypeIDs.empty())
00077     return Error(ForwardRefTypeIDs.begin()->second.second,
00078                  "use of undefined type '%" +
00079                  utostr(ForwardRefTypeIDs.begin()->first) + "'");
00080   
00081   if (!ForwardRefVals.empty())
00082     return Error(ForwardRefVals.begin()->second.second,
00083                  "use of undefined value '@" + ForwardRefVals.begin()->first +
00084                  "'");
00085   
00086   if (!ForwardRefValIDs.empty())
00087     return Error(ForwardRefValIDs.begin()->second.second,
00088                  "use of undefined value '@" +
00089                  utostr(ForwardRefValIDs.begin()->first) + "'");
00090   
00091   if (!ForwardRefMDNodes.empty())
00092     return Error(ForwardRefMDNodes.begin()->second.second,
00093                  "use of undefined metadata '!" +
00094                  utostr(ForwardRefMDNodes.begin()->first) + "'");
00095   
00096 
00097   // Look for intrinsic functions and CallInst that need to be upgraded
00098   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
00099     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
00100   
00101   return false;
00102 }
00103 
00104 //===----------------------------------------------------------------------===//
00105 // Top-Level Entities
00106 //===----------------------------------------------------------------------===//
00107 
00108 bool LLParser::ParseTopLevelEntities() {
00109   while (1) {
00110     switch (Lex.getKind()) {
00111     default:         return TokError("expected top-level entity");
00112     case lltok::Eof: return false;
00113     //case lltok::kw_define:
00114     case lltok::kw_declare: if (ParseDeclare()) return true; break;
00115     case lltok::kw_define:  if (ParseDefine()) return true; break;
00116     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
00117     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
00118     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
00119     case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
00120     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
00121     case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
00122     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
00123     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
00124     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
00125     case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
00126     case lltok::NamedMD:    if (ParseNamedMetadata()) return true; break;
00127 
00128     // The Global variable production with no name can have many different
00129     // optional leading prefixes, the production is:
00130     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
00131     //               OptionalAddrSpace ('constant'|'global') ...
00132     case lltok::kw_private :       // OptionalLinkage
00133     case lltok::kw_linker_private: // OptionalLinkage
00134     case lltok::kw_internal:       // OptionalLinkage
00135     case lltok::kw_weak:           // OptionalLinkage
00136     case lltok::kw_weak_odr:       // OptionalLinkage
00137     case lltok::kw_linkonce:       // OptionalLinkage
00138     case lltok::kw_linkonce_odr:   // OptionalLinkage
00139     case lltok::kw_appending:      // OptionalLinkage
00140     case lltok::kw_dllexport:      // OptionalLinkage
00141     case lltok::kw_common:         // OptionalLinkage
00142     case lltok::kw_dllimport:      // OptionalLinkage
00143     case lltok::kw_extern_weak:    // OptionalLinkage
00144     case lltok::kw_external: {     // OptionalLinkage
00145       unsigned Linkage, Visibility;
00146       if (ParseOptionalLinkage(Linkage) ||
00147           ParseOptionalVisibility(Visibility) ||
00148           ParseGlobal("", SMLoc(), Linkage, true, Visibility))
00149         return true;
00150       break;
00151     }
00152     case lltok::kw_default:       // OptionalVisibility
00153     case lltok::kw_hidden:        // OptionalVisibility
00154     case lltok::kw_protected: {   // OptionalVisibility
00155       unsigned Visibility;
00156       if (ParseOptionalVisibility(Visibility) ||
00157           ParseGlobal("", SMLoc(), 0, false, Visibility))
00158         return true;
00159       break;
00160     }
00161         
00162     case lltok::kw_thread_local:  // OptionalThreadLocal
00163     case lltok::kw_addrspace:     // OptionalAddrSpace
00164     case lltok::kw_constant:      // GlobalType
00165     case lltok::kw_global:        // GlobalType
00166       if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
00167       break;
00168     }
00169   }
00170 }
00171 
00172 
00173 /// toplevelentity
00174 ///   ::= 'module' 'asm' STRINGCONSTANT
00175 bool LLParser::ParseModuleAsm() {
00176   assert(Lex.getKind() == lltok::kw_module);
00177   Lex.Lex();
00178   
00179   std::string AsmStr; 
00180   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
00181       ParseStringConstant(AsmStr)) return true;
00182   
00183   const std::string &AsmSoFar = M->getModuleInlineAsm();
00184   if (AsmSoFar.empty())
00185     M->setModuleInlineAsm(AsmStr);
00186   else
00187     M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
00188   return false;
00189 }
00190 
00191 /// toplevelentity
00192 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
00193 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
00194 bool LLParser::ParseTargetDefinition() {
00195   assert(Lex.getKind() == lltok::kw_target);
00196   std::string Str;
00197   switch (Lex.Lex()) {
00198   default: return TokError("unknown target property");
00199   case lltok::kw_triple:
00200     Lex.Lex();
00201     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
00202         ParseStringConstant(Str))
00203       return true;
00204     M->setTargetTriple(Str);
00205     return false;
00206   case lltok::kw_datalayout:
00207     Lex.Lex();
00208     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
00209         ParseStringConstant(Str))
00210       return true;
00211     M->setDataLayout(Str);
00212     return false;
00213   }
00214 }
00215 
00216 /// toplevelentity
00217 ///   ::= 'deplibs' '=' '[' ']'
00218 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
00219 bool LLParser::ParseDepLibs() {
00220   assert(Lex.getKind() == lltok::kw_deplibs);
00221   Lex.Lex();
00222   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
00223       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
00224     return true;
00225 
00226   if (EatIfPresent(lltok::rsquare))
00227     return false;
00228   
00229   std::string Str;
00230   if (ParseStringConstant(Str)) return true;
00231   M->addLibrary(Str);
00232 
00233   while (EatIfPresent(lltok::comma)) {
00234     if (ParseStringConstant(Str)) return true;
00235     M->addLibrary(Str);
00236   }
00237 
00238   return ParseToken(lltok::rsquare, "expected ']' at end of list");
00239 }
00240 
00241 /// ParseUnnamedType:
00242 ///   ::= 'type' type
00243 ///   ::= LocalVarID '=' 'type' type
00244 bool LLParser::ParseUnnamedType() {
00245   unsigned TypeID = NumberedTypes.size();
00246 
00247   // Handle the LocalVarID form.
00248   if (Lex.getKind() == lltok::LocalVarID) {
00249     if (Lex.getUIntVal() != TypeID)
00250       return Error(Lex.getLoc(), "type expected to be numbered '%" +
00251                    utostr(TypeID) + "'");
00252     Lex.Lex(); // eat LocalVarID;
00253 
00254     if (ParseToken(lltok::equal, "expected '=' after name"))
00255       return true;
00256   }
00257 
00258   assert(Lex.getKind() == lltok::kw_type);
00259   LocTy TypeLoc = Lex.getLoc();
00260   Lex.Lex(); // eat kw_type
00261 
00262   PATypeHolder Ty(Type::getVoidTy(Context));
00263   if (ParseType(Ty)) return true;
00264  
00265   // See if this type was previously referenced.
00266   std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
00267     FI = ForwardRefTypeIDs.find(TypeID);
00268   if (FI != ForwardRefTypeIDs.end()) {
00269     if (FI->second.first.get() == Ty)
00270       return Error(TypeLoc, "self referential type is invalid");
00271     
00272     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
00273     Ty = FI->second.first.get();
00274     ForwardRefTypeIDs.erase(FI);
00275   }
00276   
00277   NumberedTypes.push_back(Ty);
00278   
00279   return false;
00280 }
00281 
00282 /// toplevelentity
00283 ///   ::= LocalVar '=' 'type' type
00284 bool LLParser::ParseNamedType() {
00285   std::string Name = Lex.getStrVal();
00286   LocTy NameLoc = Lex.getLoc();
00287   Lex.Lex();  // eat LocalVar.
00288   
00289   PATypeHolder Ty(Type::getVoidTy(Context));
00290   
00291   if (ParseToken(lltok::equal, "expected '=' after name") ||
00292       ParseToken(lltok::kw_type, "expected 'type' after name") ||
00293       ParseType(Ty))
00294     return true;
00295   
00296   // Set the type name, checking for conflicts as we do so.
00297   bool AlreadyExists = M->addTypeName(Name, Ty);
00298   if (!AlreadyExists) return false;
00299 
00300   // See if this type is a forward reference.  We need to eagerly resolve
00301   // types to allow recursive type redefinitions below.
00302   std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
00303   FI = ForwardRefTypes.find(Name);
00304   if (FI != ForwardRefTypes.end()) {
00305     if (FI->second.first.get() == Ty)
00306       return Error(NameLoc, "self referential type is invalid");
00307 
00308     cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
00309     Ty = FI->second.first.get();
00310     ForwardRefTypes.erase(FI);
00311   }
00312   
00313   // Inserting a name that is already defined, get the existing name.
00314   const Type *Existing = M->getTypeByName(Name);
00315   assert(Existing && "Conflict but no matching type?!");
00316     
00317   // Otherwise, this is an attempt to redefine a type. That's okay if
00318   // the redefinition is identical to the original.
00319   // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
00320   if (Existing == Ty) return false;
00321   
00322   // Any other kind of (non-equivalent) redefinition is an error.
00323   return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
00324                Ty->getDescription() + "'");
00325 }
00326 
00327 
00328 /// toplevelentity
00329 ///   ::= 'declare' FunctionHeader
00330 bool LLParser::ParseDeclare() {
00331   assert(Lex.getKind() == lltok::kw_declare);
00332   Lex.Lex();
00333   
00334   Function *F;
00335   return ParseFunctionHeader(F, false);
00336 }
00337 
00338 /// toplevelentity
00339 ///   ::= 'define' FunctionHeader '{' ...
00340 bool LLParser::ParseDefine() {
00341   assert(Lex.getKind() == lltok::kw_define);
00342   Lex.Lex();
00343   
00344   Function *F;
00345   return ParseFunctionHeader(F, true) ||
00346          ParseFunctionBody(*F);
00347 }
00348 
00349 /// ParseGlobalType
00350 ///   ::= 'constant'
00351 ///   ::= 'global'
00352 bool LLParser::ParseGlobalType(bool &IsConstant) {
00353   if (Lex.getKind() == lltok::kw_constant)
00354     IsConstant = true;
00355   else if (Lex.getKind() == lltok::kw_global)
00356     IsConstant = false;
00357   else {
00358     IsConstant = false;
00359     return TokError("expected 'global' or 'constant'");
00360   }
00361   Lex.Lex();
00362   return false;
00363 }
00364 
00365 /// ParseUnnamedGlobal:
00366 ///   OptionalVisibility ALIAS ...
00367 ///   OptionalLinkage OptionalVisibility ...   -> global variable
00368 ///   GlobalID '=' OptionalVisibility ALIAS ...
00369 ///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
00370 bool LLParser::ParseUnnamedGlobal() {
00371   unsigned VarID = NumberedVals.size();
00372   std::string Name;
00373   LocTy NameLoc = Lex.getLoc();
00374 
00375   // Handle the GlobalID form.
00376   if (Lex.getKind() == lltok::GlobalID) {
00377     if (Lex.getUIntVal() != VarID)
00378       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
00379                    utostr(VarID) + "'");
00380     Lex.Lex(); // eat GlobalID;
00381 
00382     if (ParseToken(lltok::equal, "expected '=' after name"))
00383       return true;
00384   }
00385 
00386   bool HasLinkage;
00387   unsigned Linkage, Visibility;
00388   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
00389       ParseOptionalVisibility(Visibility))
00390     return true;
00391   
00392   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
00393     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
00394   return ParseAlias(Name, NameLoc, Visibility);
00395 }
00396 
00397 /// ParseNamedGlobal:
00398 ///   GlobalVar '=' OptionalVisibility ALIAS ...
00399 ///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
00400 bool LLParser::ParseNamedGlobal() {
00401   assert(Lex.getKind() == lltok::GlobalVar);
00402   LocTy NameLoc = Lex.getLoc();
00403   std::string Name = Lex.getStrVal();
00404   Lex.Lex();
00405   
00406   bool HasLinkage;
00407   unsigned Linkage, Visibility;
00408   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
00409       ParseOptionalLinkage(Linkage, HasLinkage) ||
00410       ParseOptionalVisibility(Visibility))
00411     return true;
00412   
00413   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
00414     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
00415   return ParseAlias(Name, NameLoc, Visibility);
00416 }
00417 
00418 // MDString:
00419 //   ::= '!' STRINGCONSTANT
00420 bool LLParser::ParseMDString(MetadataBase *&MDS) {
00421   std::string Str;
00422   if (ParseStringConstant(Str)) return true;
00423   MDS = MDString::get(Context, Str);
00424   return false;
00425 }
00426 
00427 // MDNode:
00428 //   ::= '!' MDNodeNumber
00429 bool LLParser::ParseMDNode(MetadataBase *&Node) {
00430   // !{ ..., !42, ... }
00431   unsigned MID = 0;
00432   if (ParseUInt32(MID))  return true;
00433   
00434   // Check existing MDNode.
00435   std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
00436   if (I != MetadataCache.end()) {
00437     Node = I->second;
00438     return false;
00439   }
00440 
00441   // Check known forward references.
00442   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
00443     FI = ForwardRefMDNodes.find(MID);
00444   if (FI != ForwardRefMDNodes.end()) {
00445     Node = FI->second.first;
00446     return false;
00447   }
00448 
00449   // Create MDNode forward reference
00450   SmallVector<Value *, 1> Elts;
00451   std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
00452   Elts.push_back(MDString::get(Context, FwdRefName));
00453   MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
00454   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
00455   Node = FwdNode;
00456   return false;
00457 }    
00458 
00459 ///ParseNamedMetadata:
00460 ///   !foo = !{ !1, !2 }
00461 bool LLParser::ParseNamedMetadata() {
00462   assert(Lex.getKind() == lltok::NamedMD);
00463   Lex.Lex();
00464   std::string Name = Lex.getStrVal();
00465 
00466   if (ParseToken(lltok::equal, "expected '=' here"))
00467     return true;
00468 
00469   if (Lex.getKind() != lltok::Metadata)
00470     return TokError("Expected '!' here");
00471   Lex.Lex();
00472 
00473   if (Lex.getKind() != lltok::lbrace)
00474     return TokError("Expected '{' here");
00475   Lex.Lex();
00476   SmallVector<MetadataBase *, 8> Elts;
00477   do {
00478     if (Lex.getKind() != lltok::Metadata)
00479       return TokError("Expected '!' here");
00480     Lex.Lex();
00481     MetadataBase *N = 0;
00482     if (ParseMDNode(N)) return true;
00483     Elts.push_back(N);
00484   } while (EatIfPresent(lltok::comma));
00485 
00486   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
00487     return true;
00488 
00489   NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
00490   return false;
00491 }
00492 
00493 /// ParseStandaloneMetadata:
00494 ///   !42 = !{...} 
00495 bool LLParser::ParseStandaloneMetadata() {
00496   assert(Lex.getKind() == lltok::Metadata);
00497   Lex.Lex();
00498   unsigned MetadataID = 0;
00499   if (ParseUInt32(MetadataID))
00500     return true;
00501   if (MetadataCache.find(MetadataID) != MetadataCache.end())
00502     return TokError("Metadata id is already used");
00503   if (ParseToken(lltok::equal, "expected '=' here"))
00504     return true;
00505 
00506   LocTy TyLoc;
00507   PATypeHolder Ty(Type::getVoidTy(Context));
00508   if (ParseType(Ty, TyLoc))
00509     return true;
00510   
00511   if (Lex.getKind() != lltok::Metadata)
00512     return TokError("Expected metadata here");
00513 
00514   Lex.Lex();
00515   if (Lex.getKind() != lltok::lbrace)
00516     return TokError("Expected '{' here");
00517 
00518   SmallVector<Value *, 16> Elts;
00519   if (ParseMDNodeVector(Elts) 
00520       || ParseToken(lltok::rbrace, "expected end of metadata node"))
00521     return true;
00522 
00523   MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
00524   MetadataCache[MetadataID] = Init;
00525   std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
00526     FI = ForwardRefMDNodes.find(MetadataID);
00527   if (FI != ForwardRefMDNodes.end()) {
00528     MDNode *FwdNode = cast<MDNode>(FI->second.first);
00529     FwdNode->replaceAllUsesWith(Init);
00530     ForwardRefMDNodes.erase(FI);
00531   }
00532 
00533   return false;
00534 }
00535 
00536 /// ParseAlias:
00537 ///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
00538 /// Aliasee
00539 ///   ::= TypeAndValue
00540 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
00541 ///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
00542 ///
00543 /// Everything through visibility has already been parsed.
00544 ///
00545 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
00546                           unsigned Visibility) {
00547   assert(Lex.getKind() == lltok::kw_alias);
00548   Lex.Lex();
00549   unsigned Linkage;
00550   LocTy LinkageLoc = Lex.getLoc();
00551   if (ParseOptionalLinkage(Linkage))
00552     return true;
00553 
00554   if (Linkage != GlobalValue::ExternalLinkage &&
00555       Linkage != GlobalValue::WeakAnyLinkage &&
00556       Linkage != GlobalValue::WeakODRLinkage &&
00557       Linkage != GlobalValue::InternalLinkage &&
00558       Linkage != GlobalValue::PrivateLinkage &&
00559       Linkage != GlobalValue::LinkerPrivateLinkage)
00560     return Error(LinkageLoc, "invalid linkage type for alias");
00561   
00562   Constant *Aliasee;
00563   LocTy AliaseeLoc = Lex.getLoc();
00564   if (Lex.getKind() != lltok::kw_bitcast &&
00565       Lex.getKind() != lltok::kw_getelementptr) {
00566     if (ParseGlobalTypeAndValue(Aliasee)) return true;
00567   } else {
00568     // The bitcast dest type is not present, it is implied by the dest type.
00569     ValID ID;
00570     if (ParseValID(ID)) return true;
00571     if (ID.Kind != ValID::t_Constant)
00572       return Error(AliaseeLoc, "invalid aliasee");
00573     Aliasee = ID.ConstantVal;
00574   }
00575   
00576   if (!isa<PointerType>(Aliasee->getType()))
00577     return Error(AliaseeLoc, "alias must have pointer type");
00578 
00579   // Okay, create the alias but do not insert it into the module yet.
00580   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
00581                                     (GlobalValue::LinkageTypes)Linkage, Name,
00582                                     Aliasee);
00583   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
00584   
00585   // See if this value already exists in the symbol table.  If so, it is either
00586   // a redefinition or a definition of a forward reference.
00587   if (GlobalValue *Val =
00588         cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
00589     // See if this was a redefinition.  If so, there is no entry in
00590     // ForwardRefVals.
00591     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
00592       I = ForwardRefVals.find(Name);
00593     if (I == ForwardRefVals.end())
00594       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
00595 
00596     // Otherwise, this was a definition of forward ref.  Verify that types
00597     // agree.
00598     if (Val->getType() != GA->getType())
00599       return Error(NameLoc,
00600               "forward reference and definition of alias have different types");
00601     
00602     // If they agree, just RAUW the old value with the alias and remove the
00603     // forward ref info.
00604     Val->replaceAllUsesWith(GA);
00605     Val->eraseFromParent();
00606     ForwardRefVals.erase(I);
00607   }
00608   
00609   // Insert into the module, we know its name won't collide now.
00610   M->getAliasList().push_back(GA);
00611   assert(GA->getNameStr() == Name && "Should not be a name conflict!");
00612   
00613   return false;
00614 }
00615 
00616 /// ParseGlobal
00617 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
00618 ///       OptionalAddrSpace GlobalType Type Const
00619 ///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
00620 ///       OptionalAddrSpace GlobalType Type Const
00621 ///
00622 /// Everything through visibility has been parsed already.
00623 ///
00624 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
00625                            unsigned Linkage, bool HasLinkage,
00626                            unsigned Visibility) {
00627   unsigned AddrSpace;
00628   bool ThreadLocal, IsConstant;
00629   LocTy TyLoc;
00630     
00631   PATypeHolder Ty(Type::getVoidTy(Context));
00632   if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
00633       ParseOptionalAddrSpace(AddrSpace) ||
00634       ParseGlobalType(IsConstant) ||
00635       ParseType(Ty, TyLoc))
00636     return true;
00637   
00638   // If the linkage is specified and is external, then no initializer is
00639   // present.
00640   Constant *Init = 0;
00641   if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
00642                       Linkage != GlobalValue::ExternalWeakLinkage &&
00643                       Linkage != GlobalValue::ExternalLinkage)) {
00644     if (ParseGlobalValue(Ty, Init))
00645       return true;
00646   }
00647 
00648   if (isa<FunctionType>(Ty) || Ty == Type::getLabelTy(Context))
00649     return Error(TyLoc, "invalid type for global variable");
00650   
00651   GlobalVariable *GV = 0;
00652 
00653   // See if the global was forward referenced, if so, use the global.
00654   if (!Name.empty()) {
00655     if ((GV = M->getGlobalVariable(Name, true)) &&
00656         !ForwardRefVals.erase(Name))
00657       return Error(NameLoc, "redefinition of global '@" + Name + "'");
00658   } else {
00659     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
00660       I = ForwardRefValIDs.find(NumberedVals.size());
00661     if (I != ForwardRefValIDs.end()) {
00662       GV = cast<GlobalVariable>(I->second.first);
00663       ForwardRefValIDs.erase(I);
00664     }
00665   }
00666 
00667   if (GV == 0) {
00668     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, 
00669                             Name, 0, false, AddrSpace);
00670   } else {
00671     if (GV->getType()->getElementType() != Ty)
00672       return Error(TyLoc,
00673             "forward reference and definition of global have different types");
00674     
00675     // Move the forward-reference to the correct spot in the module.
00676     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
00677   }
00678 
00679   if (Name.empty())
00680     NumberedVals.push_back(GV);
00681   
00682   // Set the parsed properties on the global.
00683   if (Init)
00684     GV->setInitializer(Init);
00685   GV->setConstant(IsConstant);
00686   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
00687   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
00688   GV->setThreadLocal(ThreadLocal);
00689   
00690   // Parse attributes on the global.
00691   while (Lex.getKind() == lltok::comma) {
00692     Lex.Lex();
00693     
00694     if (Lex.getKind() == lltok::kw_section) {
00695       Lex.Lex();
00696       GV->setSection(Lex.getStrVal());
00697       if (ParseToken(lltok::StringConstant, "expected global section string"))
00698         return true;
00699     } else if (Lex.getKind() == lltok::kw_align) {
00700       unsigned Alignment;
00701       if (ParseOptionalAlignment(Alignment)) return true;
00702       GV->setAlignment(Alignment);
00703     } else {
00704       TokError("unknown global variable property!");
00705     }
00706   }
00707   
00708   return false;
00709 }
00710 
00711 
00712 //===----------------------------------------------------------------------===//
00713 // GlobalValue Reference/Resolution Routines.
00714 //===----------------------------------------------------------------------===//
00715 
00716 /// GetGlobalVal - Get a value with the specified name or ID, creating a
00717 /// forward reference record if needed.  This can return null if the value
00718 /// exists but does not have the right type.
00719 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
00720                                     LocTy Loc) {
00721   const PointerType *PTy = dyn_cast<PointerType>(Ty);
00722   if (PTy == 0) {
00723     Error(Loc, "global variable reference must have pointer type");
00724     return 0;
00725   }
00726   
00727   // Look this name up in the normal function symbol table.
00728   GlobalValue *Val =
00729     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
00730   
00731   // If this is a forward reference for the value, see if we already created a
00732   // forward ref record.
00733   if (Val == 0) {
00734     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
00735       I = ForwardRefVals.find(Name);
00736     if (I != ForwardRefVals.end())
00737       Val = I->second.first;
00738   }
00739   
00740   // If we have the value in the symbol table or fwd-ref table, return it.
00741   if (Val) {
00742     if (Val->getType() == Ty) return Val;
00743     Error(Loc, "'@" + Name + "' defined with type '" +
00744           Val->getType()->getDescription() + "'");
00745     return 0;
00746   }
00747   
00748   // Otherwise, create a new forward reference for this value and remember it.
00749   GlobalValue *FwdVal;
00750   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
00751     // Function types can return opaque but functions can't.
00752     if (isa<OpaqueType>(FT->getReturnType())) {
00753       Error(Loc, "function may not return opaque type");
00754       return 0;
00755     }
00756     
00757     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
00758   } else {
00759     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
00760                                 GlobalValue::ExternalWeakLinkage, 0, Name);
00761   }
00762   
00763   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
00764   return FwdVal;
00765 }
00766 
00767 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
00768   const PointerType *PTy = dyn_cast<PointerType>(Ty);
00769   if (PTy == 0) {
00770     Error(Loc, "global variable reference must have pointer type");
00771     return 0;
00772   }
00773   
00774   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
00775   
00776   // If this is a forward reference for the value, see if we already created a
00777   // forward ref record.
00778   if (Val == 0) {
00779     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
00780       I = ForwardRefValIDs.find(ID);
00781     if (I != ForwardRefValIDs.end())
00782       Val = I->second.first;
00783   }
00784   
00785   // If we have the value in the symbol table or fwd-ref table, return it.
00786   if (Val) {
00787     if (Val->getType() == Ty) return Val;
00788     Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
00789           Val->getType()->getDescription() + "'");
00790     return 0;
00791   }
00792   
00793   // Otherwise, create a new forward reference for this value and remember it.
00794   GlobalValue *FwdVal;
00795   if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
00796     // Function types can return opaque but functions can't.
00797     if (isa<OpaqueType>(FT->getReturnType())) {
00798       Error(Loc, "function may not return opaque type");
00799       return 0;
00800     }
00801     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
00802   } else {
00803     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
00804                                 GlobalValue::ExternalWeakLinkage, 0, "");
00805   }
00806   
00807   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
00808   return FwdVal;
00809 }
00810 
00811 
00812 //===----------------------------------------------------------------------===//
00813 // Helper Routines.
00814 //===----------------------------------------------------------------------===//
00815 
00816 /// ParseToken - If the current token has the specified kind, eat it and return
00817 /// success.  Otherwise, emit the specified error and return failure.
00818 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
00819   if (Lex.getKind() != T)
00820     return TokError(ErrMsg);
00821   Lex.Lex();
00822   return false;
00823 }
00824 
00825 /// ParseStringConstant
00826 ///   ::= StringConstant
00827 bool LLParser::ParseStringConstant(std::string &Result) {
00828   if (Lex.getKind() != lltok::StringConstant)
00829     return TokError("expected string constant");
00830   Result = Lex.getStrVal();
00831   Lex.Lex();
00832   return false;
00833 }
00834 
00835 /// ParseUInt32
00836 ///   ::= uint32
00837 bool LLParser::ParseUInt32(unsigned &Val) {
00838   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
00839     return TokError("expected integer");
00840   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
00841   if (Val64 != unsigned(Val64))
00842     return TokError("expected 32-bit integer (too large)");
00843   Val = Val64;
00844   Lex.Lex();
00845   return false;
00846 }
00847 
00848 
00849 /// ParseOptionalAddrSpace
00850 ///   := /*empty*/
00851 ///   := 'addrspace' '(' uint32 ')'
00852 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
00853   AddrSpace = 0;
00854   if (!EatIfPresent(lltok::kw_addrspace))
00855     return false;
00856   return ParseToken(lltok::lparen, "expected '(' in address space") ||
00857          ParseUInt32(AddrSpace) ||
00858          ParseToken(lltok::rparen, "expected ')' in address space");
00859 }  
00860 
00861 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
00862 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
00863 /// 2: function attr.
00864 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
00865 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
00866   Attrs = Attribute::None;
00867   LocTy AttrLoc = Lex.getLoc();
00868   
00869   while (1) {
00870     switch (Lex.getKind()) {
00871     case lltok::kw_sext:
00872     case lltok::kw_zext:
00873       // Treat these as signext/zeroext if they occur in the argument list after
00874       // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
00875       // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
00876       // expr.
00877       // FIXME: REMOVE THIS IN LLVM 3.0
00878       if (AttrKind == 3) {
00879         if (Lex.getKind() == lltok::kw_sext)
00880           Attrs |= Attribute::SExt;
00881         else
00882           Attrs |= Attribute::ZExt;
00883         break;
00884       }
00885       // FALL THROUGH.
00886     default:  // End of attributes.
00887       if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
00888         return Error(AttrLoc, "invalid use of function-only attribute");
00889         
00890       if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
00891         return Error(AttrLoc, "invalid use of parameter-only attribute");
00892         
00893       return false;
00894     case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
00895     case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
00896     case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
00897     case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
00898     case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
00899     case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
00900     case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
00901     case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
00902 
00903     case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
00904     case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
00905     case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
00906     case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
00907     case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
00908     case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
00909     case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
00910     case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
00911     case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
00912     case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
00913     case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
00914     case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
00915         
00916     case lltok::kw_align: {
00917       unsigned Alignment;
00918       if (ParseOptionalAlignment(Alignment))
00919         return true;
00920       Attrs |= Attribute::constructAlignmentFromInt(Alignment);
00921       continue;
00922     }
00923     }
00924     Lex.Lex();
00925   }
00926 }
00927 
00928 /// ParseOptionalLinkage
00929 ///   ::= /*empty*/
00930 ///   ::= 'private'
00931 ///   ::= 'linker_private'
00932 ///   ::= 'internal'
00933 ///   ::= 'weak'
00934 ///   ::= 'weak_odr'
00935 ///   ::= 'linkonce'
00936 ///   ::= 'linkonce_odr'
00937 ///   ::= 'appending'
00938 ///   ::= 'dllexport'
00939 ///   ::= 'common'
00940 ///   ::= 'dllimport'
00941 ///   ::= 'extern_weak'
00942 ///   ::= 'external'
00943 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
00944   HasLinkage = false;
00945   switch (Lex.getKind()) {
00946   default:                       Res=GlobalValue::ExternalLinkage; return false;
00947   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
00948   case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
00949   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
00950   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
00951   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
00952   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
00953   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
00954   case lltok::kw_available_externally:
00955     Res = GlobalValue::AvailableExternallyLinkage;
00956     break;
00957   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
00958   case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
00959   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
00960   case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
00961   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
00962   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
00963   }
00964   Lex.Lex();
00965   HasLinkage = true;
00966   return false;
00967 }
00968 
00969 /// ParseOptionalVisibility
00970 ///   ::= /*empty*/
00971 ///   ::= 'default'
00972 ///   ::= 'hidden'
00973 ///   ::= 'protected'
00974 /// 
00975 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
00976   switch (Lex.getKind()) {
00977   default:                  Res = GlobalValue::DefaultVisibility; return false;
00978   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
00979   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
00980   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
00981   }
00982   Lex.Lex();
00983   return false;
00984 }
00985 
00986 /// ParseOptionalCallingConv
00987 ///   ::= /*empty*/
00988 ///   ::= 'ccc'
00989 ///   ::= 'fastcc'
00990 ///   ::= 'coldcc'
00991 ///   ::= 'x86_stdcallcc'
00992 ///   ::= 'x86_fastcallcc'
00993 ///   ::= 'arm_apcscc'
00994 ///   ::= 'arm_aapcscc'
00995 ///   ::= 'arm_aapcs_vfpcc'
00996 ///   ::= 'cc' UINT
00997 ///
00998 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
00999   switch (Lex.getKind()) {
01000   default:                       CC = CallingConv::C; return false;
01001   case lltok::kw_ccc:            CC = CallingConv::C; break;
01002   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
01003   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
01004   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
01005   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
01006   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
01007   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
01008   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
01009   case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
01010   }
01011   Lex.Lex();
01012   return false;
01013 }
01014 
01015 /// ParseOptionalAlignment
01016 ///   ::= /* empty */
01017 ///   ::= 'align' 4
01018 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
01019   Alignment = 0;
01020   if (!EatIfPresent(lltok::kw_align))
01021     return false;
01022   LocTy AlignLoc = Lex.getLoc();
01023   if (ParseUInt32(Alignment)) return true;
01024   if (!isPowerOf2_32(Alignment))
01025     return Error(AlignLoc, "alignment is not a power of two");
01026   return false;
01027 }
01028 
01029 /// ParseOptionalCommaAlignment
01030 ///   ::= /* empty */
01031 ///   ::= ',' 'align' 4
01032 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
01033   Alignment = 0;
01034   if (!EatIfPresent(lltok::comma))
01035     return false;
01036   return ParseToken(lltok::kw_align, "expected 'align'") ||
01037          ParseUInt32(Alignment);
01038 }
01039 
01040 /// ParseIndexList
01041 ///    ::=  (',' uint32)+
01042 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
01043   if (Lex.getKind() != lltok::comma)
01044     return TokError("expected ',' as start of index list");
01045   
01046   while (EatIfPresent(lltok::comma)) {
01047     unsigned Idx;
01048     if (ParseUInt32(Idx)) return true;
01049     Indices.push_back(Idx);
01050   }
01051   
01052   return false;
01053 }
01054 
01055 //===----------------------------------------------------------------------===//
01056 // Type Parsing.
01057 //===----------------------------------------------------------------------===//
01058 
01059 /// ParseType - Parse and resolve a full type.
01060 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
01061   LocTy TypeLoc = Lex.getLoc();
01062   if (ParseTypeRec(Result)) return true;
01063   
01064   // Verify no unresolved uprefs.
01065   if (!UpRefs.empty())
01066     return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
01067   
01068   if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
01069     return Error(TypeLoc, "void type only allowed for function results");
01070   
01071   return false;
01072 }
01073 
01074 /// HandleUpRefs - Every time we finish a new layer of types, this function is
01075 /// called.  It loops through the UpRefs vector, which is a list of the
01076 /// currently active types.  For each type, if the up-reference is contained in
01077 /// the newly completed type, we decrement the level count.  When the level
01078 /// count reaches zero, the up-referenced type is the type that is passed in:
01079 /// thus we can complete the cycle.
01080 ///
01081 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
01082   // If Ty isn't abstract, or if there are no up-references in it, then there is
01083   // nothing to resolve here.
01084   if (!ty->isAbstract() || UpRefs.empty()) return ty;
01085   
01086   PATypeHolder Ty(ty);
01087 #if 0
01088   errs() << "Type '" << Ty->getDescription()
01089          << "' newly formed.  Resolving upreferences.\n"
01090          << UpRefs.size() << " upreferences active!\n";
01091 #endif
01092   
01093   // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
01094   // to zero), we resolve them all together before we resolve them to Ty.  At
01095   // the end of the loop, if there is anything to resolve to Ty, it will be in
01096   // this variable.
01097   OpaqueType *TypeToResolve = 0;
01098   
01099   for (unsigned i = 0; i != UpRefs.size(); ++i) {
01100     // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
01101     bool ContainsType =
01102       std::find(Ty->subtype_begin(), Ty->subtype_end(),
01103                 UpRefs[i].LastContainedTy) != Ty->subtype_end();
01104     
01105 #if 0
01106     errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
01107            << UpRefs[i].LastContainedTy->getDescription() << ") = "
01108            << (ContainsType ? "true" : "false")
01109            << " level=" << UpRefs[i].NestingLevel << "\n";
01110 #endif
01111     if (!ContainsType)
01112       continue;
01113     
01114     // Decrement level of upreference
01115     unsigned Level = --UpRefs[i].NestingLevel;
01116     UpRefs[i].LastContainedTy = Ty;
01117     
01118     // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
01119     if (Level != 0)
01120       continue;
01121     
01122 #if 0
01123     errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
01124 #endif
01125     if (!TypeToResolve)
01126       TypeToResolve = UpRefs[i].UpRefTy;
01127     else
01128       UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
01129     UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
01130     --i;                                // Do not skip the next element.
01131   }
01132   
01133   if (TypeToResolve)
01134     TypeToResolve->refineAbstractTypeTo(Ty);
01135   
01136   return Ty;
01137 }
01138 
01139 
01140 /// ParseTypeRec - The recursive function used to process the internal
01141 /// implementation details of types.
01142 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
01143   switch (Lex.getKind()) {
01144   default:
01145     return TokError("expected type");
01146   case lltok::Type:
01147     // TypeRec ::= 'float' | 'void' (etc)
01148     Result = Lex.getTyVal();
01149     Lex.Lex(); 
01150     break;
01151   case lltok::kw_opaque:
01152     // TypeRec ::= 'opaque'
01153     Result = OpaqueType::get(Context);
01154     Lex.Lex();
01155     break;
01156   case lltok::lbrace:
01157     // TypeRec ::= '{' ... '}'
01158     if (ParseStructType(Result, false))
01159       return true;
01160     break;
01161   case lltok::lsquare:
01162     // TypeRec ::= '[' ... ']'
01163     Lex.Lex(); // eat the lsquare.
01164     if (ParseArrayVectorType(Result, false))
01165       return true;
01166     break;
01167   case lltok::less: // Either vector or packed struct.
01168     // TypeRec ::= '<' ... '>'
01169     Lex.Lex();
01170     if (Lex.getKind() == lltok::lbrace) {
01171       if (ParseStructType(Result, true) ||
01172           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
01173         return true;
01174     } else if (ParseArrayVectorType(Result, true))
01175       return true;
01176     break;
01177   case lltok::LocalVar:
01178   case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
01179     // TypeRec ::= %foo
01180     if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
01181       Result = T;
01182     } else {
01183       Result = OpaqueType::get(Context);
01184       ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
01185                                             std::make_pair(Result,
01186                                                            Lex.getLoc())));
01187       M->addTypeName(Lex.getStrVal(), Result.get());
01188     }
01189     Lex.Lex();
01190     break;
01191       
01192   case lltok::LocalVarID:
01193     // TypeRec ::= %4
01194     if (Lex.getUIntVal() < NumberedTypes.size())
01195       Result = NumberedTypes[Lex.getUIntVal()];
01196     else {
01197       std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
01198         I = ForwardRefTypeIDs.find(Lex.getUIntVal());
01199       if (I != ForwardRefTypeIDs.end())
01200         Result = I->second.first;
01201       else {
01202         Result = OpaqueType::get(Context);
01203         ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
01204                                                 std::make_pair(Result,
01205                                                                Lex.getLoc())));
01206       }
01207     }
01208     Lex.Lex();
01209     break;
01210   case lltok::backslash: {
01211     // TypeRec ::= '\' 4
01212     Lex.Lex();
01213     unsigned Val;
01214     if (ParseUInt32(Val)) return true;
01215     OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
01216     UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
01217     Result = OT;
01218     break;
01219   }
01220   }
01221   
01222   // Parse the type suffixes. 
01223   while (1) {
01224     switch (Lex.getKind()) {
01225     // End of type.
01226     default: return false;    
01227 
01228     // TypeRec ::= TypeRec '*'
01229     case lltok::star:
01230       if (Result.get() == Type::getLabelTy(Context))
01231         return TokError("basic block pointers are invalid");
01232       if (Result.get() == Type::getVoidTy(Context))
01233         return TokError("pointers to void are invalid; use i8* instead");
01234       if (!PointerType::isValidElementType(Result.get()))
01235         return TokError("pointer to this type is invalid");
01236       Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
01237       Lex.Lex();
01238       break;
01239 
01240     // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
01241     case lltok::kw_addrspace: {
01242       if (Result.get() == Type::getLabelTy(Context))
01243         return TokError("basic block pointers are invalid");
01244       if (Result.get() == Type::getVoidTy(Context))
01245         return TokError("pointers to void are invalid; use i8* instead");
01246       if (!PointerType::isValidElementType(Result.get()))
01247         return TokError("pointer to this type is invalid");
01248       unsigned AddrSpace;
01249       if (ParseOptionalAddrSpace(AddrSpace) ||
01250           ParseToken(lltok::star, "expected '*' in address space"))
01251         return true;
01252 
01253       Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
01254       break;
01255     }
01256         
01257     /// Types '(' ArgTypeListI ')' OptFuncAttrs
01258     case lltok::lparen:
01259       if (ParseFunctionType(Result))
01260         return true;
01261       break;
01262     }
01263   }
01264 }
01265 
01266 /// ParseParameterList
01267 ///    ::= '(' ')'
01268 ///    ::= '(' Arg (',' Arg)* ')'
01269 ///  Arg
01270 ///    ::= Type OptionalAttributes Value OptionalAttributes
01271 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
01272                                   PerFunctionState &PFS) {
01273   if (ParseToken(lltok::lparen, "expected '(' in call"))
01274     return true;
01275   
01276   while (Lex.getKind() != lltok::rparen) {
01277     // If this isn't the first argument, we need a comma.
01278     if (!ArgList.empty() &&
01279         ParseToken(lltok::comma, "expected ',' in argument list"))
01280       return true;
01281     
01282     // Parse the argument.
01283     LocTy ArgLoc;
01284     PATypeHolder ArgTy(Type::getVoidTy(Context));
01285     unsigned ArgAttrs1, ArgAttrs2;
01286     Value *V;
01287     if (ParseType(ArgTy, ArgLoc) ||
01288         ParseOptionalAttrs(ArgAttrs1, 0) ||
01289         ParseValue(ArgTy, V, PFS) ||
01290         // FIXME: Should not allow attributes after the argument, remove this in
01291         // LLVM 3.0.
01292         ParseOptionalAttrs(ArgAttrs2, 3))
01293       return true;
01294     ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
01295   }
01296 
01297   Lex.Lex();  // Lex the ')'.
01298   return false;
01299 }
01300 
01301 
01302 
01303 /// ParseArgumentList - Parse the argument list for a function type or function
01304 /// prototype.  If 'inType' is true then we are parsing a FunctionType.
01305 ///   ::= '(' ArgTypeListI ')'
01306 /// ArgTypeListI
01307 ///   ::= /*empty*/
01308 ///   ::= '...'
01309 ///   ::= ArgTypeList ',' '...'
01310 ///   ::= ArgType (',' ArgType)*
01311 ///
01312 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
01313                                  bool &isVarArg, bool inType) {
01314   isVarArg = false;
01315   assert(Lex.getKind() == lltok::lparen);
01316   Lex.Lex(); // eat the (.
01317   
01318   if (Lex.getKind() == lltok::rparen) {
01319     // empty
01320   } else if (Lex.getKind() == lltok::dotdotdot) {
01321     isVarArg = true;
01322     Lex.Lex();
01323   } else {
01324     LocTy TypeLoc = Lex.getLoc();
01325     PATypeHolder ArgTy(Type::getVoidTy(Context));
01326     unsigned Attrs;
01327     std::string Name;
01328     
01329     // If we're parsing a type, use ParseTypeRec, because we allow recursive
01330     // types (such as a function returning a pointer to itself).  If parsing a
01331     // function prototype, we require fully resolved types.
01332     if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
01333         ParseOptionalAttrs(Attrs, 0)) return true;
01334     
01335     if (ArgTy == Type::getVoidTy(Context))
01336       return Error(TypeLoc, "argument can not have void type");
01337     
01338     if (Lex.getKind() == lltok::LocalVar ||
01339         Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
01340       Name = Lex.getStrVal();
01341       Lex.Lex();
01342     }
01343 
01344     if (!FunctionType::isValidArgumentType(ArgTy))
01345       return Error(TypeLoc, "invalid type for function argument");
01346     
01347     ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
01348     
01349     while (EatIfPresent(lltok::comma)) {
01350       // Handle ... at end of arg list.
01351       if (EatIfPresent(lltok::dotdotdot)) {
01352         isVarArg = true;
01353         break;
01354       }
01355       
01356       // Otherwise must be an argument type.
01357       TypeLoc = Lex.getLoc();
01358       if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
01359           ParseOptionalAttrs(Attrs, 0)) return true;
01360 
01361       if (ArgTy == Type::getVoidTy(Context))
01362         return Error(TypeLoc, "argument can not have void type");
01363 
01364       if (Lex.getKind() == lltok::LocalVar ||
01365           Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
01366         Name = Lex.getStrVal();
01367         Lex.Lex();
01368       } else {
01369         Name = "";
01370       }
01371 
01372       if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
01373         return Error(TypeLoc, "invalid type for function argument");
01374       
01375       ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
01376     }
01377   }
01378   
01379   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
01380 }
01381   
01382 /// ParseFunctionType
01383 ///  ::= Type ArgumentList OptionalAttrs
01384 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
01385   assert(Lex.getKind() == lltok::lparen);
01386 
01387   if (!FunctionType::isValidReturnType(Result))
01388     return TokError("invalid function return type");
01389   
01390   std::vector<ArgInfo> ArgList;
01391   bool isVarArg;
01392   unsigned Attrs;
01393   if (ParseArgumentList(ArgList, isVarArg, true) ||
01394       // FIXME: Allow, but ignore attributes on function types!
01395       // FIXME: Remove in LLVM 3.0
01396       ParseOptionalAttrs(Attrs, 2))
01397     return true;
01398   
01399   // Reject names on the arguments lists.
01400   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
01401     if (!ArgList[i].Name.empty())
01402       return Error(ArgList[i].Loc, "argument name invalid in function type");
01403     if (!ArgList[i].Attrs != 0) {
01404       // Allow but ignore attributes on function types; this permits
01405       // auto-upgrade.
01406       // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
01407     }
01408   }
01409   
01410   std::vector<const Type*> ArgListTy;
01411   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
01412     ArgListTy.push_back(ArgList[i].Type);
01413     
01414   Result = HandleUpRefs(FunctionType::get(Result.get(),
01415                                                 ArgListTy, isVarArg));
01416   return false;
01417 }
01418 
01419 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
01420 ///   TypeRec
01421 ///     ::= '{' '}'
01422 ///     ::= '{' TypeRec (',' TypeRec)* '}'
01423 ///     ::= '<' '{' '}' '>'
01424 ///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
01425 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
01426   assert(Lex.getKind() == lltok::lbrace);
01427   Lex.Lex(); // Consume the '{'
01428   
01429   if (EatIfPresent(lltok::rbrace)) {
01430     Result = StructType::get(Context, Packed);
01431     return false;
01432   }
01433 
01434   std::vector<PATypeHolder> ParamsList;
01435   LocTy EltTyLoc = Lex.getLoc();
01436   if (ParseTypeRec(Result)) return true;
01437   ParamsList.push_back(Result);
01438   
01439   if (Result == Type::getVoidTy(Context))
01440     return Error(EltTyLoc, "struct element can not have void type");
01441   if (!StructType::isValidElementType(Result))
01442     return Error(EltTyLoc, "invalid element type for struct");
01443   
01444   while (EatIfPresent(lltok::comma)) {
01445     EltTyLoc = Lex.getLoc();
01446     if (ParseTypeRec(Result)) return true;
01447     
01448     if (Result == Type::getVoidTy(Context))
01449       return Error(EltTyLoc, "struct element can not have void type");
01450     if (!StructType::isValidElementType(Result))
01451       return Error(EltTyLoc, "invalid element type for struct");
01452     
01453     ParamsList.push_back(Result);
01454   }
01455   
01456   if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
01457     return true;
01458   
01459   std::vector<const Type*> ParamsListTy;
01460   for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
01461     ParamsListTy.push_back(ParamsList[i].get());
01462   Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
01463   return false;
01464 }
01465 
01466 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
01467 /// token has already been consumed.
01468 ///   TypeRec 
01469 ///     ::= '[' APSINTVAL 'x' Types ']'
01470 ///     ::= '<' APSINTVAL 'x' Types '>'
01471 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
01472   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
01473       Lex.getAPSIntVal().getBitWidth() > 64)
01474     return TokError("expected number in address space");
01475   
01476   LocTy SizeLoc = Lex.getLoc();
01477   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
01478   Lex.Lex();
01479       
01480   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
01481       return true;
01482 
01483   LocTy TypeLoc = Lex.getLoc();
01484   PATypeHolder EltTy(Type::getVoidTy(Context));
01485   if (ParseTypeRec(EltTy)) return true;
01486   
01487   if (EltTy == Type::getVoidTy(Context))
01488     return Error(TypeLoc, "array and vector element type cannot be void");
01489 
01490   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
01491                  "expected end of sequential type"))
01492     return true;
01493   
01494   if (isVector) {
01495     if (Size == 0)
01496       return Error(SizeLoc, "zero element vector is illegal");
01497     if ((unsigned)Size != Size)
01498       return Error(SizeLoc, "size too large for vector");
01499     if (!VectorType::isValidElementType(EltTy))
01500       return Error(TypeLoc, "vector element type must be fp or integer");
01501     Result = VectorType::get(EltTy, unsigned(Size));
01502   } else {
01503     if (!ArrayType::isValidElementType(EltTy))
01504       return Error(TypeLoc, "invalid array element type");
01505     Result = HandleUpRefs(ArrayType::get(EltTy, Size));
01506   }
01507   return false;
01508 }
01509 
01510 //===----------------------------------------------------------------------===//
01511 // Function Semantic Analysis.
01512 //===----------------------------------------------------------------------===//
01513 
01514 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
01515   : P(p), F(f) {
01516 
01517   // Insert unnamed arguments into the NumberedVals list.
01518   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
01519        AI != E; ++AI)
01520     if (!AI->hasName())
01521       NumberedVals.push_back(AI);
01522 }
01523 
01524 LLParser::PerFunctionState::~PerFunctionState() {
01525   // If there were any forward referenced non-basicblock values, delete them.
01526   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
01527        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
01528     if (!isa<BasicBlock>(I->second.first)) {
01529       I->second.first->replaceAllUsesWith(
01530                            UndefValue::get(I->second.first->getType()));
01531       delete I->second.first;
01532       I->second.first = 0;
01533     }
01534   
01535   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
01536        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
01537     if (!isa<BasicBlock>(I->second.first)) {
01538       I->second.first->replaceAllUsesWith(
01539                            UndefValue::get(I->second.first->getType()));
01540       delete I->second.first;
01541       I->second.first = 0;
01542     }
01543 }
01544 
01545 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
01546   if (!ForwardRefVals.empty())
01547     return P.Error(ForwardRefVals.begin()->second.second,
01548                    "use of undefined value '%" + ForwardRefVals.begin()->first +
01549                    "'");
01550   if (!ForwardRefValIDs.empty())
01551     return P.Error(ForwardRefValIDs.begin()->second.second,
01552                    "use of undefined value '%" +
01553                    utostr(ForwardRefValIDs.begin()->first) + "'");
01554   return false;
01555 }
01556 
01557 
01558 /// GetVal - Get a value with the specified name or ID, creating a
01559 /// forward reference record if needed.  This can return null if the value
01560 /// exists but does not have the right type.
01561 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
01562                                           const Type *Ty, LocTy Loc) {
01563   // Look this name up in the normal function symbol table.
01564   Value *Val = F.getValueSymbolTable().lookup(Name);
01565   
01566   // If this is a forward reference for the value, see if we already created a
01567   // forward ref record.
01568   if (Val == 0) {
01569     std::map<std::string, std::pair<Value*, LocTy> >::iterator
01570       I = ForwardRefVals.find(Name);
01571     if (I != ForwardRefVals.end())
01572       Val = I->second.first;
01573   }
01574     
01575   // If we have the value in the symbol table or fwd-ref table, return it.
01576   if (Val) {
01577     if (Val->getType() == Ty) return Val;
01578     if (Ty == Type::getLabelTy(F.getContext()))
01579       P.Error(Loc, "'%" + Name + "' is not a basic block");
01580     else
01581       P.Error(Loc, "'%" + Name + "' defined with type '" +
01582               Val->getType()->getDescription() + "'");
01583     return 0;
01584   }
01585   
01586   // Don't make placeholders with invalid type.
01587   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
01588       Ty != Type::getLabelTy(F.getContext())) {
01589     P.Error(Loc, "invalid use of a non-first-class type");
01590     return 0;
01591   }
01592   
01593   // Otherwise, create a new forward reference for this value and remember it.
01594   Value *FwdVal;
01595   if (Ty == Type::getLabelTy(F.getContext())) 
01596     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
01597   else
01598     FwdVal = new Argument(Ty, Name);
01599   
01600   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
01601   return FwdVal;
01602 }
01603 
01604 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
01605                                           LocTy Loc) {
01606   // Look this name up in the normal function symbol table.
01607   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
01608   
01609   // If this is a forward reference for the value, see if we already created a
01610   // forward ref record.
01611   if (Val == 0) {
01612     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
01613       I = ForwardRefValIDs.find(ID);
01614     if (I != ForwardRefValIDs.end())
01615       Val = I->second.first;
01616   }
01617   
01618   // If we have the value in the symbol table or fwd-ref table, return it.
01619   if (Val) {
01620     if (Val->getType() == Ty) return Val;
01621     if (Ty == Type::getLabelTy(F.getContext()))
01622       P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
01623     else
01624       P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
01625               Val->getType()->getDescription() + "'");
01626     return 0;
01627   }
01628   
01629   if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
01630       Ty != Type::getLabelTy(F.getContext())) {
01631     P.Error(Loc, "invalid use of a non-first-class type");
01632     return 0;
01633   }
01634   
01635   // Otherwise, create a new forward reference for this value and remember it.
01636   Value *FwdVal;
01637   if (Ty == Type::getLabelTy(F.getContext())) 
01638     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
01639   else
01640     FwdVal = new Argument(Ty);
01641   
01642   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
01643   return FwdVal;
01644 }
01645 
01646 /// SetInstName - After an instruction is parsed and inserted into its
01647 /// basic block, this installs its name.
01648 bool LLParser::PerFunctionState::SetInstName(int NameID,
01649                                              const std::string &NameStr,
01650                                              LocTy NameLoc, Instruction *Inst) {
01651   // If this instruction has void type, it cannot have a name or ID specified.
01652   if (Inst->getType() == Type::getVoidTy(F.getContext())) {
01653     if (NameID != -1 || !NameStr.empty())
01654       return P.Error(NameLoc, "instructions returning void cannot have a name");
01655     return false;
01656   }
01657   
01658   // If this was a numbered instruction, verify that the instruction is the
01659   // expected value and resolve any forward references.
01660   if (NameStr.empty()) {
01661     // If neither a name nor an ID was specified, just use the next ID.
01662     if (NameID == -1)
01663       NameID = NumberedVals.size();
01664     
01665     if (unsigned(NameID) != NumberedVals.size())
01666       return P.Error(NameLoc, "instruction expected to be numbered '%" +
01667                      utostr(NumberedVals.size()) + "'");
01668     
01669     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
01670       ForwardRefValIDs.find(NameID);
01671     if (FI != ForwardRefValIDs.end()) {
01672       if (FI->second.first->getType() != Inst->getType())
01673         return P.Error(NameLoc, "instruction forward referenced with type '" + 
01674                        FI->second.first->getType()->getDescription() + "'");
01675       FI->second.first->replaceAllUsesWith(Inst);
01676       ForwardRefValIDs.erase(FI);
01677     }
01678 
01679     NumberedVals.push_back(Inst);
01680     return false;
01681   }
01682 
01683   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
01684   std::map<std::string, std::pair<Value*, LocTy> >::iterator
01685     FI = ForwardRefVals.find(NameStr);
01686   if (FI != ForwardRefVals.end()) {
01687     if (FI->second.first->getType() != Inst->getType())
01688       return P.Error(NameLoc, "instruction forward referenced with type '" + 
01689                      FI->second.first->getType()->getDescription() + "'");
01690     FI->second.first->replaceAllUsesWith(Inst);
01691     ForwardRefVals.erase(FI);
01692   }
01693   
01694   // Set the name on the instruction.
01695   Inst->setName(NameStr);
01696   
01697   if (Inst->getNameStr() != NameStr)
01698     return P.Error(NameLoc, "multiple definition of local value named '" + 
01699                    NameStr + "'");
01700   return false;
01701 }
01702 
01703 /// GetBB - Get a basic block with the specified name or ID, creating a
01704 /// forward reference record if needed.
01705 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
01706                                               LocTy Loc) {
01707   return cast_or_null<BasicBlock>(GetVal(Name,
01708                                         Type::getLabelTy(F.getContext()), Loc));
01709 }
01710 
01711 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
01712   return cast_or_null<BasicBlock>(GetVal(ID,
01713                                         Type::getLabelTy(F.getContext()), Loc));
01714 }
01715 
01716 /// DefineBB - Define the specified basic block, which is either named or
01717 /// unnamed.  If there is an error, this returns null otherwise it returns
01718 /// the block being defined.
01719 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
01720                                                  LocTy Loc) {
01721   BasicBlock *BB;
01722   if (Name.empty())
01723     BB = GetBB(NumberedVals.size(), Loc);
01724   else
01725     BB = GetBB(Name, Loc);
01726   if (BB == 0) return 0; // Already diagnosed error.
01727   
01728   // Move the block to the end of the function.  Forward ref'd blocks are
01729   // inserted wherever they happen to be referenced.
01730   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
01731   
01732   // Remove the block from forward ref sets.
01733   if (Name.empty()) {
01734     ForwardRefValIDs.erase(NumberedVals.size());
01735     NumberedVals.push_back(BB);
01736   } else {
01737     // BB forward references are already in the function symbol table.
01738     ForwardRefVals.erase(Name);
01739   }
01740   
01741   return BB;
01742 }
01743 
01744 //===----------------------------------------------------------------------===//
01745 // Constants.
01746 //===----------------------------------------------------------------------===//
01747 
01748 /// ParseValID - Parse an abstract value that doesn't necessarily have a
01749 /// type implied.  For example, if we parse "4" we don't know what integer type
01750 /// it has.  The value will later be combined with its type and checked for
01751 /// sanity.
01752 bool LLParser::ParseValID(ValID &ID) {
01753   ID.Loc = Lex.getLoc();
01754   switch (Lex.getKind()) {
01755   default: return TokError("expected value token");
01756   case lltok::GlobalID:  // @42
01757     ID.UIntVal = Lex.getUIntVal();
01758     ID.Kind = ValID::t_GlobalID;
01759     break;
01760   case lltok::GlobalVar:  // @foo
01761     ID.StrVal = Lex.getStrVal();
01762     ID.Kind = ValID::t_GlobalName;
01763     break;
01764   case lltok::LocalVarID:  // %42
01765     ID.UIntVal = Lex.getUIntVal();
01766     ID.Kind = ValID::t_LocalID;
01767     break;
01768   case lltok::LocalVar:  // %foo
01769   case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
01770     ID.StrVal = Lex.getStrVal();
01771     ID.Kind = ValID::t_LocalName;
01772     break;
01773   case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
01774     ID.Kind = ValID::t_Metadata;
01775     Lex.Lex();
01776     if (Lex.getKind() == lltok::lbrace) {
01777       SmallVector<Value*, 16> Elts;
01778       if (ParseMDNodeVector(Elts) ||
01779           ParseToken(lltok::rbrace, "expected end of metadata node"))
01780         return true;
01781 
01782       ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
01783       return false;
01784     }
01785 
01786     // Standalone metadata reference
01787     // !{ ..., !42, ... }
01788     if (!ParseMDNode(ID.MetadataVal))
01789       return false;
01790 
01791     // MDString:
01792     //   ::= '!' STRINGCONSTANT
01793     if (ParseMDString(ID.MetadataVal)) return true;
01794     ID.Kind = ValID::t_Metadata;
01795     return false;
01796   }
01797   case lltok::APSInt:
01798     ID.APSIntVal = Lex.getAPSIntVal(); 
01799     ID.Kind = ValID::t_APSInt;
01800     break;
01801   case lltok::APFloat:
01802     ID.APFloatVal = Lex.getAPFloatVal();
01803     ID.Kind = ValID::t_APFloat;
01804     break;
01805   case lltok::kw_true:
01806     ID.ConstantVal = ConstantInt::getTrue(Context);
01807     ID.Kind = ValID::t_Constant;
01808     break;
01809   case lltok::kw_false:
01810     ID.ConstantVal = ConstantInt::getFalse(Context);
01811     ID.Kind = ValID::t_Constant;
01812     break;
01813   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
01814   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
01815   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
01816       
01817   case lltok::lbrace: {
01818     // ValID ::= '{' ConstVector '}'
01819     Lex.Lex();
01820     SmallVector<Constant*, 16> Elts;
01821     if (ParseGlobalValueVector(Elts) ||
01822         ParseToken(lltok::rbrace, "expected end of struct constant"))
01823       return true;
01824     
01825     ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
01826                                          Elts.size(), false);
01827     ID.Kind = ValID::t_Constant;
01828     return false;
01829   }
01830   case lltok::less: {
01831     // ValID ::= '<' ConstVector '>'         --> Vector.
01832     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
01833     Lex.Lex();
01834     bool isPackedStruct = EatIfPresent(lltok::lbrace);
01835     
01836     SmallVector<Constant*, 16> Elts;
01837     LocTy FirstEltLoc = Lex.getLoc();
01838     if (ParseGlobalValueVector(Elts) ||
01839         (isPackedStruct &&
01840          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
01841         ParseToken(lltok::greater, "expected end of constant"))
01842       return true;
01843     
01844     if (isPackedStruct) {
01845       ID.ConstantVal =
01846         ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
01847       ID.Kind = ValID::t_Constant;
01848       return false;
01849     }
01850     
01851     if (Elts.empty())
01852       return Error(ID.Loc, "constant vector must not be empty");
01853 
01854     if (!Elts[0]->getType()->isInteger() &&
01855         !Elts[0]->getType()->isFloatingPoint())
01856       return Error(FirstEltLoc,
01857                    "vector elements must have integer or floating point type");
01858     
01859     // Verify that all the vector elements have the same type.
01860     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
01861       if (Elts[i]->getType() != Elts[0]->getType())
01862         return Error(FirstEltLoc,
01863                      "vector element #" + utostr(i) +
01864                     " is not of type '" + Elts[0]->getType()->getDescription());
01865     
01866     ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
01867     ID.Kind = ValID::t_Constant;
01868     return false;
01869   }
01870   case lltok::lsquare: {   // Array Constant
01871     Lex.Lex();
01872     SmallVector<Constant*, 16> Elts;
01873     LocTy FirstEltLoc = Lex.getLoc();
01874     if (ParseGlobalValueVector(Elts) ||
01875         ParseToken(lltok::rsquare, "expected end of array constant"))
01876       return true;
01877 
01878     // Handle empty element.
01879     if (Elts.empty()) {
01880       // Use undef instead of an array because it's inconvenient to determine
01881       // the element type at this point, there being no elements to examine.
01882       ID.Kind = ValID::t_EmptyArray;
01883       return false;
01884     }
01885     
01886     if (!Elts[0]->getType()->isFirstClassType())
01887       return Error(FirstEltLoc, "invalid array element type: " + 
01888                    Elts[0]->getType()->getDescription());
01889           
01890     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
01891     
01892     // Verify all elements are correct type!
01893     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
01894       if (Elts[i]->getType() != Elts[0]->getType())
01895         return Error(FirstEltLoc,
01896                      "array element #" + utostr(i) +
01897                      " is not of type '" +Elts[0]->getType()->getDescription());
01898     }
01899     
01900     ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
01901     ID.Kind = ValID::t_Constant;
01902     return false;
01903   }
01904   case lltok::kw_c:  // c "foo"
01905     Lex.Lex();
01906     ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
01907     if (ParseToken(lltok::StringConstant, "expected string")) return true;
01908     ID.Kind = ValID::t_Constant;
01909     return false;
01910 
01911   case lltok::kw_asm: {
01912     // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
01913     bool HasSideEffect;
01914     Lex.Lex();
01915     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
01916         ParseStringConstant(ID.StrVal) ||
01917         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
01918         ParseToken(lltok::StringConstant, "expected constraint string"))
01919       return true;
01920     ID.StrVal2 = Lex.getStrVal();
01921     ID.UIntVal = HasSideEffect;
01922     ID.Kind = ValID::t_InlineAsm;
01923     return false;
01924   }
01925       
01926   case lltok::kw_trunc:
01927   case lltok::kw_zext:
01928   case lltok::kw_sext:
01929   case lltok::kw_fptrunc:
01930   case lltok::kw_fpext:
01931   case lltok::kw_bitcast:
01932   case lltok::kw_uitofp:
01933   case lltok::kw_sitofp:
01934   case lltok::kw_fptoui:
01935   case lltok::kw_fptosi: 
01936   case lltok::kw_inttoptr:
01937   case lltok::kw_ptrtoint: { 
01938     unsigned Opc = Lex.getUIntVal();
01939     PATypeHolder DestTy(Type::getVoidTy(Context));
01940     Constant *SrcVal;
01941     Lex.Lex();
01942     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
01943         ParseGlobalTypeAndValue(SrcVal) ||
01944         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
01945         ParseType(DestTy) ||
01946         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
01947       return true;
01948     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
01949       return Error(ID.Loc, "invalid cast opcode for cast from '" +
01950                    SrcVal->getType()->getDescription() + "' to '" +
01951                    DestTy->getDescription() + "'");
01952     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 
01953                                                  SrcVal, DestTy);
01954     ID.Kind = ValID::t_Constant;
01955     return false;
01956   }
01957   case lltok::kw_extractvalue: {
01958     Lex.Lex();
01959     Constant *Val;
01960     SmallVector<unsigned, 4> Indices;
01961     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
01962         ParseGlobalTypeAndValue(Val) ||
01963         ParseIndexList(Indices) ||
01964         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
01965       return true;
01966     if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
01967       return Error(ID.Loc, "extractvalue operand must be array or struct");
01968     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
01969                                           Indices.end()))
01970       return Error(ID.Loc, "invalid indices for extractvalue");
01971     ID.ConstantVal =
01972       ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
01973     ID.Kind = ValID::t_Constant;
01974     return false;
01975   }
01976   case lltok::kw_insertvalue: {
01977     Lex.Lex();
01978     Constant *Val0, *Val1;
01979     SmallVector<unsigned, 4> Indices;
01980     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
01981         ParseGlobalTypeAndValue(Val0) ||
01982         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
01983         ParseGlobalTypeAndValue(Val1) ||
01984         ParseIndexList(Indices) ||
01985         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
01986       return true;
01987     if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
01988       return Error(ID.Loc, "extractvalue operand must be array or struct");
01989     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
01990                                           Indices.end()))
01991       return Error(ID.Loc, "invalid indices for insertvalue");
01992     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
01993                        Indices.data(), Indices.size());
01994     ID.Kind = ValID::t_Constant;
01995     return false;
01996   }
01997   case lltok::kw_icmp:
01998   case lltok::kw_fcmp: {
01999     unsigned PredVal, Opc = Lex.getUIntVal();
02000     Constant *Val0, *Val1;
02001     Lex.Lex();
02002     if (ParseCmpPredicate(PredVal, Opc) ||
02003         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
02004         ParseGlobalTypeAndValue(Val0) ||
02005         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
02006         ParseGlobalTypeAndValue(Val1) ||
02007         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
02008       return true;
02009     
02010     if (Val0->getType() != Val1->getType())
02011       return Error(ID.Loc, "compare operands must have the same type");
02012     
02013     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
02014     
02015     if (Opc == Instruction::FCmp) {
02016       if (!Val0->getType()->isFPOrFPVector())
02017         return Error(ID.Loc, "fcmp requires floating point operands");
02018       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
02019     } else {
02020       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
02021       if (!Val0->getType()->isIntOrIntVector() &&
02022           !isa<PointerType>(Val0->getType()))
02023         return Error(ID.Loc, "icmp requires pointer or integer operands");
02024       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
02025     }
02026     ID.Kind = ValID::t_Constant;
02027     return false;
02028   }
02029       
02030   // Binary Operators.
02031   case lltok::kw_add:
02032   case lltok::kw_fadd:
02033   case lltok::kw_sub:
02034   case lltok::kw_fsub:
02035   case lltok::kw_mul:
02036   case lltok::kw_fmul:
02037   case lltok::kw_udiv:
02038   case lltok::kw_sdiv:
02039   case lltok::kw_fdiv:
02040   case lltok::kw_urem:
02041   case lltok::kw_srem:
02042   case lltok::kw_frem: {
02043     bool NUW = false;
02044     bool NSW = false;
02045     bool Exact = false;
02046     unsigned Opc = Lex.getUIntVal();
02047     Constant *Val0, *Val1;
02048     Lex.Lex();
02049     LocTy ModifierLoc = Lex.getLoc();
02050     if (Opc == Instruction::Add ||
02051         Opc == Instruction::Sub ||
02052         Opc == Instruction::Mul) {
02053       if (EatIfPresent(lltok::kw_nuw))
02054         NUW = true;
02055       if (EatIfPresent(lltok::kw_nsw)) {
02056         NSW = true;
02057         if (EatIfPresent(lltok::kw_nuw))
02058           NUW = true;
02059       }
02060     } else if (Opc == Instruction::SDiv) {
02061       if (EatIfPresent(lltok::kw_exact))
02062         Exact = true;
02063     }
02064     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
02065         ParseGlobalTypeAndValue(Val0) ||
02066         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
02067         ParseGlobalTypeAndValue(Val1) ||
02068         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
02069       return true;
02070     if (Val0->getType() != Val1->getType())
02071       return Error(ID.Loc, "operands of constexpr must have same type");
02072     if (!Val0->getType()->isIntOrIntVector()) {
02073       if (NUW)
02074         return Error(ModifierLoc, "nuw only applies to integer operations");
02075       if (NSW)
02076         return Error(ModifierLoc, "nsw only applies to integer operations");
02077     }
02078     // API compatibility: Accept either integer or floating-point types with
02079     // add, sub, and mul.
02080     if (!Val0->getType()->isIntOrIntVector() &&
02081         !Val0->getType()->isFPOrFPVector())
02082       return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
02083     Constant *C = ConstantExpr::get(Opc, Val0, Val1);
02084     if (NUW)
02085       cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedWrap(true);
02086     if (NSW)
02087       cast<OverflowingBinaryOperator>(C)->setHasNoSignedWrap(true);
02088     if (Exact)
02089       cast<SDivOperator>(C)->setIsExact(true);
02090     ID.ConstantVal = C;
02091     ID.Kind = ValID::t_Constant;
02092     return false;
02093   }
02094       
02095   // Logical Operations
02096   case lltok::kw_shl:
02097   case lltok::kw_lshr:
02098   case lltok::kw_ashr:
02099   case lltok::kw_and:
02100   case lltok::kw_or:
02101   case lltok::kw_xor: {
02102     unsigned Opc = Lex.getUIntVal();
02103     Constant *Val0, *Val1;
02104     Lex.Lex();
02105     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
02106         ParseGlobalTypeAndValue(Val0) ||
02107         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
02108         ParseGlobalTypeAndValue(Val1) ||
02109         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
02110       return true;
02111     if (Val0->getType() != Val1->getType())
02112       return Error(ID.Loc, "operands of constexpr must have same type");
02113     if (!Val0->getType()->isIntOrIntVector())
02114       return Error(ID.Loc,
02115                    "constexpr requires integer or integer vector operands");
02116     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
02117     ID.Kind = ValID::t_Constant;
02118     return false;
02119   }  
02120       
02121   case lltok::kw_getelementptr:
02122   case lltok::kw_shufflevector:
02123   case lltok::kw_insertelement:
02124   case lltok::kw_extractelement:
02125   case lltok::kw_select: {
02126     unsigned Opc = Lex.getUIntVal();
02127     SmallVector<Constant*, 16> Elts;
02128     bool InBounds = false;
02129     Lex.Lex();
02130     if (Opc == Instruction::GetElementPtr)
02131       InBounds = EatIfPresent(lltok::kw_inbounds);
02132     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
02133         ParseGlobalValueVector(Elts) ||
02134         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
02135       return true;
02136     
02137     if (Opc == Instruction::GetElementPtr) {
02138       if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
02139         return Error(ID.Loc, "getelementptr requires pointer operand");
02140       
02141       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
02142                                              (Value**)(Elts.data() + 1),
02143                                              Elts.size() - 1))
02144         return Error(ID.Loc, "invalid indices for getelementptr");
02145       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
02146                                               Elts.data() + 1, Elts.size() - 1);
02147       if (InBounds)
02148         cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
02149     } else if (Opc == Instruction::Select) {
02150       if (Elts.size() != 3)
02151         return Error(ID.Loc, "expected three operands to select");
02152       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
02153                                                               Elts[2]))
02154         return Error(ID.Loc, Reason);
02155       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
02156     } else if (Opc == Instruction::ShuffleVector) {
02157       if (Elts.size() != 3)
02158         return Error(ID.Loc, "expected three operands to shufflevector");
02159       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
02160         return Error(ID.Loc, "invalid operands to shufflevector");
02161       ID.ConstantVal =
02162                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
02163     } else if (Opc == Instruction::ExtractElement) {
02164       if (Elts.size() != 2)
02165         return Error(ID.Loc, "expected two operands to extractelement");
02166       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
02167         return Error(ID.Loc, "invalid extractelement operands");
02168       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
02169     } else {
02170       assert(Opc == Instruction::InsertElement && "Unknown opcode");
02171       if (Elts.size() != 3)
02172       return Error(ID.Loc, "expected three operands to insertelement");
02173       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
02174         return Error(ID.Loc, "invalid insertelement operands");
02175       ID.ConstantVal =
02176                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
02177     }
02178     
02179     ID.Kind = ValID::t_Constant;
02180     return false;
02181   }
02182   }
02183   
02184   Lex.Lex();
02185   return false;
02186 }
02187 
02188 /// ParseGlobalValue - Parse a global value with the specified type.
02189 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
02190   V = 0;
02191   ValID ID;
02192   return ParseValID(ID) ||
02193          ConvertGlobalValIDToValue(Ty, ID, V);
02194 }
02195 
02196 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
02197 /// constant.
02198 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
02199                                          Constant *&V) {
02200   if (isa<FunctionType>(Ty))
02201     return Error(ID.Loc, "functions are not values, refer to them as pointers");
02202   
02203   switch (ID.Kind) {
02204   default: llvm_unreachable("Unknown ValID!");    
02205   case ValID::t_Metadata:
02206     return Error(ID.Loc, "invalid use of metadata");
02207   case ValID::t_LocalID:
02208   case ValID::t_LocalName:
02209     return Error(ID.Loc, "invalid use of function-local name");
02210   case ValID::t_InlineAsm:
02211     return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
02212   case ValID::t_GlobalName:
02213     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
02214     return V == 0;
02215   case ValID::t_GlobalID:
02216     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
02217     return V == 0;
02218   case ValID::t_APSInt:
02219     if (!isa<IntegerType>(Ty))
02220       return Error(ID.Loc, "integer constant must have integer type");
02221     ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
02222     V = ConstantInt::get(Context, ID.APSIntVal);
02223     return false;
02224   case ValID::t_APFloat:
02225     if (!Ty->isFloatingPoint() ||
02226         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
02227       return Error(ID.Loc, "floating point constant invalid for type");
02228       
02229     // The lexer has no type info, so builds all float and double FP constants
02230     // as double.  Fix this here.  Long double does not need this.
02231     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
02232         Ty == Type::getFloatTy(Context)) {
02233       bool Ignored;
02234       ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
02235                             &Ignored);
02236     }
02237     V = ConstantFP::get(Context, ID.APFloatVal);
02238       
02239     if (V->getType() != Ty)
02240       return Error(ID.Loc, "floating point constant does not have type '" +
02241                    Ty->getDescription() + "'");
02242       
02243     return false;
02244   case ValID::t_Null:
02245     if (!isa<PointerType>(Ty))
02246       return Error(ID.Loc, "null must be a pointer type");
02247     V = ConstantPointerNull::get(cast<PointerType>(Ty));
02248     return false;
02249   case ValID::t_Undef:
02250     // FIXME: LabelTy should not be a first-class type.
02251     if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
02252         !isa<OpaqueType>(Ty))
02253       return Error(ID.Loc, "invalid type for undef constant");
02254     V = UndefValue::get(Ty);
02255     return false;
02256   case ValID::t_EmptyArray:
02257     if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
02258       return Error(ID.Loc, "invalid empty array initializer");
02259     V = UndefValue::get(Ty);
02260     return false;
02261   case ValID::t_Zero:
02262     // FIXME: LabelTy should not be a first-class type.
02263     if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
02264       return Error(ID.Loc, "invalid type for null constant");
02265     V = Constant::getNullValue(Ty);
02266     return false;
02267   case ValID::t_Constant:
02268     if (ID.ConstantVal->getType() != Ty)
02269       return Error(ID.Loc, "constant expression type mismatch");
02270     V = ID.ConstantVal;
02271     return false;
02272   }
02273 }
02274   
02275 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
02276   PATypeHolder Type(Type::getVoidTy(Context));
02277   return ParseType(Type) ||
02278          ParseGlobalValue(Type, V);
02279 }    
02280 
02281 /// ParseGlobalValueVector
02282 ///   ::= /*empty*/
02283 ///   ::= TypeAndValue (',' TypeAndValue)*
02284 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
02285   // Empty list.
02286   if (Lex.getKind() == lltok::rbrace ||
02287       Lex.getKind() == lltok::rsquare ||
02288       Lex.getKind() == lltok::greater ||
02289       Lex.getKind() == lltok::rparen)
02290     return false;
02291   
02292   Constant *C;
02293   if (ParseGlobalTypeAndValue(C)) return true;
02294   Elts.push_back(C);
02295   
02296   while (EatIfPresent(lltok::comma)) {
02297     if (ParseGlobalTypeAndValue(C)) return true;
02298     Elts.push_back(C);
02299   }
02300   
02301   return false;
02302 }
02303 
02304 
02305 //===----------------------------------------------------------------------===//
02306 // Function Parsing.
02307 //===----------------------------------------------------------------------===//
02308 
02309 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
02310                                    PerFunctionState &PFS) {
02311   if (ID.Kind == ValID::t_LocalID)
02312     V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
02313   else if (ID.Kind == ValID::t_LocalName)
02314     V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
02315   else if (ID.Kind == ValID::t_InlineAsm) {
02316     const PointerType *PTy = dyn_cast<PointerType>(Ty);
02317     const FunctionType *FTy =
02318       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
02319     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
02320       return Error(ID.Loc, "invalid type for inline asm constraint string");
02321     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
02322     return false;
02323   } else if (ID.Kind == ValID::t_Metadata) {
02324     V = ID.MetadataVal;
02325   } else {
02326     Constant *C;
02327     if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
02328     V = C;
02329     return false;
02330   }
02331 
02332   return V == 0;
02333 }
02334 
02335 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
02336   V = 0;
02337   ValID ID;
02338   return ParseValID(ID) ||
02339          ConvertValIDToValue(Ty, ID, V, PFS);
02340 }
02341 
02342 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
02343   PATypeHolder T(Type::getVoidTy(Context));
02344   return ParseType(T) ||
02345          ParseValue(T, V, PFS);
02346 }
02347 
02348 /// FunctionHeader
02349 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
02350 ///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
02351 ///       OptionalAlign OptGC
02352 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
02353   // Parse the linkage.
02354   LocTy LinkageLoc = Lex.getLoc();
02355   unsigned Linkage;
02356   
02357   unsigned Visibility, CC, RetAttrs;
02358   PATypeHolder RetType(Type::getVoidTy(Context));
02359   LocTy RetTypeLoc = Lex.getLoc();
02360   if (ParseOptionalLinkage(Linkage) ||
02361       ParseOptionalVisibility(Visibility) ||
02362       ParseOptionalCallingConv(CC) ||
02363       ParseOptionalAttrs(RetAttrs, 1) ||
02364       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
02365     return true;
02366 
02367   // Verify that the linkage is ok.
02368   switch ((GlobalValue::LinkageTypes)Linkage) {
02369   case GlobalValue::ExternalLinkage:
02370     break; // always ok.
02371   case GlobalValue::DLLImportLinkage:
02372   case GlobalValue::ExternalWeakLinkage:
02373     if (isDefine)
02374       return Error(LinkageLoc, "invalid linkage for function definition");
02375     break;
02376   case GlobalValue::PrivateLinkage:
02377   case GlobalValue::LinkerPrivateLinkage:
02378   case GlobalValue::InternalLinkage:
02379   case GlobalValue::AvailableExternallyLinkage:
02380   case GlobalValue::LinkOnceAnyLinkage:
02381   case GlobalValue::LinkOnceODRLinkage:
02382   case GlobalValue::WeakAnyLinkage:
02383   case GlobalValue::WeakODRLinkage:
02384   case GlobalValue::DLLExportLinkage:
02385     if (!isDefine)
02386       return Error(LinkageLoc, "invalid linkage for function declaration");
02387     break;
02388   case GlobalValue::AppendingLinkage:
02389   case GlobalValue::GhostLinkage:
02390   case GlobalValue::CommonLinkage:
02391     return Error(LinkageLoc, "invalid function linkage type");
02392   }
02393   
02394   if (!FunctionType::isValidReturnType(RetType) ||
02395       isa<OpaqueType>(RetType))
02396     return Error(RetTypeLoc, "invalid function return type");
02397   
02398   LocTy NameLoc = Lex.getLoc();
02399 
02400   std::string FunctionName;
02401   if (Lex.getKind() == lltok::GlobalVar) {
02402     FunctionName = Lex.getStrVal();
02403   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
02404     unsigned NameID = Lex.getUIntVal();
02405 
02406     if (NameID != NumberedVals.size())
02407       return TokError("function expected to be numbered '%" +
02408                       utostr(NumberedVals.size()) + "'");
02409   } else {
02410     return TokError("expected function name");
02411   }
02412   
02413   Lex.Lex();
02414   
02415   if (Lex.getKind() != lltok::lparen)
02416     return TokError("expected '(' in function argument list");
02417   
02418   std::vector<ArgInfo> ArgList;
02419   bool isVarArg;
02420   unsigned FuncAttrs;
02421   std::string Section;
02422   unsigned Alignment;
02423   std::string GC;
02424 
02425   if (ParseArgumentList(ArgList, isVarArg, false) ||
02426       ParseOptionalAttrs(FuncAttrs, 2) ||
02427       (EatIfPresent(lltok::kw_section) &&
02428        ParseStringConstant(Section)) ||
02429       ParseOptionalAlignment(Alignment) ||
02430       (EatIfPresent(lltok::kw_gc) &&
02431        ParseStringConstant(GC)))
02432     return true;
02433 
02434   // If the alignment was parsed as an attribute, move to the alignment field.
02435   if (FuncAttrs & Attribute::Alignment) {
02436     Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
02437     FuncAttrs &= ~Attribute::Alignment;
02438   }
02439   
02440   // Okay, if we got here, the function is syntactically valid.  Convert types
02441   // and do semantic checks.
02442   std::vector<const Type*> ParamTypeList;
02443   SmallVector<AttributeWithIndex, 8> Attrs;
02444   // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 
02445   // attributes.
02446   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
02447   if (FuncAttrs & ObsoleteFuncAttrs) {
02448     RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
02449     FuncAttrs &= ~ObsoleteFuncAttrs;
02450   }
02451   
02452   if (RetAttrs != Attribute::None)
02453     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
02454   
02455   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
02456     ParamTypeList.push_back(ArgList[i].Type);
02457     if (ArgList[i].Attrs != Attribute::None)
02458       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
02459   }
02460 
02461   if (FuncAttrs != Attribute::None)
02462     Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
02463 
02464   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
02465   
02466   if (PAL.paramHasAttr(1, Attribute::StructRet) &&
02467       RetType != Type::getVoidTy(Context))
02468     return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 
02469   
02470   const FunctionType *FT =
02471     FunctionType::get(RetType, ParamTypeList, isVarArg);
02472   const PointerType *PFT = PointerType::getUnqual(FT);
02473 
02474   Fn = 0;
02475   if (!FunctionName.empty()) {
02476     // If this was a definition of a forward reference, remove the definition
02477     // from the forward reference table and fill in the forward ref.
02478     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
02479       ForwardRefVals.find(FunctionName);
02480     if (FRVI != ForwardRefVals.end()) {
02481       Fn = M->getFunction(FunctionName);
02482       ForwardRefVals.erase(FRVI);
02483     } else if ((Fn = M->getFunction(FunctionName))) {
02484       // If this function already exists in the symbol table, then it is
02485       // multiply defined.  We accept a few cases for old backwards compat.
02486       // FIXME: Remove this stuff for LLVM 3.0.
02487       if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
02488           (!Fn->isDeclaration() && isDefine)) {
02489         // If the redefinition has different type or different attributes,
02490         // reject it.  If both have bodies, reject it.
02491         return Error(NameLoc, "invalid redefinition of function '" +
02492                      FunctionName + "'");
02493       } else if (Fn->isDeclaration()) {
02494         // Make sure to strip off any argument names so we can't get conflicts.
02495         for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
02496              AI != AE; ++AI)
02497           AI->setName("");
02498       }
02499     }
02500     
02501   } else if (FunctionName.empty()) {
02502     // If this is a definition of a forward referenced function, make sure the
02503     // types agree.
02504     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
02505       = ForwardRefValIDs.find(NumberedVals.size());
02506     if (I != ForwardRefValIDs.end()) {
02507       Fn = cast<Function>(I->second.first);
02508       if (Fn->getType() != PFT)
02509         return Error(NameLoc, "type of definition and forward reference of '@" +
02510                      utostr(NumberedVals.size()) +"' disagree");
02511       ForwardRefValIDs.erase(I);
02512     }
02513   }
02514 
02515   if (Fn == 0)
02516     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
02517   else // Move the forward-reference to the correct spot in the module.
02518     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
02519 
02520   if (FunctionName.empty())
02521     NumberedVals.push_back(Fn);
02522   
02523   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
02524   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
02525   Fn->setCallingConv(CC);
02526   Fn->setAttributes(PAL);
02527   Fn->setAlignment(Alignment);
02528   Fn->setSection(Section);
02529   if (!GC.empty()) Fn->setGC(GC.c_str());
02530     
02531   // Add all of the arguments we parsed to the function.
02532   Function::arg_iterator ArgIt = Fn->arg_begin();
02533   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
02534     // If the argument has a name, insert it into the argument symbol table.
02535     if (ArgList[i].Name.empty()) continue;
02536     
02537     // Set the name, if it conflicted, it will be auto-renamed.
02538     ArgIt->setName(ArgList[i].Name);
02539     
02540     if (ArgIt->getNameStr() != ArgList[i].Name)
02541       return Error(ArgList[i].Loc, "redefinition of argument '%" +
02542                    ArgList[i].Name + "'");
02543   }
02544   
02545   return false;
02546 }
02547 
02548 
02549 /// ParseFunctionBody
02550 ///   ::= '{' BasicBlock+ '}'
02551 ///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
02552 ///
02553 bool LLParser::ParseFunctionBody(Function &Fn) {
02554   if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
02555     return TokError("expected '{' in function body");
02556   Lex.Lex();  // eat the {.
02557   
02558   PerFunctionState PFS(*this, Fn);
02559   
02560   while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
02561     if (ParseBasicBlock(PFS)) return true;
02562   
02563   // Eat the }.
02564   Lex.Lex();
02565   
02566   // Verify function is ok.
02567   return PFS.VerifyFunctionComplete();
02568 }
02569 
02570 /// ParseBasicBlock
02571 ///   ::= LabelStr? Instruction*
02572 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
02573   // If this basic block starts out with a name, remember it.
02574   std::string Name;
02575   LocTy NameLoc = Lex.getLoc();
02576   if (Lex.getKind() == lltok::LabelStr) {
02577     Name = Lex.getStrVal();
02578     Lex.Lex();
02579   }
02580   
02581   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
02582   if (BB == 0) return true;
02583   
02584   std::string NameStr;
02585   
02586   // Parse the instructions in this block until we get a terminator.
02587   Instruction *Inst;
02588   do {
02589     // This instruction may have three possibilities for a name: a) none
02590     // specified, b) name specified "%foo =", c) number specified: "%4 =".
02591     LocTy NameLoc = Lex.getLoc();
02592     int NameID = -1;
02593     NameStr = "";
02594     
02595     if (Lex.getKind() == lltok::LocalVarID) {
02596       NameID = Lex.getUIntVal();
02597       Lex.Lex();
02598       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
02599         return true;
02600     } else if (Lex.getKind() == lltok::LocalVar ||
02601                // FIXME: REMOVE IN LLVM 3.0
02602                Lex.getKind() == lltok::StringConstant) {
02603       NameStr = Lex.getStrVal();
02604       Lex.Lex();
02605       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
02606         return true;
02607     }
02608     
02609     if (ParseInstruction(Inst, BB, PFS)) return true;
02610     
02611     BB->getInstList().push_back(Inst);
02612 
02613     // Set the name on the instruction.
02614     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
02615   } while (!isa<TerminatorInst>(Inst));
02616   
02617   return false;
02618 }
02619 
02620 //===----------------------------------------------------------------------===//
02621 // Instruction Parsing.
02622 //===----------------------------------------------------------------------===//
02623 
02624 /// ParseInstruction - Parse one of the many different instructions.
02625 ///
02626 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
02627                                 PerFunctionState &PFS) {
02628   lltok::Kind Token = Lex.getKind();
02629   if (Token == lltok::Eof)
02630     return TokError("found end of file when expecting more instructions");
02631   LocTy Loc = Lex.getLoc();
02632   unsigned KeywordVal = Lex.getUIntVal();
02633   Lex.Lex();  // Eat the keyword.
02634   
02635   switch (Token) {
02636   default:                    return Error(Loc, "expected instruction opcode");
02637   // Terminator Instructions.
02638   case lltok::kw_unwind:      Inst = new UnwindInst(Context); return false;
02639   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
02640   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
02641   case lltok::kw_br:          return ParseBr(Inst, PFS);
02642   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
02643   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
02644   // Binary Operators.
02645   case lltok::kw_add:
02646   case lltok::kw_sub:
02647   case lltok::kw_mul: {
02648     bool NUW = false;
02649     bool NSW = false;
02650     LocTy ModifierLoc = Lex.getLoc();
02651     if (EatIfPresent(lltok::kw_nuw))
02652       NUW = true;
02653     if (EatIfPresent(lltok::kw_nsw)) {
02654       NSW = true;
02655       if (EatIfPresent(lltok::kw_nuw))
02656         NUW = true;
02657     }
02658     // API compatibility: Accept either integer or floating-point types.
02659     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
02660     if (!Result) {
02661       if (!Inst->getType()->isIntOrIntVector()) {
02662         if (NUW)
02663           return Error(ModifierLoc, "nuw only applies to integer operations");
02664         if (NSW)
02665           return Error(ModifierLoc, "nsw only applies to integer operations");
02666       }
02667       if (NUW)
02668         cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
02669       if (NSW)
02670         cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedWrap(true);
02671     }
02672     return Result;
02673   }
02674   case lltok::kw_fadd:
02675   case lltok::kw_fsub:
02676   case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
02677 
02678   case lltok::kw_sdiv: {
02679     bool Exact = false;
02680     if (EatIfPresent(lltok::kw_exact))
02681       Exact = true;
02682     bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
02683     if (!Result)
02684       if (Exact)
02685         cast<SDivOperator>(Inst)->setIsExact(true);
02686     return Result;
02687   }
02688 
02689   case lltok::kw_udiv:
02690   case lltok::kw_urem:
02691   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
02692   case lltok::kw_fdiv:
02693   case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
02694   case lltok::kw_shl:
02695   case lltok::kw_lshr:
02696   case lltok::kw_ashr:
02697   case lltok::kw_and:
02698   case lltok::kw_or:
02699   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
02700   case lltok::kw_icmp:
02701   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
02702   // Casts.
02703   case lltok::kw_trunc:
02704   case lltok::kw_zext:
02705   case lltok::kw_sext:
02706   case lltok::kw_fptrunc:
02707   case lltok::kw_fpext:
02708   case lltok::kw_bitcast:
02709   case lltok::kw_uitofp:
02710   case lltok::kw_sitofp:
02711   case lltok::kw_fptoui:
02712   case lltok::kw_fptosi: 
02713   case lltok::kw_inttoptr:
02714   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
02715   // Other.
02716   case lltok::kw_select:         return ParseSelect(Inst, PFS);
02717   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
02718   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
02719   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
02720   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
02721   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
02722   case lltok::kw_call:           return ParseCall(Inst, PFS, false);
02723   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
02724   // Memory.
02725   case lltok::kw_alloca:
02726   case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
02727   case lltok::kw_free:           return ParseFree(Inst, PFS);
02728   case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
02729   case lltok::kw_store:          return ParseStore(Inst, PFS, false);
02730   case lltok::kw_volatile:
02731     if (EatIfPresent(lltok::kw_load))
02732       return ParseLoad(Inst, PFS, true);
02733     else if (EatIfPresent(lltok::kw_store))
02734       return ParseStore(Inst, PFS, true);
02735     else
02736       return TokError("expected 'load' or 'store'");
02737   case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
02738   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
02739   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
02740   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
02741   }
02742 }
02743 
02744 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
02745 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
02746   if (Opc == Instruction::FCmp) {
02747     switch (Lex.getKind()) {
02748     default: TokError("expected fcmp predicate (e.g. 'oeq')");
02749     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
02750     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
02751     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
02752     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
02753     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
02754     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
02755     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
02756     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
02757     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
02758     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
02759     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
02760     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
02761     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
02762     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
02763     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
02764     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
02765     }
02766   } else {
02767     switch (Lex.getKind()) {
02768     default: TokError("expected icmp predicate (e.g. 'eq')");
02769     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
02770     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
02771     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
02772     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
02773     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
02774     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
02775     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
02776     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
02777     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
02778     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
02779     }
02780   }
02781   Lex.Lex();
02782   return false;
02783 }
02784 
02785 //===----------------------------------------------------------------------===//
02786 // Terminator Instructions.
02787 //===----------------------------------------------------------------------===//
02788 
02789 /// ParseRet - Parse a return instruction.
02790 ///   ::= 'ret' void
02791 ///   ::= 'ret' TypeAndValue
02792 ///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
02793 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
02794                         PerFunctionState &PFS) {
02795   PATypeHolder Ty(Type::getVoidTy(Context));
02796   if (ParseType(Ty, true /*void allowed*/)) return true;
02797   
02798   if (Ty == Type::getVoidTy(Context)) {
02799     Inst = ReturnInst::Create(Context);
02800     return false;
02801   }
02802   
02803   Value *RV;
02804   if (ParseValue(Ty, RV, PFS)) return true;
02805   
02806   // The normal case is one return value.
02807   if (Lex.getKind() == lltok::comma) {
02808     // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
02809     // of 'ret {i32,i32} {i32 1, i32 2}'
02810     SmallVector<Value*, 8> RVs;
02811     RVs.push_back(RV);
02812     
02813     while (EatIfPresent(lltok::comma)) {
02814       if (ParseTypeAndValue(RV, PFS)) return true;
02815       RVs.push_back(RV);
02816     }
02817 
02818     RV = UndefValue::get(PFS.getFunction().getReturnType());
02819     for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
02820       Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
02821       BB->getInstList().push_back(I);
02822       RV = I;
02823     }
02824   }
02825   Inst = ReturnInst::Create(Context, RV);
02826   return false;
02827 }
02828 
02829 
02830 /// ParseBr
02831 ///   ::= 'br' TypeAndValue
02832 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
02833 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
02834   LocTy Loc, Loc2;
02835   Value *Op0, *Op1, *Op2;
02836   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
02837   
02838   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
02839     Inst = BranchInst::Create(BB);
02840     return false;
02841   }
02842   
02843   if (Op0->getType() != Type::getInt1Ty(Context))
02844     return Error(Loc, "branch condition must have 'i1' type");
02845     
02846   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
02847       ParseTypeAndValue(Op1, Loc, PFS) ||
02848       ParseToken(lltok::comma, "expected ',' after true destination") ||
02849       ParseTypeAndValue(Op2, Loc2, PFS))
02850     return true;
02851   
02852   if (!isa<BasicBlock>(Op1))
02853     return Error(Loc, "true destination of branch must be a basic block");
02854   if (!isa<BasicBlock>(Op2))
02855     return Error(Loc2, "true destination of branch must be a basic block");
02856     
02857   Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
02858   return false;
02859 }
02860 
02861 /// ParseSwitch
02862 ///  Instruction
02863 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
02864 ///  JumpTable
02865 ///    ::= (TypeAndValue ',' TypeAndValue)*
02866 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
02867   LocTy CondLoc, BBLoc;
02868   Value *Cond, *DefaultBB;
02869   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
02870       ParseToken(lltok::comma, "expected ',' after switch condition") ||
02871       ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
02872       ParseToken(lltok::lsquare, "expected '[' with switch table"))
02873     return true;
02874 
02875   if (!isa<IntegerType>(Cond->getType()))
02876     return Error(CondLoc, "switch condition must have integer type");
02877   if (!isa<BasicBlock>(DefaultBB))
02878     return Error(BBLoc, "default destination must be a basic block");
02879   
02880   // Parse the jump table pairs.
02881   SmallPtrSet<Value*, 32> SeenCases;
02882   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
02883   while (Lex.getKind() != lltok::rsquare) {
02884     Value *Constant, *DestBB;
02885     
02886     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
02887         ParseToken(lltok::comma, "expected ',' after case value") ||
02888         ParseTypeAndValue(DestBB, BBLoc, PFS))
02889       return true;
02890 
02891     if (!SeenCases.insert(Constant))
02892       return Error(CondLoc, "duplicate case value in switch");
02893     if (!isa<ConstantInt>(Constant))
02894       return Error(CondLoc, "case value is not a constant integer");
02895     if (!isa<BasicBlock>(DestBB))
02896       return Error(BBLoc, "case destination is not a basic block");
02897     
02898     Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
02899                                    cast<BasicBlock>(DestBB)));
02900   }
02901   
02902   Lex.Lex();  // Eat the ']'.
02903   
02904   SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
02905                                       Table.size());
02906   for (unsigned i = 0, e = Table.size(); i != e; ++i)
02907     SI->addCase(Table[i].first, Table[i].second);
02908   Inst = SI;
02909   return false;
02910 }
02911 
02912 /// ParseInvoke
02913 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
02914 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
02915 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
02916   LocTy CallLoc = Lex.getLoc();
02917   unsigned CC, RetAttrs, FnAttrs;
02918   PATypeHolder RetType(Type::getVoidTy(Context));
02919   LocTy RetTypeLoc;
02920   ValID CalleeID;
02921   SmallVector<ParamInfo, 16> ArgList;
02922 
02923   Value *NormalBB, *UnwindBB;
02924   if (ParseOptionalCallingConv(CC) ||
02925       ParseOptionalAttrs(RetAttrs, 1) ||
02926       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
02927       ParseValID(CalleeID) ||
02928       ParseParameterList(ArgList, PFS) ||
02929       ParseOptionalAttrs(FnAttrs, 2) ||
02930       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
02931       ParseTypeAndValue(NormalBB, PFS) ||
02932       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
02933       ParseTypeAndValue(UnwindBB, PFS))
02934     return true;
02935   
02936   if (!isa<BasicBlock>(NormalBB))
02937     return Error(CallLoc, "normal destination is not a basic block");
02938   if (!isa<BasicBlock>(UnwindBB))
02939     return Error(CallLoc, "unwind destination is not a basic block");
02940   
02941   // If RetType is a non-function pointer type, then this is the short syntax
02942   // for the call, which means that RetType is just the return type.  Infer the
02943   // rest of the function argument types from the arguments that are present.
02944   const PointerType *PFTy = 0;
02945   const FunctionType *Ty = 0;
02946   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
02947       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
02948     // Pull out the types of all of the arguments...
02949     std::vector<const Type*> ParamTypes;
02950     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
02951       ParamTypes.push_back(ArgList[i].V->getType());
02952     
02953     if (!FunctionType::isValidReturnType(RetType))
02954       return Error(RetTypeLoc, "Invalid result type for LLVM function");
02955     
02956     Ty = FunctionType::get(RetType, ParamTypes, false);
02957     PFTy = PointerType::getUnqual(Ty);
02958   }
02959   
02960   // Look up the callee.
02961   Value *Callee;
02962   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
02963   
02964   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
02965   // function attributes.
02966   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
02967   if (FnAttrs & ObsoleteFuncAttrs) {
02968     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
02969     FnAttrs &= ~ObsoleteFuncAttrs;
02970   }
02971   
02972   // Set up the Attributes for the function.
02973   SmallVector<AttributeWithIndex, 8> Attrs;
02974   if (RetAttrs != Attribute::None)
02975     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
02976   
02977   SmallVector<Value*, 8> Args;
02978   
02979   // Loop through FunctionType's arguments and ensure they are specified
02980   // correctly.  Also, gather any parameter attributes.
02981   FunctionType::param_iterator I = Ty->param_begin();
02982   FunctionType::param_iterator E = Ty->param_end();
02983   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
02984     const Type *ExpectedTy = 0;
02985     if (I != E) {
02986       ExpectedTy = *I++;
02987     } else if (!Ty->isVarArg()) {
02988       return Error(ArgList[i].Loc, "too many arguments specified");
02989     }
02990     
02991     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
02992       return Error(ArgList[i].Loc, "argument is not of expected type '" +
02993                    ExpectedTy->getDescription() + "'");
02994     Args.push_back(ArgList[i].V);
02995     if (ArgList[i].Attrs != Attribute::None)
02996       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
02997   }
02998   
02999   if (I != E)
03000     return Error(CallLoc, "not enough parameters specified for call");
03001   
03002   if (FnAttrs != Attribute::None)
03003     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
03004   
03005   // Finish off the Attributes and check them
03006   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
03007   
03008   InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
03009                                       cast<BasicBlock>(UnwindBB),
03010                                       Args.begin(), Args.end());
03011   II->setCallingConv(CC);
03012   II->setAttributes(PAL);
03013   Inst = II;
03014   return false;
03015 }
03016 
03017 
03018 
03019 //===----------------------------------------------------------------------===//
03020 // Binary Operators.
03021 //===----------------------------------------------------------------------===//
03022 
03023 /// ParseArithmetic
03024 ///  ::= ArithmeticOps TypeAndValue ',' Value
03025 ///
03026 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
03027 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
03028 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
03029                                unsigned Opc, unsigned OperandType) {
03030   LocTy Loc; Value *LHS, *RHS;
03031   if (ParseTypeAndValue(LHS, Loc, PFS) ||
03032       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
03033       ParseValue(LHS->getType(), RHS, PFS))
03034     return true;
03035 
03036   bool Valid;
03037   switch (OperandType) {
03038   default: llvm_unreachable("Unknown operand type!");
03039   case 0: // int or FP.
03040     Valid = LHS->getType()->isIntOrIntVector() ||
03041             LHS->getType()->isFPOrFPVector();
03042     break;
03043   case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
03044   case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
03045   }
03046   
03047   if (!Valid)
03048     return Error(Loc, "invalid operand type for instruction");
03049   
03050   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
03051   return false;
03052 }
03053 
03054 /// ParseLogical
03055 ///  ::= ArithmeticOps TypeAndValue ',' Value {
03056 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
03057                             unsigned Opc) {
03058   LocTy Loc; Value *LHS, *RHS;
03059   if (ParseTypeAndValue(LHS, Loc, PFS) ||
03060       ParseToken(lltok::comma, "expected ',' in logical operation") ||
03061       ParseValue(LHS->getType(), RHS, PFS))
03062     return true;
03063 
03064   if (!LHS->getType()->isIntOrIntVector())
03065     return Error(Loc,"instruction requires integer or integer vector operands");
03066 
03067   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
03068   return false;
03069 }
03070 
03071 
03072 /// ParseCompare
03073 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
03074 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
03075 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
03076                             unsigned Opc) {
03077   // Parse the integer/fp comparison predicate.
03078   LocTy Loc;
03079   unsigned Pred;
03080   Value *LHS, *RHS;
03081   if (ParseCmpPredicate(Pred, Opc) ||
03082       ParseTypeAndValue(LHS, Loc, PFS) ||
03083       ParseToken(lltok::comma, "expected ',' after compare value") ||
03084       ParseValue(LHS->getType(), RHS, PFS))
03085     return true;
03086   
03087   if (Opc == Instruction::FCmp) {
03088     if (!LHS->getType()->isFPOrFPVector())
03089       return Error(Loc, "fcmp requires floating point operands");
03090     Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
03091   } else {
03092     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
03093     if (!LHS->getType()->isIntOrIntVector() &&
03094         !isa<PointerType>(LHS->getType()))
03095       return Error(Loc, "icmp requires integer operands");
03096     Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
03097   }
03098   return false;
03099 }
03100 
03101 //===----------------------------------------------------------------------===//
03102 // Other Instructions.
03103 //===----------------------------------------------------------------------===//
03104 
03105 
03106 /// ParseCast
03107 ///   ::= CastOpc TypeAndValue 'to' Type
03108 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
03109                          unsigned Opc) {
03110   LocTy Loc;  Value *Op;
03111   PATypeHolder DestTy(Type::getVoidTy(Context));
03112   if (ParseTypeAndValue(Op, Loc, PFS) ||
03113       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
03114       ParseType(DestTy))
03115     return true;
03116   
03117   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
03118     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
03119     return Error(Loc, "invalid cast opcode for cast from '" +
03120                  Op->getType()->getDescription() + "' to '" +
03121                  DestTy->getDescription() + "'");
03122   }
03123   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
03124   return false;
03125 }
03126 
03127 /// ParseSelect
03128 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
03129 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
03130   LocTy Loc;
03131   Value *Op0, *Op1, *Op2;
03132   if (ParseTypeAndValue(Op0, Loc, PFS) ||
03133       ParseToken(lltok::comma, "expected ',' after select condition") ||
03134       ParseTypeAndValue(Op1, PFS) ||
03135       ParseToken(lltok::comma, "expected ',' after select value") ||
03136       ParseTypeAndValue(Op2, PFS))
03137     return true;
03138   
03139   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
03140     return Error(Loc, Reason);
03141   
03142   Inst = SelectInst::Create(Op0, Op1, Op2);
03143   return false;
03144 }
03145 
03146 /// ParseVA_Arg
03147 ///   ::= 'va_arg' TypeAndValue ',' Type
03148 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
03149   Value *Op;
03150   PATypeHolder EltTy(Type::getVoidTy(Context));
03151   LocTy TypeLoc;
03152   if (ParseTypeAndValue(Op, PFS) ||
03153       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
03154       ParseType(EltTy, TypeLoc))
03155     return true;
03156   
03157   if (!EltTy->isFirstClassType())
03158     return Error(TypeLoc, "va_arg requires operand with first class type");
03159 
03160   Inst = new VAArgInst(Op, EltTy);
03161   return false;
03162 }
03163 
03164 /// ParseExtractElement
03165 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
03166 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
03167   LocTy Loc;
03168   Value *Op0, *Op1;
03169   if (ParseTypeAndValue(Op0, Loc, PFS) ||
03170       ParseToken(lltok::comma, "expected ',' after extract value") ||
03171       ParseTypeAndValue(Op1, PFS))
03172     return true;
03173   
03174   if (!ExtractElementInst::isValidOperands(Op0, Op1))
03175     return Error(Loc, "invalid extractelement operands");
03176   
03177   Inst = ExtractElementInst::Create(Op0, Op1);
03178   return false;
03179 }
03180 
03181 /// ParseInsertElement
03182 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
03183 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
03184   LocTy Loc;
03185   Value *Op0, *Op1, *Op2;
03186   if (ParseTypeAndValue(Op0, Loc, PFS) ||
03187       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
03188       ParseTypeAndValue(Op1, PFS) ||
03189       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
03190       ParseTypeAndValue(Op2, PFS))
03191     return true;
03192   
03193   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
03194     return Error(Loc, "invalid insertelement operands");
03195   
03196   Inst = InsertElementInst::Create(Op0, Op1, Op2);
03197   return false;
03198 }
03199 
03200 /// ParseShuffleVector
03201 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
03202 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
03203   LocTy Loc;
03204   Value *Op0, *Op1, *Op2;
03205   if (ParseTypeAndValue(Op0, Loc, PFS) ||
03206       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
03207       ParseTypeAndValue(Op1, PFS) ||
03208       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
03209       ParseTypeAndValue(Op2, PFS))
03210     return true;
03211   
03212   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
03213     return Error(Loc, "invalid extractelement operands");
03214   
03215   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
03216   return false;
03217 }
03218 
03219 /// ParsePHI
03220 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
03221 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
03222   PATypeHolder Ty(Type::getVoidTy(Context));
03223   Value *Op0, *Op1;
03224   LocTy TypeLoc = Lex.getLoc();
03225   
03226   if (ParseType(Ty) ||
03227       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
03228       ParseValue(Ty, Op0, PFS) ||
03229       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
03230       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
03231       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
03232     return true;
03233  
03234   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
03235   while (1) {
03236     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
03237     
03238     if (!EatIfPresent(lltok::comma))
03239       break;
03240 
03241     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
03242         ParseValue(Ty, Op0, PFS) ||
03243         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
03244         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
03245         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
03246       return true;
03247   }
03248   
03249   if (!Ty->isFirstClassType())
03250     return Error(TypeLoc, "phi node must have first class type");
03251 
03252   PHINode *PN = PHINode::Create(Ty);
03253   PN->reserveOperandSpace(PHIVals.size());
03254   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
03255     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
03256   Inst = PN;
03257   return false;
03258 }
03259 
03260 /// ParseCall
03261 ///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
03262 ///       ParameterList OptionalAttrs
03263 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
03264                          bool isTail) {
03265   unsigned CC, RetAttrs, FnAttrs;
03266   PATypeHolder RetType(Type::getVoidTy(Context));
03267   LocTy RetTypeLoc;
03268   ValID CalleeID;
03269   SmallVector<ParamInfo, 16> ArgList;
03270   LocTy CallLoc = Lex.getLoc();
03271   
03272   if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
03273       ParseOptionalCallingConv(CC) ||
03274       ParseOptionalAttrs(RetAttrs, 1) ||
03275       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
03276       ParseValID(CalleeID) ||
03277       ParseParameterList(ArgList, PFS) ||
03278       ParseOptionalAttrs(FnAttrs, 2))
03279     return true;
03280   
03281   // If RetType is a non-function pointer type, then this is the short syntax
03282   // for the call, which means that RetType is just the return type.  Infer the
03283   // rest of the function argument types from the arguments that are present.
03284   const PointerType *PFTy = 0;
03285   const FunctionType *Ty = 0;
03286   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
03287       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
03288     // Pull out the types of all of the arguments...
03289     std::vector<const Type*> ParamTypes;
03290     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
03291       ParamTypes.push_back(ArgList[i].V->getType());
03292     
03293     if (!FunctionType::isValidReturnType(RetType))
03294       return Error(RetTypeLoc, "Invalid result type for LLVM function");
03295     
03296     Ty = FunctionType::get(RetType, ParamTypes, false);
03297     PFTy = PointerType::getUnqual(Ty);
03298   }
03299   
03300   // Look up the callee.
03301   Value *Callee;
03302   if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
03303   
03304   // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
03305   // function attributes.
03306   unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
03307   if (FnAttrs & ObsoleteFuncAttrs) {
03308     RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
03309     FnAttrs &= ~ObsoleteFuncAttrs;
03310   }
03311 
03312   // Set up the Attributes for the function.
03313   SmallVector<AttributeWithIndex, 8> Attrs;
03314   if (RetAttrs != Attribute::None)
03315     Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
03316   
03317   SmallVector<Value*, 8> Args;
03318   
03319   // Loop through FunctionType's arguments and ensure they are specified
03320   // correctly.  Also, gather any parameter attributes.
03321   FunctionType::param_iterator I = Ty->param_begin();
03322   FunctionType::param_iterator E = Ty->param_end();
03323   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
03324     const Type *ExpectedTy = 0;
03325     if (I != E) {
03326       ExpectedTy = *I++;
03327     } else if (!Ty->isVarArg()) {
03328       return Error(ArgList[i].Loc, "too many arguments specified");
03329     }
03330     
03331     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
03332       return Error(ArgList[i].Loc, "argument is not of expected type '" +
03333                    ExpectedTy->getDescription() + "'");
03334     Args.push_back(ArgList[i].V);
03335     if (ArgList[i].Attrs != Attribute::None)
03336       Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
03337   }
03338   
03339   if (I != E)
03340     return Error(CallLoc, "not enough parameters specified for call");
03341 
03342   if (FnAttrs != Attribute::None)
03343     Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
03344 
03345   // Finish off the Attributes and check them
03346   AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
03347   
03348   CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
03349   CI->setTailCall(isTail);
03350   CI->setCallingConv(CC);
03351   CI->setAttributes(PAL);
03352   Inst = CI;
03353   return false;
03354 }
03355 
03356 //===----------------------------------------------------------------------===//
03357 // Memory Instructions.
03358 //===----------------------------------------------------------------------===//
03359 
03360 /// ParseAlloc
03361 ///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
03362 ///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
03363 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
03364                           unsigned Opc) {
03365   PATypeHolder Ty(Type::getVoidTy(Context));
03366   Value *Size = 0;
03367   LocTy SizeLoc;
03368   unsigned Alignment = 0;
03369   if (ParseType(Ty)) return true;
03370 
03371   if (EatIfPresent(lltok::comma)) {
03372     if (Lex.getKind() == lltok::kw_align) {
03373       if (ParseOptionalAlignment(Alignment)) return true;
03374     } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
03375                ParseOptionalCommaAlignment(Alignment)) {
03376       return true;
03377     }
03378   }
03379 
03380   if (Size && Size->getType() != Type::getInt32Ty(Context))
03381     return Error(SizeLoc, "element count must be i32");
03382 
03383   if (Opc == Instruction::Malloc)
03384     Inst = new MallocInst(Ty, Size, Alignment);
03385   else
03386     Inst = new AllocaInst(Ty, Size, Alignment);
03387   return false;
03388 }
03389 
03390 /// ParseFree
03391 ///   ::= 'free' TypeAndValue
03392 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
03393   Value *Val; LocTy Loc;
03394   if (ParseTypeAndValue(Val, Loc, PFS)) return true;
03395   if (!isa<PointerType>(Val->getType()))
03396     return Error(Loc, "operand to free must be a pointer");
03397   Inst = new FreeInst(Val);
03398   return false;
03399 }
03400 
03401 /// ParseLoad
03402 ///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
03403 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
03404                          bool isVolatile) {
03405   Value *Val; LocTy Loc;
03406   unsigned Alignment;
03407   if (ParseTypeAndValue(Val, Loc, PFS) ||
03408       ParseOptionalCommaAlignment(Alignment))
03409     return true;
03410 
03411   if (!isa<PointerType>(Val->getType()) ||
03412       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
03413     return Error(Loc, "load operand must be a pointer to a first class type");
03414   
03415   Inst = new LoadInst(Val, "", isVolatile, Alignment);
03416   return false;
03417 }
03418 
03419 /// ParseStore
03420 ///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
03421 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
03422                           bool isVolatile) {
03423   Value *Val, *Ptr; LocTy Loc, PtrLoc;
03424   unsigned Alignment;
03425   if (ParseTypeAndValue(Val, Loc, PFS) ||
03426       ParseToken(lltok::comma, "expected ',' after store operand") ||
03427       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
03428       ParseOptionalCommaAlignment(Alignment))
03429     return true;
03430   
03431   if (!isa<PointerType>(Ptr->getType()))
03432     return Error(PtrLoc, "store operand must be a pointer");
03433   if (!Val->getType()->isFirstClassType())
03434     return Error(Loc, "store operand must be a first class value");
03435   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
03436     return Error(Loc, "stored value and pointer type do not match");
03437   
03438   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
03439   return false;
03440 }
03441 
03442 /// ParseGetResult
03443 ///   ::= 'getresult' TypeAndValue ',' i32
03444 /// FIXME: Remove support for getresult in LLVM 3.0
03445 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
03446   Value *Val; LocTy ValLoc, EltLoc;
03447   unsigned Element;
03448   if (ParseTypeAndValue(Val, ValLoc, PFS) ||
03449       ParseToken(lltok::comma, "expected ',' after getresult operand") ||
03450       ParseUInt32(Element, EltLoc))
03451     return true;
03452   
03453   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
03454     return Error(ValLoc, "getresult inst requires an aggregate operand");
03455   if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
03456     return Error(EltLoc, "invalid getresult index for value");
03457   Inst = ExtractValueInst::Create(Val, Element);
03458   return false;
03459 }
03460 
03461 /// ParseGetElementPtr
03462 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
03463 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
03464   Value *Ptr, *Val; LocTy Loc, EltLoc;
03465 
03466   bool InBounds = EatIfPresent(lltok::kw_inbounds);
03467 
03468   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
03469   
03470   if (!isa<PointerType>(Ptr->getType()))
03471     return Error(Loc, "base of getelementptr must be a pointer");
03472   
03473   SmallVector<Value*, 16> Indices;
03474   while (EatIfPresent(lltok::comma)) {
03475     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
03476     if (!isa<IntegerType>(Val->getType()))
03477       return Error(EltLoc, "getelementptr index must be an integer");
03478     Indices.push_back(Val);
03479   }
03480   
03481   if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
03482                                          Indices.begin(), Indices.end()))
03483     return Error(Loc, "invalid getelementptr indices");
03484   Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
03485   if (InBounds)
03486     cast<GEPOperator>(Inst)->setIsInBounds(true);
03487   return false;
03488 }
03489 
03490 /// ParseExtractValue
03491 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
03492 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
03493   Value *Val; LocTy Loc;
03494   SmallVector<unsigned, 4> Indices;
03495   if (ParseTypeAndValue(Val, Loc, PFS) ||
03496       ParseIndexList(Indices))
03497     return true;
03498 
03499   if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
03500     return Error(Loc, "extractvalue operand must be array or struct");
03501 
03502   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
03503                                         Indices.end()))
03504     return Error(Loc, "invalid indices for extractvalue");
03505   Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
03506   return false;
03507 }
03508 
03509 /// ParseInsertValue
03510 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
03511 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
03512   Value *Val0, *Val1; LocTy Loc0, Loc1;
03513   SmallVector<unsigned, 4> Indices;
03514   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
03515       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
03516       ParseTypeAndValue(Val1, Loc1, PFS) ||
03517       ParseIndexList(Indices))
03518     return true;
03519   
03520   if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
03521     return Error(Loc0, "extractvalue operand must be array or struct");
03522   
03523   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
03524                                         Indices.end()))
03525     return Error(Loc0, "invalid indices for insertvalue");
03526   Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
03527   return false;
03528 }
03529 
03530 //===----------------------------------------------------------------------===//
03531 // Embedded metadata.
03532 //===----------------------------------------------------------------------===//
03533 
03534 /// ParseMDNodeVector
03535 ///   ::= Element (',' Element)*
03536 /// Element
03537 ///   ::= 'null' | TypeAndValue
03538 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
03539   assert(Lex.getKind() == lltok::lbrace);
03540   Lex.Lex();
03541   do {
03542     Value *V = 0;
03543     if (Lex.getKind() == lltok::kw_null) {
03544       Lex.Lex();
03545       V = 0;
03546     } else {
03547       PATypeHolder Ty(Type::getVoidTy(Context));
03548       if (ParseType(Ty)) return true;
03549       if (Lex.getKind() == lltok::Metadata) {
03550         Lex.Lex();
03551         MetadataBase *Node = 0;
03552         if (!ParseMDNode(Node))
03553           V = Node;
03554         else {
03555           MetadataBase *MDS = 0;
03556           if (ParseMDString(MDS)) return true;
03557           V = MDS;
03558         }
03559       } else {
03560         Constant *C;
03561         if (ParseGlobalValue(Ty, C)) return true;
03562         V = C;
03563       }
03564     }
03565     Elts.push_back(V);
03566   } while (EatIfPresent(lltok::comma));
03567 
03568   return false;
03569 }