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