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