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