1 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the parser class for .ll files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "LLParser.h" 14 #include "LLToken.h" 15 #include "llvm/ADT/APSInt.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/AsmParser/SlotMapping.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/IR/Argument.h" 23 #include "llvm/IR/AutoUpgrade.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/Comdat.h" 27 #include "llvm/IR/ConstantRange.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DebugInfoMetadata.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalIFunc.h" 33 #include "llvm/IR/GlobalObject.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/LLVMContext.h" 37 #include "llvm/IR/Metadata.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/IR/ValueSymbolTable.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/ErrorHandling.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/SaveAndRestore.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include <algorithm> 47 #include <cassert> 48 #include <cstring> 49 #include <iterator> 50 #include <vector> 51 52 using namespace llvm; 53 54 static std::string getTypeString(Type *T) { 55 std::string Result; 56 raw_string_ostream Tmp(Result); 57 Tmp << *T; 58 return Tmp.str(); 59 } 60 61 /// Run: module ::= toplevelentity* 62 bool LLParser::Run(bool UpgradeDebugInfo, 63 DataLayoutCallbackTy DataLayoutCallback) { 64 // Prime the lexer. 65 Lex.Lex(); 66 67 if (Context.shouldDiscardValueNames()) 68 return error( 69 Lex.getLoc(), 70 "Can't read textual IR with a Context that discards named Values"); 71 72 if (M) { 73 if (parseTargetDefinitions()) 74 return true; 75 76 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple())) 77 M->setDataLayout(*LayoutOverride); 78 } 79 80 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) || 81 validateEndOfIndex(); 82 } 83 84 bool LLParser::parseStandaloneConstantValue(Constant *&C, 85 const SlotMapping *Slots) { 86 restoreParsingState(Slots); 87 Lex.Lex(); 88 89 Type *Ty = nullptr; 90 if (parseType(Ty) || parseConstantValue(Ty, C)) 91 return true; 92 if (Lex.getKind() != lltok::Eof) 93 return error(Lex.getLoc(), "expected end of string"); 94 return false; 95 } 96 97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read, 98 const SlotMapping *Slots) { 99 restoreParsingState(Slots); 100 Lex.Lex(); 101 102 Read = 0; 103 SMLoc Start = Lex.getLoc(); 104 Ty = nullptr; 105 if (parseType(Ty)) 106 return true; 107 SMLoc End = Lex.getLoc(); 108 Read = End.getPointer() - Start.getPointer(); 109 110 return false; 111 } 112 113 void LLParser::restoreParsingState(const SlotMapping *Slots) { 114 if (!Slots) 115 return; 116 NumberedVals = Slots->GlobalValues; 117 NumberedMetadata = Slots->MetadataNodes; 118 for (const auto &I : Slots->NamedTypes) 119 NamedTypes.insert( 120 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy()))); 121 for (const auto &I : Slots->Types) 122 NumberedTypes.insert( 123 std::make_pair(I.first, std::make_pair(I.second, LocTy()))); 124 } 125 126 /// validateEndOfModule - Do final validity and sanity checks at the end of the 127 /// module. 128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) { 129 if (!M) 130 return false; 131 // Handle any function attribute group forward references. 132 for (const auto &RAG : ForwardRefAttrGroups) { 133 Value *V = RAG.first; 134 const std::vector<unsigned> &Attrs = RAG.second; 135 AttrBuilder B; 136 137 for (const auto &Attr : Attrs) 138 B.merge(NumberedAttrBuilders[Attr]); 139 140 if (Function *Fn = dyn_cast<Function>(V)) { 141 AttributeList AS = Fn->getAttributes(); 142 AttrBuilder FnAttrs(AS.getFnAttributes()); 143 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 144 145 FnAttrs.merge(B); 146 147 // If the alignment was parsed as an attribute, move to the alignment 148 // field. 149 if (FnAttrs.hasAlignmentAttr()) { 150 Fn->setAlignment(FnAttrs.getAlignment()); 151 FnAttrs.removeAttribute(Attribute::Alignment); 152 } 153 154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 155 AttributeSet::get(Context, FnAttrs)); 156 Fn->setAttributes(AS); 157 } else if (CallInst *CI = dyn_cast<CallInst>(V)) { 158 AttributeList AS = CI->getAttributes(); 159 AttrBuilder FnAttrs(AS.getFnAttributes()); 160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 161 FnAttrs.merge(B); 162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 163 AttributeSet::get(Context, FnAttrs)); 164 CI->setAttributes(AS); 165 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { 166 AttributeList AS = II->getAttributes(); 167 AttrBuilder FnAttrs(AS.getFnAttributes()); 168 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 169 FnAttrs.merge(B); 170 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 171 AttributeSet::get(Context, FnAttrs)); 172 II->setAttributes(AS); 173 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) { 174 AttributeList AS = CBI->getAttributes(); 175 AttrBuilder FnAttrs(AS.getFnAttributes()); 176 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 177 FnAttrs.merge(B); 178 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 179 AttributeSet::get(Context, FnAttrs)); 180 CBI->setAttributes(AS); 181 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) { 182 AttrBuilder Attrs(GV->getAttributes()); 183 Attrs.merge(B); 184 GV->setAttributes(AttributeSet::get(Context,Attrs)); 185 } else { 186 llvm_unreachable("invalid object with forward attribute group reference"); 187 } 188 } 189 190 // If there are entries in ForwardRefBlockAddresses at this point, the 191 // function was never defined. 192 if (!ForwardRefBlockAddresses.empty()) 193 return error(ForwardRefBlockAddresses.begin()->first.Loc, 194 "expected function name in blockaddress"); 195 196 for (const auto &NT : NumberedTypes) 197 if (NT.second.second.isValid()) 198 return error(NT.second.second, 199 "use of undefined type '%" + Twine(NT.first) + "'"); 200 201 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 202 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 203 if (I->second.second.isValid()) 204 return error(I->second.second, 205 "use of undefined type named '" + I->getKey() + "'"); 206 207 if (!ForwardRefComdats.empty()) 208 return error(ForwardRefComdats.begin()->second, 209 "use of undefined comdat '$" + 210 ForwardRefComdats.begin()->first + "'"); 211 212 if (!ForwardRefVals.empty()) 213 return error(ForwardRefVals.begin()->second.second, 214 "use of undefined value '@" + ForwardRefVals.begin()->first + 215 "'"); 216 217 if (!ForwardRefValIDs.empty()) 218 return error(ForwardRefValIDs.begin()->second.second, 219 "use of undefined value '@" + 220 Twine(ForwardRefValIDs.begin()->first) + "'"); 221 222 if (!ForwardRefMDNodes.empty()) 223 return error(ForwardRefMDNodes.begin()->second.second, 224 "use of undefined metadata '!" + 225 Twine(ForwardRefMDNodes.begin()->first) + "'"); 226 227 // Resolve metadata cycles. 228 for (auto &N : NumberedMetadata) { 229 if (N.second && !N.second->isResolved()) 230 N.second->resolveCycles(); 231 } 232 233 for (auto *Inst : InstsWithTBAATag) { 234 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa); 235 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag"); 236 auto *UpgradedMD = UpgradeTBAANode(*MD); 237 if (MD != UpgradedMD) 238 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD); 239 } 240 241 // Look for intrinsic functions and CallInst that need to be upgraded 242 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) 243 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove 244 245 // Some types could be renamed during loading if several modules are 246 // loaded in the same LLVMContext (LTO scenario). In this case we should 247 // remangle intrinsics names as well. 248 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) { 249 Function *F = &*FI++; 250 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) { 251 F->replaceAllUsesWith(Remangled.getValue()); 252 F->eraseFromParent(); 253 } 254 } 255 256 if (UpgradeDebugInfo) 257 llvm::UpgradeDebugInfo(*M); 258 259 UpgradeModuleFlags(*M); 260 UpgradeSectionAttributes(*M); 261 262 if (!Slots) 263 return false; 264 // Initialize the slot mapping. 265 // Because by this point we've parsed and validated everything, we can "steal" 266 // the mapping from LLParser as it doesn't need it anymore. 267 Slots->GlobalValues = std::move(NumberedVals); 268 Slots->MetadataNodes = std::move(NumberedMetadata); 269 for (const auto &I : NamedTypes) 270 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first)); 271 for (const auto &I : NumberedTypes) 272 Slots->Types.insert(std::make_pair(I.first, I.second.first)); 273 274 return false; 275 } 276 277 /// Do final validity and sanity checks at the end of the index. 278 bool LLParser::validateEndOfIndex() { 279 if (!Index) 280 return false; 281 282 if (!ForwardRefValueInfos.empty()) 283 return error(ForwardRefValueInfos.begin()->second.front().second, 284 "use of undefined summary '^" + 285 Twine(ForwardRefValueInfos.begin()->first) + "'"); 286 287 if (!ForwardRefAliasees.empty()) 288 return error(ForwardRefAliasees.begin()->second.front().second, 289 "use of undefined summary '^" + 290 Twine(ForwardRefAliasees.begin()->first) + "'"); 291 292 if (!ForwardRefTypeIds.empty()) 293 return error(ForwardRefTypeIds.begin()->second.front().second, 294 "use of undefined type id summary '^" + 295 Twine(ForwardRefTypeIds.begin()->first) + "'"); 296 297 return false; 298 } 299 300 //===----------------------------------------------------------------------===// 301 // Top-Level Entities 302 //===----------------------------------------------------------------------===// 303 304 bool LLParser::parseTargetDefinitions() { 305 while (true) { 306 switch (Lex.getKind()) { 307 case lltok::kw_target: 308 if (parseTargetDefinition()) 309 return true; 310 break; 311 case lltok::kw_source_filename: 312 if (parseSourceFileName()) 313 return true; 314 break; 315 default: 316 return false; 317 } 318 } 319 } 320 321 bool LLParser::parseTopLevelEntities() { 322 // If there is no Module, then parse just the summary index entries. 323 if (!M) { 324 while (true) { 325 switch (Lex.getKind()) { 326 case lltok::Eof: 327 return false; 328 case lltok::SummaryID: 329 if (parseSummaryEntry()) 330 return true; 331 break; 332 case lltok::kw_source_filename: 333 if (parseSourceFileName()) 334 return true; 335 break; 336 default: 337 // Skip everything else 338 Lex.Lex(); 339 } 340 } 341 } 342 while (true) { 343 switch (Lex.getKind()) { 344 default: 345 return tokError("expected top-level entity"); 346 case lltok::Eof: return false; 347 case lltok::kw_declare: 348 if (parseDeclare()) 349 return true; 350 break; 351 case lltok::kw_define: 352 if (parseDefine()) 353 return true; 354 break; 355 case lltok::kw_module: 356 if (parseModuleAsm()) 357 return true; 358 break; 359 case lltok::kw_deplibs: 360 if (parseDepLibs()) 361 return true; 362 break; 363 case lltok::LocalVarID: 364 if (parseUnnamedType()) 365 return true; 366 break; 367 case lltok::LocalVar: 368 if (parseNamedType()) 369 return true; 370 break; 371 case lltok::GlobalID: 372 if (parseUnnamedGlobal()) 373 return true; 374 break; 375 case lltok::GlobalVar: 376 if (parseNamedGlobal()) 377 return true; 378 break; 379 case lltok::ComdatVar: if (parseComdat()) return true; break; 380 case lltok::exclaim: 381 if (parseStandaloneMetadata()) 382 return true; 383 break; 384 case lltok::SummaryID: 385 if (parseSummaryEntry()) 386 return true; 387 break; 388 case lltok::MetadataVar: 389 if (parseNamedMetadata()) 390 return true; 391 break; 392 case lltok::kw_attributes: 393 if (parseUnnamedAttrGrp()) 394 return true; 395 break; 396 case lltok::kw_uselistorder: 397 if (parseUseListOrder()) 398 return true; 399 break; 400 case lltok::kw_uselistorder_bb: 401 if (parseUseListOrderBB()) 402 return true; 403 break; 404 } 405 } 406 } 407 408 /// toplevelentity 409 /// ::= 'module' 'asm' STRINGCONSTANT 410 bool LLParser::parseModuleAsm() { 411 assert(Lex.getKind() == lltok::kw_module); 412 Lex.Lex(); 413 414 std::string AsmStr; 415 if (parseToken(lltok::kw_asm, "expected 'module asm'") || 416 parseStringConstant(AsmStr)) 417 return true; 418 419 M->appendModuleInlineAsm(AsmStr); 420 return false; 421 } 422 423 /// toplevelentity 424 /// ::= 'target' 'triple' '=' STRINGCONSTANT 425 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 426 bool LLParser::parseTargetDefinition() { 427 assert(Lex.getKind() == lltok::kw_target); 428 std::string Str; 429 switch (Lex.Lex()) { 430 default: 431 return tokError("unknown target property"); 432 case lltok::kw_triple: 433 Lex.Lex(); 434 if (parseToken(lltok::equal, "expected '=' after target triple") || 435 parseStringConstant(Str)) 436 return true; 437 M->setTargetTriple(Str); 438 return false; 439 case lltok::kw_datalayout: 440 Lex.Lex(); 441 if (parseToken(lltok::equal, "expected '=' after target datalayout") || 442 parseStringConstant(Str)) 443 return true; 444 M->setDataLayout(Str); 445 return false; 446 } 447 } 448 449 /// toplevelentity 450 /// ::= 'source_filename' '=' STRINGCONSTANT 451 bool LLParser::parseSourceFileName() { 452 assert(Lex.getKind() == lltok::kw_source_filename); 453 Lex.Lex(); 454 if (parseToken(lltok::equal, "expected '=' after source_filename") || 455 parseStringConstant(SourceFileName)) 456 return true; 457 if (M) 458 M->setSourceFileName(SourceFileName); 459 return false; 460 } 461 462 /// toplevelentity 463 /// ::= 'deplibs' '=' '[' ']' 464 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 465 /// FIXME: Remove in 4.0. Currently parse, but ignore. 466 bool LLParser::parseDepLibs() { 467 assert(Lex.getKind() == lltok::kw_deplibs); 468 Lex.Lex(); 469 if (parseToken(lltok::equal, "expected '=' after deplibs") || 470 parseToken(lltok::lsquare, "expected '=' after deplibs")) 471 return true; 472 473 if (EatIfPresent(lltok::rsquare)) 474 return false; 475 476 do { 477 std::string Str; 478 if (parseStringConstant(Str)) 479 return true; 480 } while (EatIfPresent(lltok::comma)); 481 482 return parseToken(lltok::rsquare, "expected ']' at end of list"); 483 } 484 485 /// parseUnnamedType: 486 /// ::= LocalVarID '=' 'type' type 487 bool LLParser::parseUnnamedType() { 488 LocTy TypeLoc = Lex.getLoc(); 489 unsigned TypeID = Lex.getUIntVal(); 490 Lex.Lex(); // eat LocalVarID; 491 492 if (parseToken(lltok::equal, "expected '=' after name") || 493 parseToken(lltok::kw_type, "expected 'type' after '='")) 494 return true; 495 496 Type *Result = nullptr; 497 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result)) 498 return true; 499 500 if (!isa<StructType>(Result)) { 501 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 502 if (Entry.first) 503 return error(TypeLoc, "non-struct types may not be recursive"); 504 Entry.first = Result; 505 Entry.second = SMLoc(); 506 } 507 508 return false; 509 } 510 511 /// toplevelentity 512 /// ::= LocalVar '=' 'type' type 513 bool LLParser::parseNamedType() { 514 std::string Name = Lex.getStrVal(); 515 LocTy NameLoc = Lex.getLoc(); 516 Lex.Lex(); // eat LocalVar. 517 518 if (parseToken(lltok::equal, "expected '=' after name") || 519 parseToken(lltok::kw_type, "expected 'type' after name")) 520 return true; 521 522 Type *Result = nullptr; 523 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result)) 524 return true; 525 526 if (!isa<StructType>(Result)) { 527 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 528 if (Entry.first) 529 return error(NameLoc, "non-struct types may not be recursive"); 530 Entry.first = Result; 531 Entry.second = SMLoc(); 532 } 533 534 return false; 535 } 536 537 /// toplevelentity 538 /// ::= 'declare' FunctionHeader 539 bool LLParser::parseDeclare() { 540 assert(Lex.getKind() == lltok::kw_declare); 541 Lex.Lex(); 542 543 std::vector<std::pair<unsigned, MDNode *>> MDs; 544 while (Lex.getKind() == lltok::MetadataVar) { 545 unsigned MDK; 546 MDNode *N; 547 if (parseMetadataAttachment(MDK, N)) 548 return true; 549 MDs.push_back({MDK, N}); 550 } 551 552 Function *F; 553 if (parseFunctionHeader(F, false)) 554 return true; 555 for (auto &MD : MDs) 556 F->addMetadata(MD.first, *MD.second); 557 return false; 558 } 559 560 /// toplevelentity 561 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ... 562 bool LLParser::parseDefine() { 563 assert(Lex.getKind() == lltok::kw_define); 564 Lex.Lex(); 565 566 Function *F; 567 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) || 568 parseFunctionBody(*F); 569 } 570 571 /// parseGlobalType 572 /// ::= 'constant' 573 /// ::= 'global' 574 bool LLParser::parseGlobalType(bool &IsConstant) { 575 if (Lex.getKind() == lltok::kw_constant) 576 IsConstant = true; 577 else if (Lex.getKind() == lltok::kw_global) 578 IsConstant = false; 579 else { 580 IsConstant = false; 581 return tokError("expected 'global' or 'constant'"); 582 } 583 Lex.Lex(); 584 return false; 585 } 586 587 bool LLParser::parseOptionalUnnamedAddr( 588 GlobalVariable::UnnamedAddr &UnnamedAddr) { 589 if (EatIfPresent(lltok::kw_unnamed_addr)) 590 UnnamedAddr = GlobalValue::UnnamedAddr::Global; 591 else if (EatIfPresent(lltok::kw_local_unnamed_addr)) 592 UnnamedAddr = GlobalValue::UnnamedAddr::Local; 593 else 594 UnnamedAddr = GlobalValue::UnnamedAddr::None; 595 return false; 596 } 597 598 /// parseUnnamedGlobal: 599 /// OptionalVisibility (ALIAS | IFUNC) ... 600 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 601 /// OptionalDLLStorageClass 602 /// ... -> global variable 603 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ... 604 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier 605 /// OptionalVisibility 606 /// OptionalDLLStorageClass 607 /// ... -> global variable 608 bool LLParser::parseUnnamedGlobal() { 609 unsigned VarID = NumberedVals.size(); 610 std::string Name; 611 LocTy NameLoc = Lex.getLoc(); 612 613 // Handle the GlobalID form. 614 if (Lex.getKind() == lltok::GlobalID) { 615 if (Lex.getUIntVal() != VarID) 616 return error(Lex.getLoc(), 617 "variable expected to be numbered '%" + Twine(VarID) + "'"); 618 Lex.Lex(); // eat GlobalID; 619 620 if (parseToken(lltok::equal, "expected '=' after name")) 621 return true; 622 } 623 624 bool HasLinkage; 625 unsigned Linkage, Visibility, DLLStorageClass; 626 bool DSOLocal; 627 GlobalVariable::ThreadLocalMode TLM; 628 GlobalVariable::UnnamedAddr UnnamedAddr; 629 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 630 DSOLocal) || 631 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 632 return true; 633 634 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc) 635 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 636 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 637 638 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility, 639 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 640 } 641 642 /// parseNamedGlobal: 643 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ... 644 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 645 /// OptionalVisibility OptionalDLLStorageClass 646 /// ... -> global variable 647 bool LLParser::parseNamedGlobal() { 648 assert(Lex.getKind() == lltok::GlobalVar); 649 LocTy NameLoc = Lex.getLoc(); 650 std::string Name = Lex.getStrVal(); 651 Lex.Lex(); 652 653 bool HasLinkage; 654 unsigned Linkage, Visibility, DLLStorageClass; 655 bool DSOLocal; 656 GlobalVariable::ThreadLocalMode TLM; 657 GlobalVariable::UnnamedAddr UnnamedAddr; 658 if (parseToken(lltok::equal, "expected '=' in global variable") || 659 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 660 DSOLocal) || 661 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 662 return true; 663 664 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc) 665 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 666 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 667 668 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility, 669 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 670 } 671 672 bool LLParser::parseComdat() { 673 assert(Lex.getKind() == lltok::ComdatVar); 674 std::string Name = Lex.getStrVal(); 675 LocTy NameLoc = Lex.getLoc(); 676 Lex.Lex(); 677 678 if (parseToken(lltok::equal, "expected '=' here")) 679 return true; 680 681 if (parseToken(lltok::kw_comdat, "expected comdat keyword")) 682 return tokError("expected comdat type"); 683 684 Comdat::SelectionKind SK; 685 switch (Lex.getKind()) { 686 default: 687 return tokError("unknown selection kind"); 688 case lltok::kw_any: 689 SK = Comdat::Any; 690 break; 691 case lltok::kw_exactmatch: 692 SK = Comdat::ExactMatch; 693 break; 694 case lltok::kw_largest: 695 SK = Comdat::Largest; 696 break; 697 case lltok::kw_noduplicates: 698 SK = Comdat::NoDuplicates; 699 break; 700 case lltok::kw_samesize: 701 SK = Comdat::SameSize; 702 break; 703 } 704 Lex.Lex(); 705 706 // See if the comdat was forward referenced, if so, use the comdat. 707 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 708 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 709 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name)) 710 return error(NameLoc, "redefinition of comdat '$" + Name + "'"); 711 712 Comdat *C; 713 if (I != ComdatSymTab.end()) 714 C = &I->second; 715 else 716 C = M->getOrInsertComdat(Name); 717 C->setSelectionKind(SK); 718 719 return false; 720 } 721 722 // MDString: 723 // ::= '!' STRINGCONSTANT 724 bool LLParser::parseMDString(MDString *&Result) { 725 std::string Str; 726 if (parseStringConstant(Str)) 727 return true; 728 Result = MDString::get(Context, Str); 729 return false; 730 } 731 732 // MDNode: 733 // ::= '!' MDNodeNumber 734 bool LLParser::parseMDNodeID(MDNode *&Result) { 735 // !{ ..., !42, ... } 736 LocTy IDLoc = Lex.getLoc(); 737 unsigned MID = 0; 738 if (parseUInt32(MID)) 739 return true; 740 741 // If not a forward reference, just return it now. 742 if (NumberedMetadata.count(MID)) { 743 Result = NumberedMetadata[MID]; 744 return false; 745 } 746 747 // Otherwise, create MDNode forward reference. 748 auto &FwdRef = ForwardRefMDNodes[MID]; 749 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc); 750 751 Result = FwdRef.first.get(); 752 NumberedMetadata[MID].reset(Result); 753 return false; 754 } 755 756 /// parseNamedMetadata: 757 /// !foo = !{ !1, !2 } 758 bool LLParser::parseNamedMetadata() { 759 assert(Lex.getKind() == lltok::MetadataVar); 760 std::string Name = Lex.getStrVal(); 761 Lex.Lex(); 762 763 if (parseToken(lltok::equal, "expected '=' here") || 764 parseToken(lltok::exclaim, "Expected '!' here") || 765 parseToken(lltok::lbrace, "Expected '{' here")) 766 return true; 767 768 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 769 if (Lex.getKind() != lltok::rbrace) 770 do { 771 MDNode *N = nullptr; 772 // parse DIExpressions inline as a special case. They are still MDNodes, 773 // so they can still appear in named metadata. Remove this logic if they 774 // become plain Metadata. 775 if (Lex.getKind() == lltok::MetadataVar && 776 Lex.getStrVal() == "DIExpression") { 777 if (parseDIExpression(N, /*IsDistinct=*/false)) 778 return true; 779 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 780 parseMDNodeID(N)) { 781 return true; 782 } 783 NMD->addOperand(N); 784 } while (EatIfPresent(lltok::comma)); 785 786 return parseToken(lltok::rbrace, "expected end of metadata node"); 787 } 788 789 /// parseStandaloneMetadata: 790 /// !42 = !{...} 791 bool LLParser::parseStandaloneMetadata() { 792 assert(Lex.getKind() == lltok::exclaim); 793 Lex.Lex(); 794 unsigned MetadataID = 0; 795 796 MDNode *Init; 797 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here")) 798 return true; 799 800 // Detect common error, from old metadata syntax. 801 if (Lex.getKind() == lltok::Type) 802 return tokError("unexpected type in metadata definition"); 803 804 bool IsDistinct = EatIfPresent(lltok::kw_distinct); 805 if (Lex.getKind() == lltok::MetadataVar) { 806 if (parseSpecializedMDNode(Init, IsDistinct)) 807 return true; 808 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 809 parseMDTuple(Init, IsDistinct)) 810 return true; 811 812 // See if this was forward referenced, if so, handle it. 813 auto FI = ForwardRefMDNodes.find(MetadataID); 814 if (FI != ForwardRefMDNodes.end()) { 815 FI->second.first->replaceAllUsesWith(Init); 816 ForwardRefMDNodes.erase(FI); 817 818 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 819 } else { 820 if (NumberedMetadata.count(MetadataID)) 821 return tokError("Metadata id is already used"); 822 NumberedMetadata[MetadataID].reset(Init); 823 } 824 825 return false; 826 } 827 828 // Skips a single module summary entry. 829 bool LLParser::skipModuleSummaryEntry() { 830 // Each module summary entry consists of a tag for the entry 831 // type, followed by a colon, then the fields which may be surrounded by 832 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing 833 // support is in place we will look for the tokens corresponding to the 834 // expected tags. 835 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module && 836 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags && 837 Lex.getKind() != lltok::kw_blockcount) 838 return tokError( 839 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the " 840 "start of summary entry"); 841 if (Lex.getKind() == lltok::kw_flags) 842 return parseSummaryIndexFlags(); 843 if (Lex.getKind() == lltok::kw_blockcount) 844 return parseBlockCount(); 845 Lex.Lex(); 846 if (parseToken(lltok::colon, "expected ':' at start of summary entry") || 847 parseToken(lltok::lparen, "expected '(' at start of summary entry")) 848 return true; 849 // Now walk through the parenthesized entry, until the number of open 850 // parentheses goes back down to 0 (the first '(' was parsed above). 851 unsigned NumOpenParen = 1; 852 do { 853 switch (Lex.getKind()) { 854 case lltok::lparen: 855 NumOpenParen++; 856 break; 857 case lltok::rparen: 858 NumOpenParen--; 859 break; 860 case lltok::Eof: 861 return tokError("found end of file while parsing summary entry"); 862 default: 863 // Skip everything in between parentheses. 864 break; 865 } 866 Lex.Lex(); 867 } while (NumOpenParen > 0); 868 return false; 869 } 870 871 /// SummaryEntry 872 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry 873 bool LLParser::parseSummaryEntry() { 874 assert(Lex.getKind() == lltok::SummaryID); 875 unsigned SummaryID = Lex.getUIntVal(); 876 877 // For summary entries, colons should be treated as distinct tokens, 878 // not an indication of the end of a label token. 879 Lex.setIgnoreColonInIdentifiers(true); 880 881 Lex.Lex(); 882 if (parseToken(lltok::equal, "expected '=' here")) 883 return true; 884 885 // If we don't have an index object, skip the summary entry. 886 if (!Index) 887 return skipModuleSummaryEntry(); 888 889 bool result = false; 890 switch (Lex.getKind()) { 891 case lltok::kw_gv: 892 result = parseGVEntry(SummaryID); 893 break; 894 case lltok::kw_module: 895 result = parseModuleEntry(SummaryID); 896 break; 897 case lltok::kw_typeid: 898 result = parseTypeIdEntry(SummaryID); 899 break; 900 case lltok::kw_typeidCompatibleVTable: 901 result = parseTypeIdCompatibleVtableEntry(SummaryID); 902 break; 903 case lltok::kw_flags: 904 result = parseSummaryIndexFlags(); 905 break; 906 case lltok::kw_blockcount: 907 result = parseBlockCount(); 908 break; 909 default: 910 result = error(Lex.getLoc(), "unexpected summary kind"); 911 break; 912 } 913 Lex.setIgnoreColonInIdentifiers(false); 914 return result; 915 } 916 917 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) { 918 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) || 919 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility; 920 } 921 922 // If there was an explicit dso_local, update GV. In the absence of an explicit 923 // dso_local we keep the default value. 924 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) { 925 if (DSOLocal) 926 GV.setDSOLocal(true); 927 } 928 929 /// parseIndirectSymbol: 930 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 931 /// OptionalVisibility OptionalDLLStorageClass 932 /// OptionalThreadLocal OptionalUnnamedAddr 933 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr* 934 /// 935 /// IndirectSymbol 936 /// ::= TypeAndValue 937 /// 938 /// IndirectSymbolAttr 939 /// ::= ',' 'partition' StringConstant 940 /// 941 /// Everything through OptionalUnnamedAddr has already been parsed. 942 /// 943 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc, 944 unsigned L, unsigned Visibility, 945 unsigned DLLStorageClass, bool DSOLocal, 946 GlobalVariable::ThreadLocalMode TLM, 947 GlobalVariable::UnnamedAddr UnnamedAddr) { 948 bool IsAlias; 949 if (Lex.getKind() == lltok::kw_alias) 950 IsAlias = true; 951 else if (Lex.getKind() == lltok::kw_ifunc) 952 IsAlias = false; 953 else 954 llvm_unreachable("Not an alias or ifunc!"); 955 Lex.Lex(); 956 957 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; 958 959 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage)) 960 return error(NameLoc, "invalid linkage type for alias"); 961 962 if (!isValidVisibilityForLinkage(Visibility, L)) 963 return error(NameLoc, 964 "symbol with local linkage must have default visibility"); 965 966 Type *Ty; 967 LocTy ExplicitTypeLoc = Lex.getLoc(); 968 if (parseType(Ty) || 969 parseToken(lltok::comma, "expected comma after alias or ifunc's type")) 970 return true; 971 972 Constant *Aliasee; 973 LocTy AliaseeLoc = Lex.getLoc(); 974 if (Lex.getKind() != lltok::kw_bitcast && 975 Lex.getKind() != lltok::kw_getelementptr && 976 Lex.getKind() != lltok::kw_addrspacecast && 977 Lex.getKind() != lltok::kw_inttoptr) { 978 if (parseGlobalTypeAndValue(Aliasee)) 979 return true; 980 } else { 981 // The bitcast dest type is not present, it is implied by the dest type. 982 ValID ID; 983 if (parseValID(ID)) 984 return true; 985 if (ID.Kind != ValID::t_Constant) 986 return error(AliaseeLoc, "invalid aliasee"); 987 Aliasee = ID.ConstantVal; 988 } 989 990 Type *AliaseeType = Aliasee->getType(); 991 auto *PTy = dyn_cast<PointerType>(AliaseeType); 992 if (!PTy) 993 return error(AliaseeLoc, "An alias or ifunc must have pointer type"); 994 unsigned AddrSpace = PTy->getAddressSpace(); 995 996 if (IsAlias && Ty != PTy->getElementType()) 997 return error(ExplicitTypeLoc, 998 "explicit pointee type doesn't match operand's pointee type"); 999 1000 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) 1001 return error(ExplicitTypeLoc, 1002 "explicit pointee type should be a function type"); 1003 1004 GlobalValue *GVal = nullptr; 1005 1006 // See if the alias was forward referenced, if so, prepare to replace the 1007 // forward reference. 1008 if (!Name.empty()) { 1009 GVal = M->getNamedValue(Name); 1010 if (GVal) { 1011 if (!ForwardRefVals.erase(Name)) 1012 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1013 } 1014 } else { 1015 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1016 if (I != ForwardRefValIDs.end()) { 1017 GVal = I->second.first; 1018 ForwardRefValIDs.erase(I); 1019 } 1020 } 1021 1022 // Okay, create the alias but do not insert it into the module yet. 1023 std::unique_ptr<GlobalIndirectSymbol> GA; 1024 if (IsAlias) 1025 GA.reset(GlobalAlias::create(Ty, AddrSpace, 1026 (GlobalValue::LinkageTypes)Linkage, Name, 1027 Aliasee, /*Parent*/ nullptr)); 1028 else 1029 GA.reset(GlobalIFunc::create(Ty, AddrSpace, 1030 (GlobalValue::LinkageTypes)Linkage, Name, 1031 Aliasee, /*Parent*/ nullptr)); 1032 GA->setThreadLocalMode(TLM); 1033 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1034 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1035 GA->setUnnamedAddr(UnnamedAddr); 1036 maybeSetDSOLocal(DSOLocal, *GA); 1037 1038 // At this point we've parsed everything except for the IndirectSymbolAttrs. 1039 // Now parse them if there are any. 1040 while (Lex.getKind() == lltok::comma) { 1041 Lex.Lex(); 1042 1043 if (Lex.getKind() == lltok::kw_partition) { 1044 Lex.Lex(); 1045 GA->setPartition(Lex.getStrVal()); 1046 if (parseToken(lltok::StringConstant, "expected partition string")) 1047 return true; 1048 } else { 1049 return tokError("unknown alias or ifunc property!"); 1050 } 1051 } 1052 1053 if (Name.empty()) 1054 NumberedVals.push_back(GA.get()); 1055 1056 if (GVal) { 1057 // Verify that types agree. 1058 if (GVal->getType() != GA->getType()) 1059 return error( 1060 ExplicitTypeLoc, 1061 "forward reference and definition of alias have different types"); 1062 1063 // If they agree, just RAUW the old value with the alias and remove the 1064 // forward ref info. 1065 GVal->replaceAllUsesWith(GA.get()); 1066 GVal->eraseFromParent(); 1067 } 1068 1069 // Insert into the module, we know its name won't collide now. 1070 if (IsAlias) 1071 M->getAliasList().push_back(cast<GlobalAlias>(GA.get())); 1072 else 1073 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get())); 1074 assert(GA->getName() == Name && "Should not be a name conflict!"); 1075 1076 // The module owns this now 1077 GA.release(); 1078 1079 return false; 1080 } 1081 1082 /// parseGlobal 1083 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 1084 /// OptionalVisibility OptionalDLLStorageClass 1085 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace 1086 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs 1087 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 1088 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr 1089 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type 1090 /// Const OptionalAttrs 1091 /// 1092 /// Everything up to and including OptionalUnnamedAddr has been parsed 1093 /// already. 1094 /// 1095 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc, 1096 unsigned Linkage, bool HasLinkage, 1097 unsigned Visibility, unsigned DLLStorageClass, 1098 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM, 1099 GlobalVariable::UnnamedAddr UnnamedAddr) { 1100 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 1101 return error(NameLoc, 1102 "symbol with local linkage must have default visibility"); 1103 1104 unsigned AddrSpace; 1105 bool IsConstant, IsExternallyInitialized; 1106 LocTy IsExternallyInitializedLoc; 1107 LocTy TyLoc; 1108 1109 Type *Ty = nullptr; 1110 if (parseOptionalAddrSpace(AddrSpace) || 1111 parseOptionalToken(lltok::kw_externally_initialized, 1112 IsExternallyInitialized, 1113 &IsExternallyInitializedLoc) || 1114 parseGlobalType(IsConstant) || parseType(Ty, TyLoc)) 1115 return true; 1116 1117 // If the linkage is specified and is external, then no initializer is 1118 // present. 1119 Constant *Init = nullptr; 1120 if (!HasLinkage || 1121 !GlobalValue::isValidDeclarationLinkage( 1122 (GlobalValue::LinkageTypes)Linkage)) { 1123 if (parseGlobalValue(Ty, Init)) 1124 return true; 1125 } 1126 1127 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 1128 return error(TyLoc, "invalid type for global variable"); 1129 1130 GlobalValue *GVal = nullptr; 1131 1132 // See if the global was forward referenced, if so, use the global. 1133 if (!Name.empty()) { 1134 GVal = M->getNamedValue(Name); 1135 if (GVal) { 1136 if (!ForwardRefVals.erase(Name)) 1137 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1138 } 1139 } else { 1140 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1141 if (I != ForwardRefValIDs.end()) { 1142 GVal = I->second.first; 1143 ForwardRefValIDs.erase(I); 1144 } 1145 } 1146 1147 GlobalVariable *GV; 1148 if (!GVal) { 1149 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr, 1150 Name, nullptr, GlobalVariable::NotThreadLocal, 1151 AddrSpace); 1152 } else { 1153 if (GVal->getValueType() != Ty) 1154 return error( 1155 TyLoc, 1156 "forward reference and definition of global have different types"); 1157 1158 GV = cast<GlobalVariable>(GVal); 1159 1160 // Move the forward-reference to the correct spot in the module. 1161 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 1162 } 1163 1164 if (Name.empty()) 1165 NumberedVals.push_back(GV); 1166 1167 // Set the parsed properties on the global. 1168 if (Init) 1169 GV->setInitializer(Init); 1170 GV->setConstant(IsConstant); 1171 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 1172 maybeSetDSOLocal(DSOLocal, *GV); 1173 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1174 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1175 GV->setExternallyInitialized(IsExternallyInitialized); 1176 GV->setThreadLocalMode(TLM); 1177 GV->setUnnamedAddr(UnnamedAddr); 1178 1179 // parse attributes on the global. 1180 while (Lex.getKind() == lltok::comma) { 1181 Lex.Lex(); 1182 1183 if (Lex.getKind() == lltok::kw_section) { 1184 Lex.Lex(); 1185 GV->setSection(Lex.getStrVal()); 1186 if (parseToken(lltok::StringConstant, "expected global section string")) 1187 return true; 1188 } else if (Lex.getKind() == lltok::kw_partition) { 1189 Lex.Lex(); 1190 GV->setPartition(Lex.getStrVal()); 1191 if (parseToken(lltok::StringConstant, "expected partition string")) 1192 return true; 1193 } else if (Lex.getKind() == lltok::kw_align) { 1194 MaybeAlign Alignment; 1195 if (parseOptionalAlignment(Alignment)) 1196 return true; 1197 GV->setAlignment(Alignment); 1198 } else if (Lex.getKind() == lltok::MetadataVar) { 1199 if (parseGlobalObjectMetadataAttachment(*GV)) 1200 return true; 1201 } else { 1202 Comdat *C; 1203 if (parseOptionalComdat(Name, C)) 1204 return true; 1205 if (C) 1206 GV->setComdat(C); 1207 else 1208 return tokError("unknown global variable property!"); 1209 } 1210 } 1211 1212 AttrBuilder Attrs; 1213 LocTy BuiltinLoc; 1214 std::vector<unsigned> FwdRefAttrGrps; 1215 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc)) 1216 return true; 1217 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { 1218 GV->setAttributes(AttributeSet::get(Context, Attrs)); 1219 ForwardRefAttrGroups[GV] = FwdRefAttrGrps; 1220 } 1221 1222 return false; 1223 } 1224 1225 /// parseUnnamedAttrGrp 1226 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 1227 bool LLParser::parseUnnamedAttrGrp() { 1228 assert(Lex.getKind() == lltok::kw_attributes); 1229 LocTy AttrGrpLoc = Lex.getLoc(); 1230 Lex.Lex(); 1231 1232 if (Lex.getKind() != lltok::AttrGrpID) 1233 return tokError("expected attribute group id"); 1234 1235 unsigned VarID = Lex.getUIntVal(); 1236 std::vector<unsigned> unused; 1237 LocTy BuiltinLoc; 1238 Lex.Lex(); 1239 1240 if (parseToken(lltok::equal, "expected '=' here") || 1241 parseToken(lltok::lbrace, "expected '{' here") || 1242 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true, 1243 BuiltinLoc) || 1244 parseToken(lltok::rbrace, "expected end of attribute group")) 1245 return true; 1246 1247 if (!NumberedAttrBuilders[VarID].hasAttributes()) 1248 return error(AttrGrpLoc, "attribute group has no attributes"); 1249 1250 return false; 1251 } 1252 1253 /// parseFnAttributeValuePairs 1254 /// ::= <attr> | <attr> '=' <value> 1255 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B, 1256 std::vector<unsigned> &FwdRefAttrGrps, 1257 bool inAttrGrp, LocTy &BuiltinLoc) { 1258 bool HaveError = false; 1259 1260 B.clear(); 1261 1262 while (true) { 1263 lltok::Kind Token = Lex.getKind(); 1264 if (Token == lltok::kw_builtin) 1265 BuiltinLoc = Lex.getLoc(); 1266 switch (Token) { 1267 default: 1268 if (!inAttrGrp) return HaveError; 1269 return error(Lex.getLoc(), "unterminated attribute group"); 1270 case lltok::rbrace: 1271 // Finished. 1272 return false; 1273 1274 case lltok::AttrGrpID: { 1275 // Allow a function to reference an attribute group: 1276 // 1277 // define void @foo() #1 { ... } 1278 if (inAttrGrp) 1279 HaveError |= error( 1280 Lex.getLoc(), 1281 "cannot have an attribute group reference in an attribute group"); 1282 1283 unsigned AttrGrpNum = Lex.getUIntVal(); 1284 if (inAttrGrp) break; 1285 1286 // Save the reference to the attribute group. We'll fill it in later. 1287 FwdRefAttrGrps.push_back(AttrGrpNum); 1288 break; 1289 } 1290 // Target-dependent attributes: 1291 case lltok::StringConstant: { 1292 if (parseStringAttribute(B)) 1293 return true; 1294 continue; 1295 } 1296 1297 // Target-independent attributes: 1298 case lltok::kw_align: { 1299 // As a hack, we allow function alignment to be initially parsed as an 1300 // attribute on a function declaration/definition or added to an attribute 1301 // group and later moved to the alignment field. 1302 MaybeAlign Alignment; 1303 if (inAttrGrp) { 1304 Lex.Lex(); 1305 uint32_t Value = 0; 1306 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value)) 1307 return true; 1308 Alignment = Align(Value); 1309 } else { 1310 if (parseOptionalAlignment(Alignment)) 1311 return true; 1312 } 1313 B.addAlignmentAttr(Alignment); 1314 continue; 1315 } 1316 case lltok::kw_alignstack: { 1317 unsigned Alignment; 1318 if (inAttrGrp) { 1319 Lex.Lex(); 1320 if (parseToken(lltok::equal, "expected '=' here") || 1321 parseUInt32(Alignment)) 1322 return true; 1323 } else { 1324 if (parseOptionalStackAlignment(Alignment)) 1325 return true; 1326 } 1327 B.addStackAlignmentAttr(Alignment); 1328 continue; 1329 } 1330 case lltok::kw_allocsize: { 1331 unsigned ElemSizeArg; 1332 Optional<unsigned> NumElemsArg; 1333 // inAttrGrp doesn't matter; we only support allocsize(a[, b]) 1334 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg)) 1335 return true; 1336 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1337 continue; 1338 } 1339 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break; 1340 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break; 1341 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break; 1342 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break; 1343 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break; 1344 case lltok::kw_inaccessiblememonly: 1345 B.addAttribute(Attribute::InaccessibleMemOnly); break; 1346 case lltok::kw_inaccessiblemem_or_argmemonly: 1347 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break; 1348 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break; 1349 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break; 1350 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break; 1351 case lltok::kw_mustprogress: 1352 B.addAttribute(Attribute::MustProgress); 1353 break; 1354 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break; 1355 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break; 1356 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break; 1357 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break; 1358 case lltok::kw_noimplicitfloat: 1359 B.addAttribute(Attribute::NoImplicitFloat); break; 1360 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break; 1361 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break; 1362 case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break; 1363 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break; 1364 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break; 1365 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break; 1366 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break; 1367 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break; 1368 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break; 1369 case lltok::kw_null_pointer_is_valid: 1370 B.addAttribute(Attribute::NullPointerIsValid); break; 1371 case lltok::kw_optforfuzzing: 1372 B.addAttribute(Attribute::OptForFuzzing); break; 1373 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break; 1374 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break; 1375 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 1376 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 1377 case lltok::kw_returns_twice: 1378 B.addAttribute(Attribute::ReturnsTwice); break; 1379 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break; 1380 case lltok::kw_nossp: 1381 B.addAttribute(Attribute::NoStackProtect); 1382 break; 1383 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break; 1384 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break; 1385 case lltok::kw_sspstrong: 1386 B.addAttribute(Attribute::StackProtectStrong); break; 1387 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break; 1388 case lltok::kw_shadowcallstack: 1389 B.addAttribute(Attribute::ShadowCallStack); break; 1390 case lltok::kw_sanitize_address: 1391 B.addAttribute(Attribute::SanitizeAddress); break; 1392 case lltok::kw_sanitize_hwaddress: 1393 B.addAttribute(Attribute::SanitizeHWAddress); break; 1394 case lltok::kw_sanitize_memtag: 1395 B.addAttribute(Attribute::SanitizeMemTag); break; 1396 case lltok::kw_sanitize_thread: 1397 B.addAttribute(Attribute::SanitizeThread); break; 1398 case lltok::kw_sanitize_memory: 1399 B.addAttribute(Attribute::SanitizeMemory); break; 1400 case lltok::kw_speculative_load_hardening: 1401 B.addAttribute(Attribute::SpeculativeLoadHardening); 1402 break; 1403 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break; 1404 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break; 1405 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break; 1406 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break; 1407 case lltok::kw_preallocated: { 1408 Type *Ty; 1409 if (parsePreallocated(Ty)) 1410 return true; 1411 B.addPreallocatedAttr(Ty); 1412 break; 1413 } 1414 1415 // error handling. 1416 case lltok::kw_inreg: 1417 case lltok::kw_signext: 1418 case lltok::kw_zeroext: 1419 HaveError |= 1420 error(Lex.getLoc(), "invalid use of attribute on a function"); 1421 break; 1422 case lltok::kw_byval: 1423 case lltok::kw_dereferenceable: 1424 case lltok::kw_dereferenceable_or_null: 1425 case lltok::kw_inalloca: 1426 case lltok::kw_nest: 1427 case lltok::kw_noalias: 1428 case lltok::kw_noundef: 1429 case lltok::kw_nocapture: 1430 case lltok::kw_nonnull: 1431 case lltok::kw_returned: 1432 case lltok::kw_sret: 1433 case lltok::kw_swifterror: 1434 case lltok::kw_swiftself: 1435 case lltok::kw_immarg: 1436 case lltok::kw_byref: 1437 HaveError |= 1438 error(Lex.getLoc(), 1439 "invalid use of parameter-only attribute on a function"); 1440 break; 1441 } 1442 1443 // parsePreallocated() consumes token 1444 if (Token != lltok::kw_preallocated) 1445 Lex.Lex(); 1446 } 1447 } 1448 1449 //===----------------------------------------------------------------------===// 1450 // GlobalValue Reference/Resolution Routines. 1451 //===----------------------------------------------------------------------===// 1452 1453 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy, 1454 const std::string &Name) { 1455 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType())) 1456 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, 1457 PTy->getAddressSpace(), Name, M); 1458 else 1459 return new GlobalVariable(*M, PTy->getElementType(), false, 1460 GlobalValue::ExternalWeakLinkage, nullptr, Name, 1461 nullptr, GlobalVariable::NotThreadLocal, 1462 PTy->getAddressSpace()); 1463 } 1464 1465 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty, 1466 Value *Val, bool IsCall) { 1467 if (Val->getType() == Ty) 1468 return Val; 1469 // For calls we also accept variables in the program address space. 1470 Type *SuggestedTy = Ty; 1471 if (IsCall && isa<PointerType>(Ty)) { 1472 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo( 1473 M->getDataLayout().getProgramAddressSpace()); 1474 SuggestedTy = TyInProgAS; 1475 if (Val->getType() == TyInProgAS) 1476 return Val; 1477 } 1478 if (Ty->isLabelTy()) 1479 error(Loc, "'" + Name + "' is not a basic block"); 1480 else 1481 error(Loc, "'" + Name + "' defined with type '" + 1482 getTypeString(Val->getType()) + "' but expected '" + 1483 getTypeString(SuggestedTy) + "'"); 1484 return nullptr; 1485 } 1486 1487 /// getGlobalVal - Get a value with the specified name or ID, creating a 1488 /// forward reference record if needed. This can return null if the value 1489 /// exists but does not have the right type. 1490 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty, 1491 LocTy Loc, bool IsCall) { 1492 PointerType *PTy = dyn_cast<PointerType>(Ty); 1493 if (!PTy) { 1494 error(Loc, "global variable reference must have pointer type"); 1495 return nullptr; 1496 } 1497 1498 // Look this name up in the normal function symbol table. 1499 GlobalValue *Val = 1500 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 1501 1502 // If this is a forward reference for the value, see if we already created a 1503 // forward ref record. 1504 if (!Val) { 1505 auto I = ForwardRefVals.find(Name); 1506 if (I != ForwardRefVals.end()) 1507 Val = I->second.first; 1508 } 1509 1510 // If we have the value in the symbol table or fwd-ref table, return it. 1511 if (Val) 1512 return cast_or_null<GlobalValue>( 1513 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall)); 1514 1515 // Otherwise, create a new forward reference for this value and remember it. 1516 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name); 1517 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1518 return FwdVal; 1519 } 1520 1521 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc, 1522 bool IsCall) { 1523 PointerType *PTy = dyn_cast<PointerType>(Ty); 1524 if (!PTy) { 1525 error(Loc, "global variable reference must have pointer type"); 1526 return nullptr; 1527 } 1528 1529 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 1530 1531 // If this is a forward reference for the value, see if we already created a 1532 // forward ref record. 1533 if (!Val) { 1534 auto I = ForwardRefValIDs.find(ID); 1535 if (I != ForwardRefValIDs.end()) 1536 Val = I->second.first; 1537 } 1538 1539 // If we have the value in the symbol table or fwd-ref table, return it. 1540 if (Val) 1541 return cast_or_null<GlobalValue>( 1542 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall)); 1543 1544 // Otherwise, create a new forward reference for this value and remember it. 1545 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, ""); 1546 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1547 return FwdVal; 1548 } 1549 1550 //===----------------------------------------------------------------------===// 1551 // Comdat Reference/Resolution Routines. 1552 //===----------------------------------------------------------------------===// 1553 1554 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) { 1555 // Look this name up in the comdat symbol table. 1556 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 1557 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 1558 if (I != ComdatSymTab.end()) 1559 return &I->second; 1560 1561 // Otherwise, create a new forward reference for this value and remember it. 1562 Comdat *C = M->getOrInsertComdat(Name); 1563 ForwardRefComdats[Name] = Loc; 1564 return C; 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Helper Routines. 1569 //===----------------------------------------------------------------------===// 1570 1571 /// parseToken - If the current token has the specified kind, eat it and return 1572 /// success. Otherwise, emit the specified error and return failure. 1573 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) { 1574 if (Lex.getKind() != T) 1575 return tokError(ErrMsg); 1576 Lex.Lex(); 1577 return false; 1578 } 1579 1580 /// parseStringConstant 1581 /// ::= StringConstant 1582 bool LLParser::parseStringConstant(std::string &Result) { 1583 if (Lex.getKind() != lltok::StringConstant) 1584 return tokError("expected string constant"); 1585 Result = Lex.getStrVal(); 1586 Lex.Lex(); 1587 return false; 1588 } 1589 1590 /// parseUInt32 1591 /// ::= uint32 1592 bool LLParser::parseUInt32(uint32_t &Val) { 1593 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1594 return tokError("expected integer"); 1595 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 1596 if (Val64 != unsigned(Val64)) 1597 return tokError("expected 32-bit integer (too large)"); 1598 Val = Val64; 1599 Lex.Lex(); 1600 return false; 1601 } 1602 1603 /// parseUInt64 1604 /// ::= uint64 1605 bool LLParser::parseUInt64(uint64_t &Val) { 1606 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1607 return tokError("expected integer"); 1608 Val = Lex.getAPSIntVal().getLimitedValue(); 1609 Lex.Lex(); 1610 return false; 1611 } 1612 1613 /// parseTLSModel 1614 /// := 'localdynamic' 1615 /// := 'initialexec' 1616 /// := 'localexec' 1617 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 1618 switch (Lex.getKind()) { 1619 default: 1620 return tokError("expected localdynamic, initialexec or localexec"); 1621 case lltok::kw_localdynamic: 1622 TLM = GlobalVariable::LocalDynamicTLSModel; 1623 break; 1624 case lltok::kw_initialexec: 1625 TLM = GlobalVariable::InitialExecTLSModel; 1626 break; 1627 case lltok::kw_localexec: 1628 TLM = GlobalVariable::LocalExecTLSModel; 1629 break; 1630 } 1631 1632 Lex.Lex(); 1633 return false; 1634 } 1635 1636 /// parseOptionalThreadLocal 1637 /// := /*empty*/ 1638 /// := 'thread_local' 1639 /// := 'thread_local' '(' tlsmodel ')' 1640 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 1641 TLM = GlobalVariable::NotThreadLocal; 1642 if (!EatIfPresent(lltok::kw_thread_local)) 1643 return false; 1644 1645 TLM = GlobalVariable::GeneralDynamicTLSModel; 1646 if (Lex.getKind() == lltok::lparen) { 1647 Lex.Lex(); 1648 return parseTLSModel(TLM) || 1649 parseToken(lltok::rparen, "expected ')' after thread local model"); 1650 } 1651 return false; 1652 } 1653 1654 /// parseOptionalAddrSpace 1655 /// := /*empty*/ 1656 /// := 'addrspace' '(' uint32 ')' 1657 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) { 1658 AddrSpace = DefaultAS; 1659 if (!EatIfPresent(lltok::kw_addrspace)) 1660 return false; 1661 return parseToken(lltok::lparen, "expected '(' in address space") || 1662 parseUInt32(AddrSpace) || 1663 parseToken(lltok::rparen, "expected ')' in address space"); 1664 } 1665 1666 /// parseStringAttribute 1667 /// := StringConstant 1668 /// := StringConstant '=' StringConstant 1669 bool LLParser::parseStringAttribute(AttrBuilder &B) { 1670 std::string Attr = Lex.getStrVal(); 1671 Lex.Lex(); 1672 std::string Val; 1673 if (EatIfPresent(lltok::equal) && parseStringConstant(Val)) 1674 return true; 1675 B.addAttribute(Attr, Val); 1676 return false; 1677 } 1678 1679 /// parseOptionalParamAttrs - parse a potentially empty list of parameter 1680 /// attributes. 1681 bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) { 1682 bool HaveError = false; 1683 1684 B.clear(); 1685 1686 while (true) { 1687 lltok::Kind Token = Lex.getKind(); 1688 switch (Token) { 1689 default: // End of attributes. 1690 return HaveError; 1691 case lltok::StringConstant: { 1692 if (parseStringAttribute(B)) 1693 return true; 1694 continue; 1695 } 1696 case lltok::kw_align: { 1697 MaybeAlign Alignment; 1698 if (parseOptionalAlignment(Alignment, true)) 1699 return true; 1700 B.addAlignmentAttr(Alignment); 1701 continue; 1702 } 1703 case lltok::kw_byval: { 1704 Type *Ty; 1705 if (parseOptionalTypeAttr(Ty, lltok::kw_byval)) 1706 return true; 1707 B.addByValAttr(Ty); 1708 continue; 1709 } 1710 case lltok::kw_sret: { 1711 Type *Ty; 1712 if (parseOptionalTypeAttr(Ty, lltok::kw_sret)) 1713 return true; 1714 B.addStructRetAttr(Ty); 1715 continue; 1716 } 1717 case lltok::kw_preallocated: { 1718 Type *Ty; 1719 if (parsePreallocated(Ty)) 1720 return true; 1721 B.addPreallocatedAttr(Ty); 1722 continue; 1723 } 1724 case lltok::kw_dereferenceable: { 1725 uint64_t Bytes; 1726 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1727 return true; 1728 B.addDereferenceableAttr(Bytes); 1729 continue; 1730 } 1731 case lltok::kw_dereferenceable_or_null: { 1732 uint64_t Bytes; 1733 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1734 return true; 1735 B.addDereferenceableOrNullAttr(Bytes); 1736 continue; 1737 } 1738 case lltok::kw_byref: { 1739 Type *Ty; 1740 if (parseByRef(Ty)) 1741 return true; 1742 B.addByRefAttr(Ty); 1743 continue; 1744 } 1745 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break; 1746 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1747 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break; 1748 case lltok::kw_noundef: 1749 B.addAttribute(Attribute::NoUndef); 1750 break; 1751 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1752 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break; 1753 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break; 1754 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break; 1755 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 1756 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 1757 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break; 1758 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1759 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break; 1760 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break; 1761 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break; 1762 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1763 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break; 1764 1765 case lltok::kw_alignstack: 1766 case lltok::kw_alwaysinline: 1767 case lltok::kw_argmemonly: 1768 case lltok::kw_builtin: 1769 case lltok::kw_inlinehint: 1770 case lltok::kw_jumptable: 1771 case lltok::kw_minsize: 1772 case lltok::kw_mustprogress: 1773 case lltok::kw_naked: 1774 case lltok::kw_nobuiltin: 1775 case lltok::kw_noduplicate: 1776 case lltok::kw_noimplicitfloat: 1777 case lltok::kw_noinline: 1778 case lltok::kw_nonlazybind: 1779 case lltok::kw_nomerge: 1780 case lltok::kw_noredzone: 1781 case lltok::kw_noreturn: 1782 case lltok::kw_nocf_check: 1783 case lltok::kw_nounwind: 1784 case lltok::kw_optforfuzzing: 1785 case lltok::kw_optnone: 1786 case lltok::kw_optsize: 1787 case lltok::kw_returns_twice: 1788 case lltok::kw_sanitize_address: 1789 case lltok::kw_sanitize_hwaddress: 1790 case lltok::kw_sanitize_memtag: 1791 case lltok::kw_sanitize_memory: 1792 case lltok::kw_sanitize_thread: 1793 case lltok::kw_speculative_load_hardening: 1794 case lltok::kw_nossp: 1795 case lltok::kw_ssp: 1796 case lltok::kw_sspreq: 1797 case lltok::kw_sspstrong: 1798 case lltok::kw_safestack: 1799 case lltok::kw_shadowcallstack: 1800 case lltok::kw_strictfp: 1801 case lltok::kw_uwtable: 1802 HaveError |= 1803 error(Lex.getLoc(), "invalid use of function-only attribute"); 1804 break; 1805 } 1806 1807 Lex.Lex(); 1808 } 1809 } 1810 1811 /// parseOptionalReturnAttrs - parse a potentially empty list of return 1812 /// attributes. 1813 bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) { 1814 bool HaveError = false; 1815 1816 B.clear(); 1817 1818 while (true) { 1819 lltok::Kind Token = Lex.getKind(); 1820 switch (Token) { 1821 default: // End of attributes. 1822 return HaveError; 1823 case lltok::StringConstant: { 1824 if (parseStringAttribute(B)) 1825 return true; 1826 continue; 1827 } 1828 case lltok::kw_dereferenceable: { 1829 uint64_t Bytes; 1830 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1831 return true; 1832 B.addDereferenceableAttr(Bytes); 1833 continue; 1834 } 1835 case lltok::kw_dereferenceable_or_null: { 1836 uint64_t Bytes; 1837 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1838 return true; 1839 B.addDereferenceableOrNullAttr(Bytes); 1840 continue; 1841 } 1842 case lltok::kw_align: { 1843 MaybeAlign Alignment; 1844 if (parseOptionalAlignment(Alignment)) 1845 return true; 1846 B.addAlignmentAttr(Alignment); 1847 continue; 1848 } 1849 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1850 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1851 case lltok::kw_noundef: 1852 B.addAttribute(Attribute::NoUndef); 1853 break; 1854 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break; 1855 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1856 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1857 1858 // error handling. 1859 case lltok::kw_byval: 1860 case lltok::kw_inalloca: 1861 case lltok::kw_nest: 1862 case lltok::kw_nocapture: 1863 case lltok::kw_returned: 1864 case lltok::kw_sret: 1865 case lltok::kw_swifterror: 1866 case lltok::kw_swiftself: 1867 case lltok::kw_immarg: 1868 case lltok::kw_byref: 1869 HaveError |= 1870 error(Lex.getLoc(), "invalid use of parameter-only attribute"); 1871 break; 1872 1873 case lltok::kw_alignstack: 1874 case lltok::kw_alwaysinline: 1875 case lltok::kw_argmemonly: 1876 case lltok::kw_builtin: 1877 case lltok::kw_cold: 1878 case lltok::kw_inlinehint: 1879 case lltok::kw_jumptable: 1880 case lltok::kw_minsize: 1881 case lltok::kw_mustprogress: 1882 case lltok::kw_naked: 1883 case lltok::kw_nobuiltin: 1884 case lltok::kw_noduplicate: 1885 case lltok::kw_noimplicitfloat: 1886 case lltok::kw_noinline: 1887 case lltok::kw_nonlazybind: 1888 case lltok::kw_nomerge: 1889 case lltok::kw_noredzone: 1890 case lltok::kw_noreturn: 1891 case lltok::kw_nocf_check: 1892 case lltok::kw_nounwind: 1893 case lltok::kw_optforfuzzing: 1894 case lltok::kw_optnone: 1895 case lltok::kw_optsize: 1896 case lltok::kw_returns_twice: 1897 case lltok::kw_sanitize_address: 1898 case lltok::kw_sanitize_hwaddress: 1899 case lltok::kw_sanitize_memtag: 1900 case lltok::kw_sanitize_memory: 1901 case lltok::kw_sanitize_thread: 1902 case lltok::kw_speculative_load_hardening: 1903 case lltok::kw_nossp: 1904 case lltok::kw_ssp: 1905 case lltok::kw_sspreq: 1906 case lltok::kw_sspstrong: 1907 case lltok::kw_safestack: 1908 case lltok::kw_shadowcallstack: 1909 case lltok::kw_strictfp: 1910 case lltok::kw_uwtable: 1911 HaveError |= 1912 error(Lex.getLoc(), "invalid use of function-only attribute"); 1913 break; 1914 case lltok::kw_readnone: 1915 case lltok::kw_readonly: 1916 HaveError |= 1917 error(Lex.getLoc(), "invalid use of attribute on return type"); 1918 break; 1919 case lltok::kw_preallocated: 1920 HaveError |= 1921 error(Lex.getLoc(), 1922 "invalid use of parameter-only/call site-only attribute"); 1923 break; 1924 } 1925 1926 Lex.Lex(); 1927 } 1928 } 1929 1930 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) { 1931 HasLinkage = true; 1932 switch (Kind) { 1933 default: 1934 HasLinkage = false; 1935 return GlobalValue::ExternalLinkage; 1936 case lltok::kw_private: 1937 return GlobalValue::PrivateLinkage; 1938 case lltok::kw_internal: 1939 return GlobalValue::InternalLinkage; 1940 case lltok::kw_weak: 1941 return GlobalValue::WeakAnyLinkage; 1942 case lltok::kw_weak_odr: 1943 return GlobalValue::WeakODRLinkage; 1944 case lltok::kw_linkonce: 1945 return GlobalValue::LinkOnceAnyLinkage; 1946 case lltok::kw_linkonce_odr: 1947 return GlobalValue::LinkOnceODRLinkage; 1948 case lltok::kw_available_externally: 1949 return GlobalValue::AvailableExternallyLinkage; 1950 case lltok::kw_appending: 1951 return GlobalValue::AppendingLinkage; 1952 case lltok::kw_common: 1953 return GlobalValue::CommonLinkage; 1954 case lltok::kw_extern_weak: 1955 return GlobalValue::ExternalWeakLinkage; 1956 case lltok::kw_external: 1957 return GlobalValue::ExternalLinkage; 1958 } 1959 } 1960 1961 /// parseOptionalLinkage 1962 /// ::= /*empty*/ 1963 /// ::= 'private' 1964 /// ::= 'internal' 1965 /// ::= 'weak' 1966 /// ::= 'weak_odr' 1967 /// ::= 'linkonce' 1968 /// ::= 'linkonce_odr' 1969 /// ::= 'available_externally' 1970 /// ::= 'appending' 1971 /// ::= 'common' 1972 /// ::= 'extern_weak' 1973 /// ::= 'external' 1974 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage, 1975 unsigned &Visibility, 1976 unsigned &DLLStorageClass, bool &DSOLocal) { 1977 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 1978 if (HasLinkage) 1979 Lex.Lex(); 1980 parseOptionalDSOLocal(DSOLocal); 1981 parseOptionalVisibility(Visibility); 1982 parseOptionalDLLStorageClass(DLLStorageClass); 1983 1984 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) { 1985 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch"); 1986 } 1987 1988 return false; 1989 } 1990 1991 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) { 1992 switch (Lex.getKind()) { 1993 default: 1994 DSOLocal = false; 1995 break; 1996 case lltok::kw_dso_local: 1997 DSOLocal = true; 1998 Lex.Lex(); 1999 break; 2000 case lltok::kw_dso_preemptable: 2001 DSOLocal = false; 2002 Lex.Lex(); 2003 break; 2004 } 2005 } 2006 2007 /// parseOptionalVisibility 2008 /// ::= /*empty*/ 2009 /// ::= 'default' 2010 /// ::= 'hidden' 2011 /// ::= 'protected' 2012 /// 2013 void LLParser::parseOptionalVisibility(unsigned &Res) { 2014 switch (Lex.getKind()) { 2015 default: 2016 Res = GlobalValue::DefaultVisibility; 2017 return; 2018 case lltok::kw_default: 2019 Res = GlobalValue::DefaultVisibility; 2020 break; 2021 case lltok::kw_hidden: 2022 Res = GlobalValue::HiddenVisibility; 2023 break; 2024 case lltok::kw_protected: 2025 Res = GlobalValue::ProtectedVisibility; 2026 break; 2027 } 2028 Lex.Lex(); 2029 } 2030 2031 /// parseOptionalDLLStorageClass 2032 /// ::= /*empty*/ 2033 /// ::= 'dllimport' 2034 /// ::= 'dllexport' 2035 /// 2036 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) { 2037 switch (Lex.getKind()) { 2038 default: 2039 Res = GlobalValue::DefaultStorageClass; 2040 return; 2041 case lltok::kw_dllimport: 2042 Res = GlobalValue::DLLImportStorageClass; 2043 break; 2044 case lltok::kw_dllexport: 2045 Res = GlobalValue::DLLExportStorageClass; 2046 break; 2047 } 2048 Lex.Lex(); 2049 } 2050 2051 /// parseOptionalCallingConv 2052 /// ::= /*empty*/ 2053 /// ::= 'ccc' 2054 /// ::= 'fastcc' 2055 /// ::= 'intel_ocl_bicc' 2056 /// ::= 'coldcc' 2057 /// ::= 'cfguard_checkcc' 2058 /// ::= 'x86_stdcallcc' 2059 /// ::= 'x86_fastcallcc' 2060 /// ::= 'x86_thiscallcc' 2061 /// ::= 'x86_vectorcallcc' 2062 /// ::= 'arm_apcscc' 2063 /// ::= 'arm_aapcscc' 2064 /// ::= 'arm_aapcs_vfpcc' 2065 /// ::= 'aarch64_vector_pcs' 2066 /// ::= 'aarch64_sve_vector_pcs' 2067 /// ::= 'msp430_intrcc' 2068 /// ::= 'avr_intrcc' 2069 /// ::= 'avr_signalcc' 2070 /// ::= 'ptx_kernel' 2071 /// ::= 'ptx_device' 2072 /// ::= 'spir_func' 2073 /// ::= 'spir_kernel' 2074 /// ::= 'x86_64_sysvcc' 2075 /// ::= 'win64cc' 2076 /// ::= 'webkit_jscc' 2077 /// ::= 'anyregcc' 2078 /// ::= 'preserve_mostcc' 2079 /// ::= 'preserve_allcc' 2080 /// ::= 'ghccc' 2081 /// ::= 'swiftcc' 2082 /// ::= 'x86_intrcc' 2083 /// ::= 'hhvmcc' 2084 /// ::= 'hhvm_ccc' 2085 /// ::= 'cxx_fast_tlscc' 2086 /// ::= 'amdgpu_vs' 2087 /// ::= 'amdgpu_ls' 2088 /// ::= 'amdgpu_hs' 2089 /// ::= 'amdgpu_es' 2090 /// ::= 'amdgpu_gs' 2091 /// ::= 'amdgpu_ps' 2092 /// ::= 'amdgpu_cs' 2093 /// ::= 'amdgpu_kernel' 2094 /// ::= 'tailcc' 2095 /// ::= 'cc' UINT 2096 /// 2097 bool LLParser::parseOptionalCallingConv(unsigned &CC) { 2098 switch (Lex.getKind()) { 2099 default: CC = CallingConv::C; return false; 2100 case lltok::kw_ccc: CC = CallingConv::C; break; 2101 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 2102 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 2103 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break; 2104 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 2105 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 2106 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break; 2107 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 2108 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break; 2109 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 2110 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 2111 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 2112 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break; 2113 case lltok::kw_aarch64_sve_vector_pcs: 2114 CC = CallingConv::AArch64_SVE_VectorCall; 2115 break; 2116 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 2117 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break; 2118 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break; 2119 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 2120 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 2121 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 2122 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 2123 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 2124 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; 2125 case lltok::kw_win64cc: CC = CallingConv::Win64; break; 2126 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break; 2127 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; 2128 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; 2129 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; 2130 case lltok::kw_ghccc: CC = CallingConv::GHC; break; 2131 case lltok::kw_swiftcc: CC = CallingConv::Swift; break; 2132 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break; 2133 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break; 2134 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break; 2135 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break; 2136 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break; 2137 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break; 2138 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break; 2139 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; 2140 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break; 2141 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; 2142 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; 2143 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; 2144 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; 2145 case lltok::kw_tailcc: CC = CallingConv::Tail; break; 2146 case lltok::kw_cc: { 2147 Lex.Lex(); 2148 return parseUInt32(CC); 2149 } 2150 } 2151 2152 Lex.Lex(); 2153 return false; 2154 } 2155 2156 /// parseMetadataAttachment 2157 /// ::= !dbg !42 2158 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) { 2159 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"); 2160 2161 std::string Name = Lex.getStrVal(); 2162 Kind = M->getMDKindID(Name); 2163 Lex.Lex(); 2164 2165 return parseMDNode(MD); 2166 } 2167 2168 /// parseInstructionMetadata 2169 /// ::= !dbg !42 (',' !dbg !57)* 2170 bool LLParser::parseInstructionMetadata(Instruction &Inst) { 2171 do { 2172 if (Lex.getKind() != lltok::MetadataVar) 2173 return tokError("expected metadata after comma"); 2174 2175 unsigned MDK; 2176 MDNode *N; 2177 if (parseMetadataAttachment(MDK, N)) 2178 return true; 2179 2180 Inst.setMetadata(MDK, N); 2181 if (MDK == LLVMContext::MD_tbaa) 2182 InstsWithTBAATag.push_back(&Inst); 2183 2184 // If this is the end of the list, we're done. 2185 } while (EatIfPresent(lltok::comma)); 2186 return false; 2187 } 2188 2189 /// parseGlobalObjectMetadataAttachment 2190 /// ::= !dbg !57 2191 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) { 2192 unsigned MDK; 2193 MDNode *N; 2194 if (parseMetadataAttachment(MDK, N)) 2195 return true; 2196 2197 GO.addMetadata(MDK, *N); 2198 return false; 2199 } 2200 2201 /// parseOptionalFunctionMetadata 2202 /// ::= (!dbg !57)* 2203 bool LLParser::parseOptionalFunctionMetadata(Function &F) { 2204 while (Lex.getKind() == lltok::MetadataVar) 2205 if (parseGlobalObjectMetadataAttachment(F)) 2206 return true; 2207 return false; 2208 } 2209 2210 /// parseOptionalAlignment 2211 /// ::= /* empty */ 2212 /// ::= 'align' 4 2213 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) { 2214 Alignment = None; 2215 if (!EatIfPresent(lltok::kw_align)) 2216 return false; 2217 LocTy AlignLoc = Lex.getLoc(); 2218 uint32_t Value = 0; 2219 2220 LocTy ParenLoc = Lex.getLoc(); 2221 bool HaveParens = false; 2222 if (AllowParens) { 2223 if (EatIfPresent(lltok::lparen)) 2224 HaveParens = true; 2225 } 2226 2227 if (parseUInt32(Value)) 2228 return true; 2229 2230 if (HaveParens && !EatIfPresent(lltok::rparen)) 2231 return error(ParenLoc, "expected ')'"); 2232 2233 if (!isPowerOf2_32(Value)) 2234 return error(AlignLoc, "alignment is not a power of two"); 2235 if (Value > Value::MaximumAlignment) 2236 return error(AlignLoc, "huge alignments are not supported yet"); 2237 Alignment = Align(Value); 2238 return false; 2239 } 2240 2241 /// parseOptionalDerefAttrBytes 2242 /// ::= /* empty */ 2243 /// ::= AttrKind '(' 4 ')' 2244 /// 2245 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'. 2246 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind, 2247 uint64_t &Bytes) { 2248 assert((AttrKind == lltok::kw_dereferenceable || 2249 AttrKind == lltok::kw_dereferenceable_or_null) && 2250 "contract!"); 2251 2252 Bytes = 0; 2253 if (!EatIfPresent(AttrKind)) 2254 return false; 2255 LocTy ParenLoc = Lex.getLoc(); 2256 if (!EatIfPresent(lltok::lparen)) 2257 return error(ParenLoc, "expected '('"); 2258 LocTy DerefLoc = Lex.getLoc(); 2259 if (parseUInt64(Bytes)) 2260 return true; 2261 ParenLoc = Lex.getLoc(); 2262 if (!EatIfPresent(lltok::rparen)) 2263 return error(ParenLoc, "expected ')'"); 2264 if (!Bytes) 2265 return error(DerefLoc, "dereferenceable bytes must be non-zero"); 2266 return false; 2267 } 2268 2269 /// parseOptionalCommaAlign 2270 /// ::= 2271 /// ::= ',' align 4 2272 /// 2273 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2274 /// end. 2275 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment, 2276 bool &AteExtraComma) { 2277 AteExtraComma = false; 2278 while (EatIfPresent(lltok::comma)) { 2279 // Metadata at the end is an early exit. 2280 if (Lex.getKind() == lltok::MetadataVar) { 2281 AteExtraComma = true; 2282 return false; 2283 } 2284 2285 if (Lex.getKind() != lltok::kw_align) 2286 return error(Lex.getLoc(), "expected metadata or 'align'"); 2287 2288 if (parseOptionalAlignment(Alignment)) 2289 return true; 2290 } 2291 2292 return false; 2293 } 2294 2295 /// parseOptionalCommaAddrSpace 2296 /// ::= 2297 /// ::= ',' addrspace(1) 2298 /// 2299 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2300 /// end. 2301 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc, 2302 bool &AteExtraComma) { 2303 AteExtraComma = false; 2304 while (EatIfPresent(lltok::comma)) { 2305 // Metadata at the end is an early exit. 2306 if (Lex.getKind() == lltok::MetadataVar) { 2307 AteExtraComma = true; 2308 return false; 2309 } 2310 2311 Loc = Lex.getLoc(); 2312 if (Lex.getKind() != lltok::kw_addrspace) 2313 return error(Lex.getLoc(), "expected metadata or 'addrspace'"); 2314 2315 if (parseOptionalAddrSpace(AddrSpace)) 2316 return true; 2317 } 2318 2319 return false; 2320 } 2321 2322 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, 2323 Optional<unsigned> &HowManyArg) { 2324 Lex.Lex(); 2325 2326 auto StartParen = Lex.getLoc(); 2327 if (!EatIfPresent(lltok::lparen)) 2328 return error(StartParen, "expected '('"); 2329 2330 if (parseUInt32(BaseSizeArg)) 2331 return true; 2332 2333 if (EatIfPresent(lltok::comma)) { 2334 auto HowManyAt = Lex.getLoc(); 2335 unsigned HowMany; 2336 if (parseUInt32(HowMany)) 2337 return true; 2338 if (HowMany == BaseSizeArg) 2339 return error(HowManyAt, 2340 "'allocsize' indices can't refer to the same parameter"); 2341 HowManyArg = HowMany; 2342 } else 2343 HowManyArg = None; 2344 2345 auto EndParen = Lex.getLoc(); 2346 if (!EatIfPresent(lltok::rparen)) 2347 return error(EndParen, "expected ')'"); 2348 return false; 2349 } 2350 2351 /// parseScopeAndOrdering 2352 /// if isAtomic: ::= SyncScope? AtomicOrdering 2353 /// else: ::= 2354 /// 2355 /// This sets Scope and Ordering to the parsed values. 2356 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID, 2357 AtomicOrdering &Ordering) { 2358 if (!IsAtomic) 2359 return false; 2360 2361 return parseScope(SSID) || parseOrdering(Ordering); 2362 } 2363 2364 /// parseScope 2365 /// ::= syncscope("singlethread" | "<target scope>")? 2366 /// 2367 /// This sets synchronization scope ID to the ID of the parsed value. 2368 bool LLParser::parseScope(SyncScope::ID &SSID) { 2369 SSID = SyncScope::System; 2370 if (EatIfPresent(lltok::kw_syncscope)) { 2371 auto StartParenAt = Lex.getLoc(); 2372 if (!EatIfPresent(lltok::lparen)) 2373 return error(StartParenAt, "Expected '(' in syncscope"); 2374 2375 std::string SSN; 2376 auto SSNAt = Lex.getLoc(); 2377 if (parseStringConstant(SSN)) 2378 return error(SSNAt, "Expected synchronization scope name"); 2379 2380 auto EndParenAt = Lex.getLoc(); 2381 if (!EatIfPresent(lltok::rparen)) 2382 return error(EndParenAt, "Expected ')' in syncscope"); 2383 2384 SSID = Context.getOrInsertSyncScopeID(SSN); 2385 } 2386 2387 return false; 2388 } 2389 2390 /// parseOrdering 2391 /// ::= AtomicOrdering 2392 /// 2393 /// This sets Ordering to the parsed value. 2394 bool LLParser::parseOrdering(AtomicOrdering &Ordering) { 2395 switch (Lex.getKind()) { 2396 default: 2397 return tokError("Expected ordering on atomic instruction"); 2398 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; 2399 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; 2400 // Not specified yet: 2401 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; 2402 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; 2403 case lltok::kw_release: Ordering = AtomicOrdering::Release; break; 2404 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; 2405 case lltok::kw_seq_cst: 2406 Ordering = AtomicOrdering::SequentiallyConsistent; 2407 break; 2408 } 2409 Lex.Lex(); 2410 return false; 2411 } 2412 2413 /// parseOptionalStackAlignment 2414 /// ::= /* empty */ 2415 /// ::= 'alignstack' '(' 4 ')' 2416 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) { 2417 Alignment = 0; 2418 if (!EatIfPresent(lltok::kw_alignstack)) 2419 return false; 2420 LocTy ParenLoc = Lex.getLoc(); 2421 if (!EatIfPresent(lltok::lparen)) 2422 return error(ParenLoc, "expected '('"); 2423 LocTy AlignLoc = Lex.getLoc(); 2424 if (parseUInt32(Alignment)) 2425 return true; 2426 ParenLoc = Lex.getLoc(); 2427 if (!EatIfPresent(lltok::rparen)) 2428 return error(ParenLoc, "expected ')'"); 2429 if (!isPowerOf2_32(Alignment)) 2430 return error(AlignLoc, "stack alignment is not a power of two"); 2431 return false; 2432 } 2433 2434 /// parseIndexList - This parses the index list for an insert/extractvalue 2435 /// instruction. This sets AteExtraComma in the case where we eat an extra 2436 /// comma at the end of the line and find that it is followed by metadata. 2437 /// Clients that don't allow metadata can call the version of this function that 2438 /// only takes one argument. 2439 /// 2440 /// parseIndexList 2441 /// ::= (',' uint32)+ 2442 /// 2443 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices, 2444 bool &AteExtraComma) { 2445 AteExtraComma = false; 2446 2447 if (Lex.getKind() != lltok::comma) 2448 return tokError("expected ',' as start of index list"); 2449 2450 while (EatIfPresent(lltok::comma)) { 2451 if (Lex.getKind() == lltok::MetadataVar) { 2452 if (Indices.empty()) 2453 return tokError("expected index"); 2454 AteExtraComma = true; 2455 return false; 2456 } 2457 unsigned Idx = 0; 2458 if (parseUInt32(Idx)) 2459 return true; 2460 Indices.push_back(Idx); 2461 } 2462 2463 return false; 2464 } 2465 2466 //===----------------------------------------------------------------------===// 2467 // Type Parsing. 2468 //===----------------------------------------------------------------------===// 2469 2470 /// parseType - parse a type. 2471 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) { 2472 SMLoc TypeLoc = Lex.getLoc(); 2473 switch (Lex.getKind()) { 2474 default: 2475 return tokError(Msg); 2476 case lltok::Type: 2477 // Type ::= 'float' | 'void' (etc) 2478 Result = Lex.getTyVal(); 2479 Lex.Lex(); 2480 break; 2481 case lltok::lbrace: 2482 // Type ::= StructType 2483 if (parseAnonStructType(Result, false)) 2484 return true; 2485 break; 2486 case lltok::lsquare: 2487 // Type ::= '[' ... ']' 2488 Lex.Lex(); // eat the lsquare. 2489 if (parseArrayVectorType(Result, false)) 2490 return true; 2491 break; 2492 case lltok::less: // Either vector or packed struct. 2493 // Type ::= '<' ... '>' 2494 Lex.Lex(); 2495 if (Lex.getKind() == lltok::lbrace) { 2496 if (parseAnonStructType(Result, true) || 2497 parseToken(lltok::greater, "expected '>' at end of packed struct")) 2498 return true; 2499 } else if (parseArrayVectorType(Result, true)) 2500 return true; 2501 break; 2502 case lltok::LocalVar: { 2503 // Type ::= %foo 2504 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 2505 2506 // If the type hasn't been defined yet, create a forward definition and 2507 // remember where that forward def'n was seen (in case it never is defined). 2508 if (!Entry.first) { 2509 Entry.first = StructType::create(Context, Lex.getStrVal()); 2510 Entry.second = Lex.getLoc(); 2511 } 2512 Result = Entry.first; 2513 Lex.Lex(); 2514 break; 2515 } 2516 2517 case lltok::LocalVarID: { 2518 // Type ::= %4 2519 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 2520 2521 // If the type hasn't been defined yet, create a forward definition and 2522 // remember where that forward def'n was seen (in case it never is defined). 2523 if (!Entry.first) { 2524 Entry.first = StructType::create(Context); 2525 Entry.second = Lex.getLoc(); 2526 } 2527 Result = Entry.first; 2528 Lex.Lex(); 2529 break; 2530 } 2531 } 2532 2533 // parse the type suffixes. 2534 while (true) { 2535 switch (Lex.getKind()) { 2536 // End of type. 2537 default: 2538 if (!AllowVoid && Result->isVoidTy()) 2539 return error(TypeLoc, "void type only allowed for function results"); 2540 return false; 2541 2542 // Type ::= Type '*' 2543 case lltok::star: 2544 if (Result->isLabelTy()) 2545 return tokError("basic block pointers are invalid"); 2546 if (Result->isVoidTy()) 2547 return tokError("pointers to void are invalid - use i8* instead"); 2548 if (!PointerType::isValidElementType(Result)) 2549 return tokError("pointer to this type is invalid"); 2550 Result = PointerType::getUnqual(Result); 2551 Lex.Lex(); 2552 break; 2553 2554 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 2555 case lltok::kw_addrspace: { 2556 if (Result->isLabelTy()) 2557 return tokError("basic block pointers are invalid"); 2558 if (Result->isVoidTy()) 2559 return tokError("pointers to void are invalid; use i8* instead"); 2560 if (!PointerType::isValidElementType(Result)) 2561 return tokError("pointer to this type is invalid"); 2562 unsigned AddrSpace; 2563 if (parseOptionalAddrSpace(AddrSpace) || 2564 parseToken(lltok::star, "expected '*' in address space")) 2565 return true; 2566 2567 Result = PointerType::get(Result, AddrSpace); 2568 break; 2569 } 2570 2571 /// Types '(' ArgTypeListI ')' OptFuncAttrs 2572 case lltok::lparen: 2573 if (parseFunctionType(Result)) 2574 return true; 2575 break; 2576 } 2577 } 2578 } 2579 2580 /// parseParameterList 2581 /// ::= '(' ')' 2582 /// ::= '(' Arg (',' Arg)* ')' 2583 /// Arg 2584 /// ::= Type OptionalAttributes Value OptionalAttributes 2585 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 2586 PerFunctionState &PFS, bool IsMustTailCall, 2587 bool InVarArgsFunc) { 2588 if (parseToken(lltok::lparen, "expected '(' in call")) 2589 return true; 2590 2591 while (Lex.getKind() != lltok::rparen) { 2592 // If this isn't the first argument, we need a comma. 2593 if (!ArgList.empty() && 2594 parseToken(lltok::comma, "expected ',' in argument list")) 2595 return true; 2596 2597 // parse an ellipsis if this is a musttail call in a variadic function. 2598 if (Lex.getKind() == lltok::dotdotdot) { 2599 const char *Msg = "unexpected ellipsis in argument list for "; 2600 if (!IsMustTailCall) 2601 return tokError(Twine(Msg) + "non-musttail call"); 2602 if (!InVarArgsFunc) 2603 return tokError(Twine(Msg) + "musttail call in non-varargs function"); 2604 Lex.Lex(); // Lex the '...', it is purely for readability. 2605 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2606 } 2607 2608 // parse the argument. 2609 LocTy ArgLoc; 2610 Type *ArgTy = nullptr; 2611 AttrBuilder ArgAttrs; 2612 Value *V; 2613 if (parseType(ArgTy, ArgLoc)) 2614 return true; 2615 2616 if (ArgTy->isMetadataTy()) { 2617 if (parseMetadataAsValue(V, PFS)) 2618 return true; 2619 } else { 2620 // Otherwise, handle normal operands. 2621 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS)) 2622 return true; 2623 } 2624 ArgList.push_back(ParamInfo( 2625 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs))); 2626 } 2627 2628 if (IsMustTailCall && InVarArgsFunc) 2629 return tokError("expected '...' at end of argument list for musttail call " 2630 "in varargs function"); 2631 2632 Lex.Lex(); // Lex the ')'. 2633 return false; 2634 } 2635 2636 /// parseByValWithOptionalType 2637 /// ::= byval 2638 /// ::= byval(<ty>) 2639 bool LLParser::parseOptionalTypeAttr(Type *&Result, lltok::Kind AttrName) { 2640 Result = nullptr; 2641 if (!EatIfPresent(AttrName)) 2642 return true; 2643 if (!EatIfPresent(lltok::lparen)) 2644 return false; 2645 if (parseType(Result)) 2646 return true; 2647 if (!EatIfPresent(lltok::rparen)) 2648 return error(Lex.getLoc(), "expected ')'"); 2649 return false; 2650 } 2651 2652 /// parseRequiredTypeAttr 2653 /// ::= attrname(<ty>) 2654 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) { 2655 Result = nullptr; 2656 if (!EatIfPresent(AttrName)) 2657 return true; 2658 if (!EatIfPresent(lltok::lparen)) 2659 return error(Lex.getLoc(), "expected '('"); 2660 if (parseType(Result)) 2661 return true; 2662 if (!EatIfPresent(lltok::rparen)) 2663 return error(Lex.getLoc(), "expected ')'"); 2664 return false; 2665 } 2666 2667 /// parsePreallocated 2668 /// ::= preallocated(<ty>) 2669 bool LLParser::parsePreallocated(Type *&Result) { 2670 return parseRequiredTypeAttr(Result, lltok::kw_preallocated); 2671 } 2672 2673 /// parseByRef 2674 /// ::= byref(<type>) 2675 bool LLParser::parseByRef(Type *&Result) { 2676 return parseRequiredTypeAttr(Result, lltok::kw_byref); 2677 } 2678 2679 /// parseOptionalOperandBundles 2680 /// ::= /*empty*/ 2681 /// ::= '[' OperandBundle [, OperandBundle ]* ']' 2682 /// 2683 /// OperandBundle 2684 /// ::= bundle-tag '(' ')' 2685 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' 2686 /// 2687 /// bundle-tag ::= String Constant 2688 bool LLParser::parseOptionalOperandBundles( 2689 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { 2690 LocTy BeginLoc = Lex.getLoc(); 2691 if (!EatIfPresent(lltok::lsquare)) 2692 return false; 2693 2694 while (Lex.getKind() != lltok::rsquare) { 2695 // If this isn't the first operand bundle, we need a comma. 2696 if (!BundleList.empty() && 2697 parseToken(lltok::comma, "expected ',' in input list")) 2698 return true; 2699 2700 std::string Tag; 2701 if (parseStringConstant(Tag)) 2702 return true; 2703 2704 if (parseToken(lltok::lparen, "expected '(' in operand bundle")) 2705 return true; 2706 2707 std::vector<Value *> Inputs; 2708 while (Lex.getKind() != lltok::rparen) { 2709 // If this isn't the first input, we need a comma. 2710 if (!Inputs.empty() && 2711 parseToken(lltok::comma, "expected ',' in input list")) 2712 return true; 2713 2714 Type *Ty = nullptr; 2715 Value *Input = nullptr; 2716 if (parseType(Ty) || parseValue(Ty, Input, PFS)) 2717 return true; 2718 Inputs.push_back(Input); 2719 } 2720 2721 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 2722 2723 Lex.Lex(); // Lex the ')'. 2724 } 2725 2726 if (BundleList.empty()) 2727 return error(BeginLoc, "operand bundle set must not be empty"); 2728 2729 Lex.Lex(); // Lex the ']'. 2730 return false; 2731 } 2732 2733 /// parseArgumentList - parse the argument list for a function type or function 2734 /// prototype. 2735 /// ::= '(' ArgTypeListI ')' 2736 /// ArgTypeListI 2737 /// ::= /*empty*/ 2738 /// ::= '...' 2739 /// ::= ArgTypeList ',' '...' 2740 /// ::= ArgType (',' ArgType)* 2741 /// 2742 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 2743 bool &IsVarArg) { 2744 unsigned CurValID = 0; 2745 IsVarArg = false; 2746 assert(Lex.getKind() == lltok::lparen); 2747 Lex.Lex(); // eat the (. 2748 2749 if (Lex.getKind() == lltok::rparen) { 2750 // empty 2751 } else if (Lex.getKind() == lltok::dotdotdot) { 2752 IsVarArg = true; 2753 Lex.Lex(); 2754 } else { 2755 LocTy TypeLoc = Lex.getLoc(); 2756 Type *ArgTy = nullptr; 2757 AttrBuilder Attrs; 2758 std::string Name; 2759 2760 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2761 return true; 2762 2763 if (ArgTy->isVoidTy()) 2764 return error(TypeLoc, "argument can not have void type"); 2765 2766 if (Lex.getKind() == lltok::LocalVar) { 2767 Name = Lex.getStrVal(); 2768 Lex.Lex(); 2769 } else if (Lex.getKind() == lltok::LocalVarID) { 2770 if (Lex.getUIntVal() != CurValID) 2771 return error(TypeLoc, "argument expected to be numbered '%" + 2772 Twine(CurValID) + "'"); 2773 ++CurValID; 2774 Lex.Lex(); 2775 } 2776 2777 if (!FunctionType::isValidArgumentType(ArgTy)) 2778 return error(TypeLoc, "invalid type for function argument"); 2779 2780 ArgList.emplace_back(TypeLoc, ArgTy, 2781 AttributeSet::get(ArgTy->getContext(), Attrs), 2782 std::move(Name)); 2783 2784 while (EatIfPresent(lltok::comma)) { 2785 // Handle ... at end of arg list. 2786 if (EatIfPresent(lltok::dotdotdot)) { 2787 IsVarArg = true; 2788 break; 2789 } 2790 2791 // Otherwise must be an argument type. 2792 TypeLoc = Lex.getLoc(); 2793 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2794 return true; 2795 2796 if (ArgTy->isVoidTy()) 2797 return error(TypeLoc, "argument can not have void type"); 2798 2799 if (Lex.getKind() == lltok::LocalVar) { 2800 Name = Lex.getStrVal(); 2801 Lex.Lex(); 2802 } else { 2803 if (Lex.getKind() == lltok::LocalVarID) { 2804 if (Lex.getUIntVal() != CurValID) 2805 return error(TypeLoc, "argument expected to be numbered '%" + 2806 Twine(CurValID) + "'"); 2807 Lex.Lex(); 2808 } 2809 ++CurValID; 2810 Name = ""; 2811 } 2812 2813 if (!ArgTy->isFirstClassType()) 2814 return error(TypeLoc, "invalid type for function argument"); 2815 2816 ArgList.emplace_back(TypeLoc, ArgTy, 2817 AttributeSet::get(ArgTy->getContext(), Attrs), 2818 std::move(Name)); 2819 } 2820 } 2821 2822 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2823 } 2824 2825 /// parseFunctionType 2826 /// ::= Type ArgumentList OptionalAttrs 2827 bool LLParser::parseFunctionType(Type *&Result) { 2828 assert(Lex.getKind() == lltok::lparen); 2829 2830 if (!FunctionType::isValidReturnType(Result)) 2831 return tokError("invalid function return type"); 2832 2833 SmallVector<ArgInfo, 8> ArgList; 2834 bool IsVarArg; 2835 if (parseArgumentList(ArgList, IsVarArg)) 2836 return true; 2837 2838 // Reject names on the arguments lists. 2839 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2840 if (!ArgList[i].Name.empty()) 2841 return error(ArgList[i].Loc, "argument name invalid in function type"); 2842 if (ArgList[i].Attrs.hasAttributes()) 2843 return error(ArgList[i].Loc, 2844 "argument attributes invalid in function type"); 2845 } 2846 2847 SmallVector<Type*, 16> ArgListTy; 2848 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2849 ArgListTy.push_back(ArgList[i].Ty); 2850 2851 Result = FunctionType::get(Result, ArgListTy, IsVarArg); 2852 return false; 2853 } 2854 2855 /// parseAnonStructType - parse an anonymous struct type, which is inlined into 2856 /// other structs. 2857 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { 2858 SmallVector<Type*, 8> Elts; 2859 if (parseStructBody(Elts)) 2860 return true; 2861 2862 Result = StructType::get(Context, Elts, Packed); 2863 return false; 2864 } 2865 2866 /// parseStructDefinition - parse a struct in a 'type' definition. 2867 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, 2868 std::pair<Type *, LocTy> &Entry, 2869 Type *&ResultTy) { 2870 // If the type was already defined, diagnose the redefinition. 2871 if (Entry.first && !Entry.second.isValid()) 2872 return error(TypeLoc, "redefinition of type"); 2873 2874 // If we have opaque, just return without filling in the definition for the 2875 // struct. This counts as a definition as far as the .ll file goes. 2876 if (EatIfPresent(lltok::kw_opaque)) { 2877 // This type is being defined, so clear the location to indicate this. 2878 Entry.second = SMLoc(); 2879 2880 // If this type number has never been uttered, create it. 2881 if (!Entry.first) 2882 Entry.first = StructType::create(Context, Name); 2883 ResultTy = Entry.first; 2884 return false; 2885 } 2886 2887 // If the type starts with '<', then it is either a packed struct or a vector. 2888 bool isPacked = EatIfPresent(lltok::less); 2889 2890 // If we don't have a struct, then we have a random type alias, which we 2891 // accept for compatibility with old files. These types are not allowed to be 2892 // forward referenced and not allowed to be recursive. 2893 if (Lex.getKind() != lltok::lbrace) { 2894 if (Entry.first) 2895 return error(TypeLoc, "forward references to non-struct type"); 2896 2897 ResultTy = nullptr; 2898 if (isPacked) 2899 return parseArrayVectorType(ResultTy, true); 2900 return parseType(ResultTy); 2901 } 2902 2903 // This type is being defined, so clear the location to indicate this. 2904 Entry.second = SMLoc(); 2905 2906 // If this type number has never been uttered, create it. 2907 if (!Entry.first) 2908 Entry.first = StructType::create(Context, Name); 2909 2910 StructType *STy = cast<StructType>(Entry.first); 2911 2912 SmallVector<Type*, 8> Body; 2913 if (parseStructBody(Body) || 2914 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct"))) 2915 return true; 2916 2917 STy->setBody(Body, isPacked); 2918 ResultTy = STy; 2919 return false; 2920 } 2921 2922 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. 2923 /// StructType 2924 /// ::= '{' '}' 2925 /// ::= '{' Type (',' Type)* '}' 2926 /// ::= '<' '{' '}' '>' 2927 /// ::= '<' '{' Type (',' Type)* '}' '>' 2928 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { 2929 assert(Lex.getKind() == lltok::lbrace); 2930 Lex.Lex(); // Consume the '{' 2931 2932 // Handle the empty struct. 2933 if (EatIfPresent(lltok::rbrace)) 2934 return false; 2935 2936 LocTy EltTyLoc = Lex.getLoc(); 2937 Type *Ty = nullptr; 2938 if (parseType(Ty)) 2939 return true; 2940 Body.push_back(Ty); 2941 2942 if (!StructType::isValidElementType(Ty)) 2943 return error(EltTyLoc, "invalid element type for struct"); 2944 2945 while (EatIfPresent(lltok::comma)) { 2946 EltTyLoc = Lex.getLoc(); 2947 if (parseType(Ty)) 2948 return true; 2949 2950 if (!StructType::isValidElementType(Ty)) 2951 return error(EltTyLoc, "invalid element type for struct"); 2952 2953 Body.push_back(Ty); 2954 } 2955 2956 return parseToken(lltok::rbrace, "expected '}' at end of struct"); 2957 } 2958 2959 /// parseArrayVectorType - parse an array or vector type, assuming the first 2960 /// token has already been consumed. 2961 /// Type 2962 /// ::= '[' APSINTVAL 'x' Types ']' 2963 /// ::= '<' APSINTVAL 'x' Types '>' 2964 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' 2965 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { 2966 bool Scalable = false; 2967 2968 if (IsVector && Lex.getKind() == lltok::kw_vscale) { 2969 Lex.Lex(); // consume the 'vscale' 2970 if (parseToken(lltok::kw_x, "expected 'x' after vscale")) 2971 return true; 2972 2973 Scalable = true; 2974 } 2975 2976 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 2977 Lex.getAPSIntVal().getBitWidth() > 64) 2978 return tokError("expected number in address space"); 2979 2980 LocTy SizeLoc = Lex.getLoc(); 2981 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 2982 Lex.Lex(); 2983 2984 if (parseToken(lltok::kw_x, "expected 'x' after element count")) 2985 return true; 2986 2987 LocTy TypeLoc = Lex.getLoc(); 2988 Type *EltTy = nullptr; 2989 if (parseType(EltTy)) 2990 return true; 2991 2992 if (parseToken(IsVector ? lltok::greater : lltok::rsquare, 2993 "expected end of sequential type")) 2994 return true; 2995 2996 if (IsVector) { 2997 if (Size == 0) 2998 return error(SizeLoc, "zero element vector is illegal"); 2999 if ((unsigned)Size != Size) 3000 return error(SizeLoc, "size too large for vector"); 3001 if (!VectorType::isValidElementType(EltTy)) 3002 return error(TypeLoc, "invalid vector element type"); 3003 Result = VectorType::get(EltTy, unsigned(Size), Scalable); 3004 } else { 3005 if (!ArrayType::isValidElementType(EltTy)) 3006 return error(TypeLoc, "invalid array element type"); 3007 Result = ArrayType::get(EltTy, Size); 3008 } 3009 return false; 3010 } 3011 3012 //===----------------------------------------------------------------------===// 3013 // Function Semantic Analysis. 3014 //===----------------------------------------------------------------------===// 3015 3016 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 3017 int functionNumber) 3018 : P(p), F(f), FunctionNumber(functionNumber) { 3019 3020 // Insert unnamed arguments into the NumberedVals list. 3021 for (Argument &A : F.args()) 3022 if (!A.hasName()) 3023 NumberedVals.push_back(&A); 3024 } 3025 3026 LLParser::PerFunctionState::~PerFunctionState() { 3027 // If there were any forward referenced non-basicblock values, delete them. 3028 3029 for (const auto &P : ForwardRefVals) { 3030 if (isa<BasicBlock>(P.second.first)) 3031 continue; 3032 P.second.first->replaceAllUsesWith( 3033 UndefValue::get(P.second.first->getType())); 3034 P.second.first->deleteValue(); 3035 } 3036 3037 for (const auto &P : ForwardRefValIDs) { 3038 if (isa<BasicBlock>(P.second.first)) 3039 continue; 3040 P.second.first->replaceAllUsesWith( 3041 UndefValue::get(P.second.first->getType())); 3042 P.second.first->deleteValue(); 3043 } 3044 } 3045 3046 bool LLParser::PerFunctionState::finishFunction() { 3047 if (!ForwardRefVals.empty()) 3048 return P.error(ForwardRefVals.begin()->second.second, 3049 "use of undefined value '%" + ForwardRefVals.begin()->first + 3050 "'"); 3051 if (!ForwardRefValIDs.empty()) 3052 return P.error(ForwardRefValIDs.begin()->second.second, 3053 "use of undefined value '%" + 3054 Twine(ForwardRefValIDs.begin()->first) + "'"); 3055 return false; 3056 } 3057 3058 /// getVal - Get a value with the specified name or ID, creating a 3059 /// forward reference record if needed. This can return null if the value 3060 /// exists but does not have the right type. 3061 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, 3062 LocTy Loc, bool IsCall) { 3063 // Look this name up in the normal function symbol table. 3064 Value *Val = F.getValueSymbolTable()->lookup(Name); 3065 3066 // If this is a forward reference for the value, see if we already created a 3067 // forward ref record. 3068 if (!Val) { 3069 auto I = ForwardRefVals.find(Name); 3070 if (I != ForwardRefVals.end()) 3071 Val = I->second.first; 3072 } 3073 3074 // If we have the value in the symbol table or fwd-ref table, return it. 3075 if (Val) 3076 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall); 3077 3078 // Don't make placeholders with invalid type. 3079 if (!Ty->isFirstClassType()) { 3080 P.error(Loc, "invalid use of a non-first-class type"); 3081 return nullptr; 3082 } 3083 3084 // Otherwise, create a new forward reference for this value and remember it. 3085 Value *FwdVal; 3086 if (Ty->isLabelTy()) { 3087 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 3088 } else { 3089 FwdVal = new Argument(Ty, Name); 3090 } 3091 3092 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 3093 return FwdVal; 3094 } 3095 3096 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc, 3097 bool IsCall) { 3098 // Look this name up in the normal function symbol table. 3099 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 3100 3101 // If this is a forward reference for the value, see if we already created a 3102 // forward ref record. 3103 if (!Val) { 3104 auto I = ForwardRefValIDs.find(ID); 3105 if (I != ForwardRefValIDs.end()) 3106 Val = I->second.first; 3107 } 3108 3109 // If we have the value in the symbol table or fwd-ref table, return it. 3110 if (Val) 3111 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall); 3112 3113 if (!Ty->isFirstClassType()) { 3114 P.error(Loc, "invalid use of a non-first-class type"); 3115 return nullptr; 3116 } 3117 3118 // Otherwise, create a new forward reference for this value and remember it. 3119 Value *FwdVal; 3120 if (Ty->isLabelTy()) { 3121 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 3122 } else { 3123 FwdVal = new Argument(Ty); 3124 } 3125 3126 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 3127 return FwdVal; 3128 } 3129 3130 /// setInstName - After an instruction is parsed and inserted into its 3131 /// basic block, this installs its name. 3132 bool LLParser::PerFunctionState::setInstName(int NameID, 3133 const std::string &NameStr, 3134 LocTy NameLoc, Instruction *Inst) { 3135 // If this instruction has void type, it cannot have a name or ID specified. 3136 if (Inst->getType()->isVoidTy()) { 3137 if (NameID != -1 || !NameStr.empty()) 3138 return P.error(NameLoc, "instructions returning void cannot have a name"); 3139 return false; 3140 } 3141 3142 // If this was a numbered instruction, verify that the instruction is the 3143 // expected value and resolve any forward references. 3144 if (NameStr.empty()) { 3145 // If neither a name nor an ID was specified, just use the next ID. 3146 if (NameID == -1) 3147 NameID = NumberedVals.size(); 3148 3149 if (unsigned(NameID) != NumberedVals.size()) 3150 return P.error(NameLoc, "instruction expected to be numbered '%" + 3151 Twine(NumberedVals.size()) + "'"); 3152 3153 auto FI = ForwardRefValIDs.find(NameID); 3154 if (FI != ForwardRefValIDs.end()) { 3155 Value *Sentinel = FI->second.first; 3156 if (Sentinel->getType() != Inst->getType()) 3157 return P.error(NameLoc, "instruction forward referenced with type '" + 3158 getTypeString(FI->second.first->getType()) + 3159 "'"); 3160 3161 Sentinel->replaceAllUsesWith(Inst); 3162 Sentinel->deleteValue(); 3163 ForwardRefValIDs.erase(FI); 3164 } 3165 3166 NumberedVals.push_back(Inst); 3167 return false; 3168 } 3169 3170 // Otherwise, the instruction had a name. Resolve forward refs and set it. 3171 auto FI = ForwardRefVals.find(NameStr); 3172 if (FI != ForwardRefVals.end()) { 3173 Value *Sentinel = FI->second.first; 3174 if (Sentinel->getType() != Inst->getType()) 3175 return P.error(NameLoc, "instruction forward referenced with type '" + 3176 getTypeString(FI->second.first->getType()) + 3177 "'"); 3178 3179 Sentinel->replaceAllUsesWith(Inst); 3180 Sentinel->deleteValue(); 3181 ForwardRefVals.erase(FI); 3182 } 3183 3184 // Set the name on the instruction. 3185 Inst->setName(NameStr); 3186 3187 if (Inst->getName() != NameStr) 3188 return P.error(NameLoc, "multiple definition of local value named '" + 3189 NameStr + "'"); 3190 return false; 3191 } 3192 3193 /// getBB - Get a basic block with the specified name or ID, creating a 3194 /// forward reference record if needed. 3195 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, 3196 LocTy Loc) { 3197 return dyn_cast_or_null<BasicBlock>( 3198 getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false)); 3199 } 3200 3201 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { 3202 return dyn_cast_or_null<BasicBlock>( 3203 getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false)); 3204 } 3205 3206 /// defineBB - Define the specified basic block, which is either named or 3207 /// unnamed. If there is an error, this returns null otherwise it returns 3208 /// the block being defined. 3209 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, 3210 int NameID, LocTy Loc) { 3211 BasicBlock *BB; 3212 if (Name.empty()) { 3213 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) { 3214 P.error(Loc, "label expected to be numbered '" + 3215 Twine(NumberedVals.size()) + "'"); 3216 return nullptr; 3217 } 3218 BB = getBB(NumberedVals.size(), Loc); 3219 if (!BB) { 3220 P.error(Loc, "unable to create block numbered '" + 3221 Twine(NumberedVals.size()) + "'"); 3222 return nullptr; 3223 } 3224 } else { 3225 BB = getBB(Name, Loc); 3226 if (!BB) { 3227 P.error(Loc, "unable to create block named '" + Name + "'"); 3228 return nullptr; 3229 } 3230 } 3231 3232 // Move the block to the end of the function. Forward ref'd blocks are 3233 // inserted wherever they happen to be referenced. 3234 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 3235 3236 // Remove the block from forward ref sets. 3237 if (Name.empty()) { 3238 ForwardRefValIDs.erase(NumberedVals.size()); 3239 NumberedVals.push_back(BB); 3240 } else { 3241 // BB forward references are already in the function symbol table. 3242 ForwardRefVals.erase(Name); 3243 } 3244 3245 return BB; 3246 } 3247 3248 //===----------------------------------------------------------------------===// 3249 // Constants. 3250 //===----------------------------------------------------------------------===// 3251 3252 /// parseValID - parse an abstract value that doesn't necessarily have a 3253 /// type implied. For example, if we parse "4" we don't know what integer type 3254 /// it has. The value will later be combined with its type and checked for 3255 /// sanity. PFS is used to convert function-local operands of metadata (since 3256 /// metadata operands are not just parsed here but also converted to values). 3257 /// PFS can be null when we are not parsing metadata values inside a function. 3258 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) { 3259 ID.Loc = Lex.getLoc(); 3260 switch (Lex.getKind()) { 3261 default: 3262 return tokError("expected value token"); 3263 case lltok::GlobalID: // @42 3264 ID.UIntVal = Lex.getUIntVal(); 3265 ID.Kind = ValID::t_GlobalID; 3266 break; 3267 case lltok::GlobalVar: // @foo 3268 ID.StrVal = Lex.getStrVal(); 3269 ID.Kind = ValID::t_GlobalName; 3270 break; 3271 case lltok::LocalVarID: // %42 3272 ID.UIntVal = Lex.getUIntVal(); 3273 ID.Kind = ValID::t_LocalID; 3274 break; 3275 case lltok::LocalVar: // %foo 3276 ID.StrVal = Lex.getStrVal(); 3277 ID.Kind = ValID::t_LocalName; 3278 break; 3279 case lltok::APSInt: 3280 ID.APSIntVal = Lex.getAPSIntVal(); 3281 ID.Kind = ValID::t_APSInt; 3282 break; 3283 case lltok::APFloat: 3284 ID.APFloatVal = Lex.getAPFloatVal(); 3285 ID.Kind = ValID::t_APFloat; 3286 break; 3287 case lltok::kw_true: 3288 ID.ConstantVal = ConstantInt::getTrue(Context); 3289 ID.Kind = ValID::t_Constant; 3290 break; 3291 case lltok::kw_false: 3292 ID.ConstantVal = ConstantInt::getFalse(Context); 3293 ID.Kind = ValID::t_Constant; 3294 break; 3295 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 3296 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 3297 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 3298 case lltok::kw_none: ID.Kind = ValID::t_None; break; 3299 3300 case lltok::lbrace: { 3301 // ValID ::= '{' ConstVector '}' 3302 Lex.Lex(); 3303 SmallVector<Constant*, 16> Elts; 3304 if (parseGlobalValueVector(Elts) || 3305 parseToken(lltok::rbrace, "expected end of struct constant")) 3306 return true; 3307 3308 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3309 ID.UIntVal = Elts.size(); 3310 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3311 Elts.size() * sizeof(Elts[0])); 3312 ID.Kind = ValID::t_ConstantStruct; 3313 return false; 3314 } 3315 case lltok::less: { 3316 // ValID ::= '<' ConstVector '>' --> Vector. 3317 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 3318 Lex.Lex(); 3319 bool isPackedStruct = EatIfPresent(lltok::lbrace); 3320 3321 SmallVector<Constant*, 16> Elts; 3322 LocTy FirstEltLoc = Lex.getLoc(); 3323 if (parseGlobalValueVector(Elts) || 3324 (isPackedStruct && 3325 parseToken(lltok::rbrace, "expected end of packed struct")) || 3326 parseToken(lltok::greater, "expected end of constant")) 3327 return true; 3328 3329 if (isPackedStruct) { 3330 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3331 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3332 Elts.size() * sizeof(Elts[0])); 3333 ID.UIntVal = Elts.size(); 3334 ID.Kind = ValID::t_PackedConstantStruct; 3335 return false; 3336 } 3337 3338 if (Elts.empty()) 3339 return error(ID.Loc, "constant vector must not be empty"); 3340 3341 if (!Elts[0]->getType()->isIntegerTy() && 3342 !Elts[0]->getType()->isFloatingPointTy() && 3343 !Elts[0]->getType()->isPointerTy()) 3344 return error( 3345 FirstEltLoc, 3346 "vector elements must have integer, pointer or floating point type"); 3347 3348 // Verify that all the vector elements have the same type. 3349 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 3350 if (Elts[i]->getType() != Elts[0]->getType()) 3351 return error(FirstEltLoc, "vector element #" + Twine(i) + 3352 " is not of type '" + 3353 getTypeString(Elts[0]->getType())); 3354 3355 ID.ConstantVal = ConstantVector::get(Elts); 3356 ID.Kind = ValID::t_Constant; 3357 return false; 3358 } 3359 case lltok::lsquare: { // Array Constant 3360 Lex.Lex(); 3361 SmallVector<Constant*, 16> Elts; 3362 LocTy FirstEltLoc = Lex.getLoc(); 3363 if (parseGlobalValueVector(Elts) || 3364 parseToken(lltok::rsquare, "expected end of array constant")) 3365 return true; 3366 3367 // Handle empty element. 3368 if (Elts.empty()) { 3369 // Use undef instead of an array because it's inconvenient to determine 3370 // the element type at this point, there being no elements to examine. 3371 ID.Kind = ValID::t_EmptyArray; 3372 return false; 3373 } 3374 3375 if (!Elts[0]->getType()->isFirstClassType()) 3376 return error(FirstEltLoc, "invalid array element type: " + 3377 getTypeString(Elts[0]->getType())); 3378 3379 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 3380 3381 // Verify all elements are correct type! 3382 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 3383 if (Elts[i]->getType() != Elts[0]->getType()) 3384 return error(FirstEltLoc, "array element #" + Twine(i) + 3385 " is not of type '" + 3386 getTypeString(Elts[0]->getType())); 3387 } 3388 3389 ID.ConstantVal = ConstantArray::get(ATy, Elts); 3390 ID.Kind = ValID::t_Constant; 3391 return false; 3392 } 3393 case lltok::kw_c: // c "foo" 3394 Lex.Lex(); 3395 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 3396 false); 3397 if (parseToken(lltok::StringConstant, "expected string")) 3398 return true; 3399 ID.Kind = ValID::t_Constant; 3400 return false; 3401 3402 case lltok::kw_asm: { 3403 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 3404 // STRINGCONSTANT 3405 bool HasSideEffect, AlignStack, AsmDialect; 3406 Lex.Lex(); 3407 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 3408 parseOptionalToken(lltok::kw_alignstack, AlignStack) || 3409 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 3410 parseStringConstant(ID.StrVal) || 3411 parseToken(lltok::comma, "expected comma in inline asm expression") || 3412 parseToken(lltok::StringConstant, "expected constraint string")) 3413 return true; 3414 ID.StrVal2 = Lex.getStrVal(); 3415 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) | 3416 (unsigned(AsmDialect)<<2); 3417 ID.Kind = ValID::t_InlineAsm; 3418 return false; 3419 } 3420 3421 case lltok::kw_blockaddress: { 3422 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 3423 Lex.Lex(); 3424 3425 ValID Fn, Label; 3426 3427 if (parseToken(lltok::lparen, "expected '(' in block address expression") || 3428 parseValID(Fn) || 3429 parseToken(lltok::comma, 3430 "expected comma in block address expression") || 3431 parseValID(Label) || 3432 parseToken(lltok::rparen, "expected ')' in block address expression")) 3433 return true; 3434 3435 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3436 return error(Fn.Loc, "expected function name in blockaddress"); 3437 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 3438 return error(Label.Loc, "expected basic block name in blockaddress"); 3439 3440 // Try to find the function (but skip it if it's forward-referenced). 3441 GlobalValue *GV = nullptr; 3442 if (Fn.Kind == ValID::t_GlobalID) { 3443 if (Fn.UIntVal < NumberedVals.size()) 3444 GV = NumberedVals[Fn.UIntVal]; 3445 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3446 GV = M->getNamedValue(Fn.StrVal); 3447 } 3448 Function *F = nullptr; 3449 if (GV) { 3450 // Confirm that it's actually a function with a definition. 3451 if (!isa<Function>(GV)) 3452 return error(Fn.Loc, "expected function name in blockaddress"); 3453 F = cast<Function>(GV); 3454 if (F->isDeclaration()) 3455 return error(Fn.Loc, "cannot take blockaddress inside a declaration"); 3456 } 3457 3458 if (!F) { 3459 // Make a global variable as a placeholder for this reference. 3460 GlobalValue *&FwdRef = 3461 ForwardRefBlockAddresses.insert(std::make_pair( 3462 std::move(Fn), 3463 std::map<ValID, GlobalValue *>())) 3464 .first->second.insert(std::make_pair(std::move(Label), nullptr)) 3465 .first->second; 3466 if (!FwdRef) 3467 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false, 3468 GlobalValue::InternalLinkage, nullptr, ""); 3469 ID.ConstantVal = FwdRef; 3470 ID.Kind = ValID::t_Constant; 3471 return false; 3472 } 3473 3474 // We found the function; now find the basic block. Don't use PFS, since we 3475 // might be inside a constant expression. 3476 BasicBlock *BB; 3477 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 3478 if (Label.Kind == ValID::t_LocalID) 3479 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc); 3480 else 3481 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc); 3482 if (!BB) 3483 return error(Label.Loc, "referenced value is not a basic block"); 3484 } else { 3485 if (Label.Kind == ValID::t_LocalID) 3486 return error(Label.Loc, "cannot take address of numeric label after " 3487 "the function is defined"); 3488 BB = dyn_cast_or_null<BasicBlock>( 3489 F->getValueSymbolTable()->lookup(Label.StrVal)); 3490 if (!BB) 3491 return error(Label.Loc, "referenced value is not a basic block"); 3492 } 3493 3494 ID.ConstantVal = BlockAddress::get(F, BB); 3495 ID.Kind = ValID::t_Constant; 3496 return false; 3497 } 3498 3499 case lltok::kw_trunc: 3500 case lltok::kw_zext: 3501 case lltok::kw_sext: 3502 case lltok::kw_fptrunc: 3503 case lltok::kw_fpext: 3504 case lltok::kw_bitcast: 3505 case lltok::kw_addrspacecast: 3506 case lltok::kw_uitofp: 3507 case lltok::kw_sitofp: 3508 case lltok::kw_fptoui: 3509 case lltok::kw_fptosi: 3510 case lltok::kw_inttoptr: 3511 case lltok::kw_ptrtoint: { 3512 unsigned Opc = Lex.getUIntVal(); 3513 Type *DestTy = nullptr; 3514 Constant *SrcVal; 3515 Lex.Lex(); 3516 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") || 3517 parseGlobalTypeAndValue(SrcVal) || 3518 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 3519 parseType(DestTy) || 3520 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 3521 return true; 3522 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 3523 return error(ID.Loc, "invalid cast opcode for cast from '" + 3524 getTypeString(SrcVal->getType()) + "' to '" + 3525 getTypeString(DestTy) + "'"); 3526 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 3527 SrcVal, DestTy); 3528 ID.Kind = ValID::t_Constant; 3529 return false; 3530 } 3531 case lltok::kw_extractvalue: { 3532 Lex.Lex(); 3533 Constant *Val; 3534 SmallVector<unsigned, 4> Indices; 3535 if (parseToken(lltok::lparen, 3536 "expected '(' in extractvalue constantexpr") || 3537 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) || 3538 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 3539 return true; 3540 3541 if (!Val->getType()->isAggregateType()) 3542 return error(ID.Loc, "extractvalue operand must be aggregate type"); 3543 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3544 return error(ID.Loc, "invalid indices for extractvalue"); 3545 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 3546 ID.Kind = ValID::t_Constant; 3547 return false; 3548 } 3549 case lltok::kw_insertvalue: { 3550 Lex.Lex(); 3551 Constant *Val0, *Val1; 3552 SmallVector<unsigned, 4> Indices; 3553 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") || 3554 parseGlobalTypeAndValue(Val0) || 3555 parseToken(lltok::comma, 3556 "expected comma in insertvalue constantexpr") || 3557 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) || 3558 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 3559 return true; 3560 if (!Val0->getType()->isAggregateType()) 3561 return error(ID.Loc, "insertvalue operand must be aggregate type"); 3562 Type *IndexedType = 3563 ExtractValueInst::getIndexedType(Val0->getType(), Indices); 3564 if (!IndexedType) 3565 return error(ID.Loc, "invalid indices for insertvalue"); 3566 if (IndexedType != Val1->getType()) 3567 return error(ID.Loc, "insertvalue operand and field disagree in type: '" + 3568 getTypeString(Val1->getType()) + 3569 "' instead of '" + getTypeString(IndexedType) + 3570 "'"); 3571 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 3572 ID.Kind = ValID::t_Constant; 3573 return false; 3574 } 3575 case lltok::kw_icmp: 3576 case lltok::kw_fcmp: { 3577 unsigned PredVal, Opc = Lex.getUIntVal(); 3578 Constant *Val0, *Val1; 3579 Lex.Lex(); 3580 if (parseCmpPredicate(PredVal, Opc) || 3581 parseToken(lltok::lparen, "expected '(' in compare constantexpr") || 3582 parseGlobalTypeAndValue(Val0) || 3583 parseToken(lltok::comma, "expected comma in compare constantexpr") || 3584 parseGlobalTypeAndValue(Val1) || 3585 parseToken(lltok::rparen, "expected ')' in compare constantexpr")) 3586 return true; 3587 3588 if (Val0->getType() != Val1->getType()) 3589 return error(ID.Loc, "compare operands must have the same type"); 3590 3591 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 3592 3593 if (Opc == Instruction::FCmp) { 3594 if (!Val0->getType()->isFPOrFPVectorTy()) 3595 return error(ID.Loc, "fcmp requires floating point operands"); 3596 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 3597 } else { 3598 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 3599 if (!Val0->getType()->isIntOrIntVectorTy() && 3600 !Val0->getType()->isPtrOrPtrVectorTy()) 3601 return error(ID.Loc, "icmp requires pointer or integer operands"); 3602 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 3603 } 3604 ID.Kind = ValID::t_Constant; 3605 return false; 3606 } 3607 3608 // Unary Operators. 3609 case lltok::kw_fneg: { 3610 unsigned Opc = Lex.getUIntVal(); 3611 Constant *Val; 3612 Lex.Lex(); 3613 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") || 3614 parseGlobalTypeAndValue(Val) || 3615 parseToken(lltok::rparen, "expected ')' in unary constantexpr")) 3616 return true; 3617 3618 // Check that the type is valid for the operator. 3619 switch (Opc) { 3620 case Instruction::FNeg: 3621 if (!Val->getType()->isFPOrFPVectorTy()) 3622 return error(ID.Loc, "constexpr requires fp operands"); 3623 break; 3624 default: llvm_unreachable("Unknown unary operator!"); 3625 } 3626 unsigned Flags = 0; 3627 Constant *C = ConstantExpr::get(Opc, Val, Flags); 3628 ID.ConstantVal = C; 3629 ID.Kind = ValID::t_Constant; 3630 return false; 3631 } 3632 // Binary Operators. 3633 case lltok::kw_add: 3634 case lltok::kw_fadd: 3635 case lltok::kw_sub: 3636 case lltok::kw_fsub: 3637 case lltok::kw_mul: 3638 case lltok::kw_fmul: 3639 case lltok::kw_udiv: 3640 case lltok::kw_sdiv: 3641 case lltok::kw_fdiv: 3642 case lltok::kw_urem: 3643 case lltok::kw_srem: 3644 case lltok::kw_frem: 3645 case lltok::kw_shl: 3646 case lltok::kw_lshr: 3647 case lltok::kw_ashr: { 3648 bool NUW = false; 3649 bool NSW = false; 3650 bool Exact = false; 3651 unsigned Opc = Lex.getUIntVal(); 3652 Constant *Val0, *Val1; 3653 Lex.Lex(); 3654 if (Opc == Instruction::Add || Opc == Instruction::Sub || 3655 Opc == Instruction::Mul || Opc == Instruction::Shl) { 3656 if (EatIfPresent(lltok::kw_nuw)) 3657 NUW = true; 3658 if (EatIfPresent(lltok::kw_nsw)) { 3659 NSW = true; 3660 if (EatIfPresent(lltok::kw_nuw)) 3661 NUW = true; 3662 } 3663 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 3664 Opc == Instruction::LShr || Opc == Instruction::AShr) { 3665 if (EatIfPresent(lltok::kw_exact)) 3666 Exact = true; 3667 } 3668 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") || 3669 parseGlobalTypeAndValue(Val0) || 3670 parseToken(lltok::comma, "expected comma in binary constantexpr") || 3671 parseGlobalTypeAndValue(Val1) || 3672 parseToken(lltok::rparen, "expected ')' in binary constantexpr")) 3673 return true; 3674 if (Val0->getType() != Val1->getType()) 3675 return error(ID.Loc, "operands of constexpr must have same type"); 3676 // Check that the type is valid for the operator. 3677 switch (Opc) { 3678 case Instruction::Add: 3679 case Instruction::Sub: 3680 case Instruction::Mul: 3681 case Instruction::UDiv: 3682 case Instruction::SDiv: 3683 case Instruction::URem: 3684 case Instruction::SRem: 3685 case Instruction::Shl: 3686 case Instruction::AShr: 3687 case Instruction::LShr: 3688 if (!Val0->getType()->isIntOrIntVectorTy()) 3689 return error(ID.Loc, "constexpr requires integer operands"); 3690 break; 3691 case Instruction::FAdd: 3692 case Instruction::FSub: 3693 case Instruction::FMul: 3694 case Instruction::FDiv: 3695 case Instruction::FRem: 3696 if (!Val0->getType()->isFPOrFPVectorTy()) 3697 return error(ID.Loc, "constexpr requires fp operands"); 3698 break; 3699 default: llvm_unreachable("Unknown binary operator!"); 3700 } 3701 unsigned Flags = 0; 3702 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3703 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 3704 if (Exact) Flags |= PossiblyExactOperator::IsExact; 3705 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 3706 ID.ConstantVal = C; 3707 ID.Kind = ValID::t_Constant; 3708 return false; 3709 } 3710 3711 // Logical Operations 3712 case lltok::kw_and: 3713 case lltok::kw_or: 3714 case lltok::kw_xor: { 3715 unsigned Opc = Lex.getUIntVal(); 3716 Constant *Val0, *Val1; 3717 Lex.Lex(); 3718 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") || 3719 parseGlobalTypeAndValue(Val0) || 3720 parseToken(lltok::comma, "expected comma in logical constantexpr") || 3721 parseGlobalTypeAndValue(Val1) || 3722 parseToken(lltok::rparen, "expected ')' in logical constantexpr")) 3723 return true; 3724 if (Val0->getType() != Val1->getType()) 3725 return error(ID.Loc, "operands of constexpr must have same type"); 3726 if (!Val0->getType()->isIntOrIntVectorTy()) 3727 return error(ID.Loc, 3728 "constexpr requires integer or integer vector operands"); 3729 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 3730 ID.Kind = ValID::t_Constant; 3731 return false; 3732 } 3733 3734 case lltok::kw_getelementptr: 3735 case lltok::kw_shufflevector: 3736 case lltok::kw_insertelement: 3737 case lltok::kw_extractelement: 3738 case lltok::kw_select: { 3739 unsigned Opc = Lex.getUIntVal(); 3740 SmallVector<Constant*, 16> Elts; 3741 bool InBounds = false; 3742 Type *Ty; 3743 Lex.Lex(); 3744 3745 if (Opc == Instruction::GetElementPtr) 3746 InBounds = EatIfPresent(lltok::kw_inbounds); 3747 3748 if (parseToken(lltok::lparen, "expected '(' in constantexpr")) 3749 return true; 3750 3751 LocTy ExplicitTypeLoc = Lex.getLoc(); 3752 if (Opc == Instruction::GetElementPtr) { 3753 if (parseType(Ty) || 3754 parseToken(lltok::comma, "expected comma after getelementptr's type")) 3755 return true; 3756 } 3757 3758 Optional<unsigned> InRangeOp; 3759 if (parseGlobalValueVector( 3760 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) || 3761 parseToken(lltok::rparen, "expected ')' in constantexpr")) 3762 return true; 3763 3764 if (Opc == Instruction::GetElementPtr) { 3765 if (Elts.size() == 0 || 3766 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 3767 return error(ID.Loc, "base of getelementptr must be a pointer"); 3768 3769 Type *BaseType = Elts[0]->getType(); 3770 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType()); 3771 if (Ty != BasePointerType->getElementType()) 3772 return error( 3773 ExplicitTypeLoc, 3774 "explicit pointee type doesn't match operand's pointee type"); 3775 3776 unsigned GEPWidth = 3777 BaseType->isVectorTy() 3778 ? cast<FixedVectorType>(BaseType)->getNumElements() 3779 : 0; 3780 3781 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3782 for (Constant *Val : Indices) { 3783 Type *ValTy = Val->getType(); 3784 if (!ValTy->isIntOrIntVectorTy()) 3785 return error(ID.Loc, "getelementptr index must be an integer"); 3786 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 3787 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 3788 if (GEPWidth && (ValNumEl != GEPWidth)) 3789 return error( 3790 ID.Loc, 3791 "getelementptr vector index has a wrong number of elements"); 3792 // GEPWidth may have been unknown because the base is a scalar, 3793 // but it is known now. 3794 GEPWidth = ValNumEl; 3795 } 3796 } 3797 3798 SmallPtrSet<Type*, 4> Visited; 3799 if (!Indices.empty() && !Ty->isSized(&Visited)) 3800 return error(ID.Loc, "base element of getelementptr must be sized"); 3801 3802 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3803 return error(ID.Loc, "invalid getelementptr indices"); 3804 3805 if (InRangeOp) { 3806 if (*InRangeOp == 0) 3807 return error(ID.Loc, 3808 "inrange keyword may not appear on pointer operand"); 3809 --*InRangeOp; 3810 } 3811 3812 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3813 InBounds, InRangeOp); 3814 } else if (Opc == Instruction::Select) { 3815 if (Elts.size() != 3) 3816 return error(ID.Loc, "expected three operands to select"); 3817 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3818 Elts[2])) 3819 return error(ID.Loc, Reason); 3820 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3821 } else if (Opc == Instruction::ShuffleVector) { 3822 if (Elts.size() != 3) 3823 return error(ID.Loc, "expected three operands to shufflevector"); 3824 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3825 return error(ID.Loc, "invalid operands to shufflevector"); 3826 SmallVector<int, 16> Mask; 3827 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 3828 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 3829 } else if (Opc == Instruction::ExtractElement) { 3830 if (Elts.size() != 2) 3831 return error(ID.Loc, "expected two operands to extractelement"); 3832 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3833 return error(ID.Loc, "invalid extractelement operands"); 3834 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3835 } else { 3836 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3837 if (Elts.size() != 3) 3838 return error(ID.Loc, "expected three operands to insertelement"); 3839 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3840 return error(ID.Loc, "invalid insertelement operands"); 3841 ID.ConstantVal = 3842 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3843 } 3844 3845 ID.Kind = ValID::t_Constant; 3846 return false; 3847 } 3848 } 3849 3850 Lex.Lex(); 3851 return false; 3852 } 3853 3854 /// parseGlobalValue - parse a global value with the specified type. 3855 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { 3856 C = nullptr; 3857 ValID ID; 3858 Value *V = nullptr; 3859 bool Parsed = parseValID(ID) || 3860 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false); 3861 if (V && !(C = dyn_cast<Constant>(V))) 3862 return error(ID.Loc, "global values must be constants"); 3863 return Parsed; 3864 } 3865 3866 bool LLParser::parseGlobalTypeAndValue(Constant *&V) { 3867 Type *Ty = nullptr; 3868 return parseType(Ty) || parseGlobalValue(Ty, V); 3869 } 3870 3871 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3872 C = nullptr; 3873 3874 LocTy KwLoc = Lex.getLoc(); 3875 if (!EatIfPresent(lltok::kw_comdat)) 3876 return false; 3877 3878 if (EatIfPresent(lltok::lparen)) { 3879 if (Lex.getKind() != lltok::ComdatVar) 3880 return tokError("expected comdat variable"); 3881 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3882 Lex.Lex(); 3883 if (parseToken(lltok::rparen, "expected ')' after comdat var")) 3884 return true; 3885 } else { 3886 if (GlobalName.empty()) 3887 return tokError("comdat cannot be unnamed"); 3888 C = getComdat(std::string(GlobalName), KwLoc); 3889 } 3890 3891 return false; 3892 } 3893 3894 /// parseGlobalValueVector 3895 /// ::= /*empty*/ 3896 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3897 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3898 Optional<unsigned> *InRangeOp) { 3899 // Empty list. 3900 if (Lex.getKind() == lltok::rbrace || 3901 Lex.getKind() == lltok::rsquare || 3902 Lex.getKind() == lltok::greater || 3903 Lex.getKind() == lltok::rparen) 3904 return false; 3905 3906 do { 3907 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3908 *InRangeOp = Elts.size(); 3909 3910 Constant *C; 3911 if (parseGlobalTypeAndValue(C)) 3912 return true; 3913 Elts.push_back(C); 3914 } while (EatIfPresent(lltok::comma)); 3915 3916 return false; 3917 } 3918 3919 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { 3920 SmallVector<Metadata *, 16> Elts; 3921 if (parseMDNodeVector(Elts)) 3922 return true; 3923 3924 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3925 return false; 3926 } 3927 3928 /// MDNode: 3929 /// ::= !{ ... } 3930 /// ::= !7 3931 /// ::= !DILocation(...) 3932 bool LLParser::parseMDNode(MDNode *&N) { 3933 if (Lex.getKind() == lltok::MetadataVar) 3934 return parseSpecializedMDNode(N); 3935 3936 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N); 3937 } 3938 3939 bool LLParser::parseMDNodeTail(MDNode *&N) { 3940 // !{ ... } 3941 if (Lex.getKind() == lltok::lbrace) 3942 return parseMDTuple(N); 3943 3944 // !42 3945 return parseMDNodeID(N); 3946 } 3947 3948 namespace { 3949 3950 /// Structure to represent an optional metadata field. 3951 template <class FieldTy> struct MDFieldImpl { 3952 typedef MDFieldImpl ImplTy; 3953 FieldTy Val; 3954 bool Seen; 3955 3956 void assign(FieldTy Val) { 3957 Seen = true; 3958 this->Val = std::move(Val); 3959 } 3960 3961 explicit MDFieldImpl(FieldTy Default) 3962 : Val(std::move(Default)), Seen(false) {} 3963 }; 3964 3965 /// Structure to represent an optional metadata field that 3966 /// can be of either type (A or B) and encapsulates the 3967 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3968 /// to reimplement the specifics for representing each Field. 3969 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3970 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3971 FieldTypeA A; 3972 FieldTypeB B; 3973 bool Seen; 3974 3975 enum { 3976 IsInvalid = 0, 3977 IsTypeA = 1, 3978 IsTypeB = 2 3979 } WhatIs; 3980 3981 void assign(FieldTypeA A) { 3982 Seen = true; 3983 this->A = std::move(A); 3984 WhatIs = IsTypeA; 3985 } 3986 3987 void assign(FieldTypeB B) { 3988 Seen = true; 3989 this->B = std::move(B); 3990 WhatIs = IsTypeB; 3991 } 3992 3993 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3994 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3995 WhatIs(IsInvalid) {} 3996 }; 3997 3998 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3999 uint64_t Max; 4000 4001 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 4002 : ImplTy(Default), Max(Max) {} 4003 }; 4004 4005 struct LineField : public MDUnsignedField { 4006 LineField() : MDUnsignedField(0, UINT32_MAX) {} 4007 }; 4008 4009 struct ColumnField : public MDUnsignedField { 4010 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 4011 }; 4012 4013 struct DwarfTagField : public MDUnsignedField { 4014 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 4015 DwarfTagField(dwarf::Tag DefaultTag) 4016 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 4017 }; 4018 4019 struct DwarfMacinfoTypeField : public MDUnsignedField { 4020 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 4021 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 4022 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 4023 }; 4024 4025 struct DwarfAttEncodingField : public MDUnsignedField { 4026 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 4027 }; 4028 4029 struct DwarfVirtualityField : public MDUnsignedField { 4030 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 4031 }; 4032 4033 struct DwarfLangField : public MDUnsignedField { 4034 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 4035 }; 4036 4037 struct DwarfCCField : public MDUnsignedField { 4038 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 4039 }; 4040 4041 struct EmissionKindField : public MDUnsignedField { 4042 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 4043 }; 4044 4045 struct NameTableKindField : public MDUnsignedField { 4046 NameTableKindField() 4047 : MDUnsignedField( 4048 0, (unsigned) 4049 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 4050 }; 4051 4052 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 4053 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 4054 }; 4055 4056 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 4057 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 4058 }; 4059 4060 struct MDAPSIntField : public MDFieldImpl<APSInt> { 4061 MDAPSIntField() : ImplTy(APSInt()) {} 4062 }; 4063 4064 struct MDSignedField : public MDFieldImpl<int64_t> { 4065 int64_t Min; 4066 int64_t Max; 4067 4068 MDSignedField(int64_t Default = 0) 4069 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 4070 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 4071 : ImplTy(Default), Min(Min), Max(Max) {} 4072 }; 4073 4074 struct MDBoolField : public MDFieldImpl<bool> { 4075 MDBoolField(bool Default = false) : ImplTy(Default) {} 4076 }; 4077 4078 struct MDField : public MDFieldImpl<Metadata *> { 4079 bool AllowNull; 4080 4081 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 4082 }; 4083 4084 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> { 4085 MDConstant() : ImplTy(nullptr) {} 4086 }; 4087 4088 struct MDStringField : public MDFieldImpl<MDString *> { 4089 bool AllowEmpty; 4090 MDStringField(bool AllowEmpty = true) 4091 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 4092 }; 4093 4094 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 4095 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 4096 }; 4097 4098 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 4099 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 4100 }; 4101 4102 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 4103 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 4104 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 4105 4106 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 4107 bool AllowNull = true) 4108 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 4109 4110 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4111 bool isMDField() const { return WhatIs == IsTypeB; } 4112 int64_t getMDSignedValue() const { 4113 assert(isMDSignedField() && "Wrong field type"); 4114 return A.Val; 4115 } 4116 Metadata *getMDFieldValue() const { 4117 assert(isMDField() && "Wrong field type"); 4118 return B.Val; 4119 } 4120 }; 4121 4122 struct MDSignedOrUnsignedField 4123 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> { 4124 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {} 4125 4126 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4127 bool isMDUnsignedField() const { return WhatIs == IsTypeB; } 4128 int64_t getMDSignedValue() const { 4129 assert(isMDSignedField() && "Wrong field type"); 4130 return A.Val; 4131 } 4132 uint64_t getMDUnsignedValue() const { 4133 assert(isMDUnsignedField() && "Wrong field type"); 4134 return B.Val; 4135 } 4136 }; 4137 4138 } // end anonymous namespace 4139 4140 namespace llvm { 4141 4142 template <> 4143 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 4144 if (Lex.getKind() != lltok::APSInt) 4145 return tokError("expected integer"); 4146 4147 Result.assign(Lex.getAPSIntVal()); 4148 Lex.Lex(); 4149 return false; 4150 } 4151 4152 template <> 4153 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4154 MDUnsignedField &Result) { 4155 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4156 return tokError("expected unsigned integer"); 4157 4158 auto &U = Lex.getAPSIntVal(); 4159 if (U.ugt(Result.Max)) 4160 return tokError("value for '" + Name + "' too large, limit is " + 4161 Twine(Result.Max)); 4162 Result.assign(U.getZExtValue()); 4163 assert(Result.Val <= Result.Max && "Expected value in range"); 4164 Lex.Lex(); 4165 return false; 4166 } 4167 4168 template <> 4169 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { 4170 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4171 } 4172 template <> 4173 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 4174 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4175 } 4176 4177 template <> 4178 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 4179 if (Lex.getKind() == lltok::APSInt) 4180 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4181 4182 if (Lex.getKind() != lltok::DwarfTag) 4183 return tokError("expected DWARF tag"); 4184 4185 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 4186 if (Tag == dwarf::DW_TAG_invalid) 4187 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 4188 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 4189 4190 Result.assign(Tag); 4191 Lex.Lex(); 4192 return false; 4193 } 4194 4195 template <> 4196 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4197 DwarfMacinfoTypeField &Result) { 4198 if (Lex.getKind() == lltok::APSInt) 4199 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4200 4201 if (Lex.getKind() != lltok::DwarfMacinfo) 4202 return tokError("expected DWARF macinfo type"); 4203 4204 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4205 if (Macinfo == dwarf::DW_MACINFO_invalid) 4206 return tokError("invalid DWARF macinfo type" + Twine(" '") + 4207 Lex.getStrVal() + "'"); 4208 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4209 4210 Result.assign(Macinfo); 4211 Lex.Lex(); 4212 return false; 4213 } 4214 4215 template <> 4216 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4217 DwarfVirtualityField &Result) { 4218 if (Lex.getKind() == lltok::APSInt) 4219 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4220 4221 if (Lex.getKind() != lltok::DwarfVirtuality) 4222 return tokError("expected DWARF virtuality code"); 4223 4224 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4225 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4226 return tokError("invalid DWARF virtuality code" + Twine(" '") + 4227 Lex.getStrVal() + "'"); 4228 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4229 Result.assign(Virtuality); 4230 Lex.Lex(); 4231 return false; 4232 } 4233 4234 template <> 4235 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4236 if (Lex.getKind() == lltok::APSInt) 4237 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4238 4239 if (Lex.getKind() != lltok::DwarfLang) 4240 return tokError("expected DWARF language"); 4241 4242 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4243 if (!Lang) 4244 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4245 "'"); 4246 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4247 Result.assign(Lang); 4248 Lex.Lex(); 4249 return false; 4250 } 4251 4252 template <> 4253 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4254 if (Lex.getKind() == lltok::APSInt) 4255 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4256 4257 if (Lex.getKind() != lltok::DwarfCC) 4258 return tokError("expected DWARF calling convention"); 4259 4260 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4261 if (!CC) 4262 return tokError("invalid DWARF calling convention" + Twine(" '") + 4263 Lex.getStrVal() + "'"); 4264 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4265 Result.assign(CC); 4266 Lex.Lex(); 4267 return false; 4268 } 4269 4270 template <> 4271 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4272 EmissionKindField &Result) { 4273 if (Lex.getKind() == lltok::APSInt) 4274 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4275 4276 if (Lex.getKind() != lltok::EmissionKind) 4277 return tokError("expected emission kind"); 4278 4279 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4280 if (!Kind) 4281 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4282 "'"); 4283 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4284 Result.assign(*Kind); 4285 Lex.Lex(); 4286 return false; 4287 } 4288 4289 template <> 4290 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4291 NameTableKindField &Result) { 4292 if (Lex.getKind() == lltok::APSInt) 4293 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4294 4295 if (Lex.getKind() != lltok::NameTableKind) 4296 return tokError("expected nameTable kind"); 4297 4298 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4299 if (!Kind) 4300 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4301 "'"); 4302 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4303 Result.assign((unsigned)*Kind); 4304 Lex.Lex(); 4305 return false; 4306 } 4307 4308 template <> 4309 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4310 DwarfAttEncodingField &Result) { 4311 if (Lex.getKind() == lltok::APSInt) 4312 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4313 4314 if (Lex.getKind() != lltok::DwarfAttEncoding) 4315 return tokError("expected DWARF type attribute encoding"); 4316 4317 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4318 if (!Encoding) 4319 return tokError("invalid DWARF type attribute encoding" + Twine(" '") + 4320 Lex.getStrVal() + "'"); 4321 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4322 Result.assign(Encoding); 4323 Lex.Lex(); 4324 return false; 4325 } 4326 4327 /// DIFlagField 4328 /// ::= uint32 4329 /// ::= DIFlagVector 4330 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4331 template <> 4332 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4333 4334 // parser for a single flag. 4335 auto parseFlag = [&](DINode::DIFlags &Val) { 4336 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4337 uint32_t TempVal = static_cast<uint32_t>(Val); 4338 bool Res = parseUInt32(TempVal); 4339 Val = static_cast<DINode::DIFlags>(TempVal); 4340 return Res; 4341 } 4342 4343 if (Lex.getKind() != lltok::DIFlag) 4344 return tokError("expected debug info flag"); 4345 4346 Val = DINode::getFlag(Lex.getStrVal()); 4347 if (!Val) 4348 return tokError(Twine("invalid debug info flag flag '") + 4349 Lex.getStrVal() + "'"); 4350 Lex.Lex(); 4351 return false; 4352 }; 4353 4354 // parse the flags and combine them together. 4355 DINode::DIFlags Combined = DINode::FlagZero; 4356 do { 4357 DINode::DIFlags Val; 4358 if (parseFlag(Val)) 4359 return true; 4360 Combined |= Val; 4361 } while (EatIfPresent(lltok::bar)); 4362 4363 Result.assign(Combined); 4364 return false; 4365 } 4366 4367 /// DISPFlagField 4368 /// ::= uint32 4369 /// ::= DISPFlagVector 4370 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4371 template <> 4372 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4373 4374 // parser for a single flag. 4375 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4376 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4377 uint32_t TempVal = static_cast<uint32_t>(Val); 4378 bool Res = parseUInt32(TempVal); 4379 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4380 return Res; 4381 } 4382 4383 if (Lex.getKind() != lltok::DISPFlag) 4384 return tokError("expected debug info flag"); 4385 4386 Val = DISubprogram::getFlag(Lex.getStrVal()); 4387 if (!Val) 4388 return tokError(Twine("invalid subprogram debug info flag '") + 4389 Lex.getStrVal() + "'"); 4390 Lex.Lex(); 4391 return false; 4392 }; 4393 4394 // parse the flags and combine them together. 4395 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4396 do { 4397 DISubprogram::DISPFlags Val; 4398 if (parseFlag(Val)) 4399 return true; 4400 Combined |= Val; 4401 } while (EatIfPresent(lltok::bar)); 4402 4403 Result.assign(Combined); 4404 return false; 4405 } 4406 4407 template <> 4408 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { 4409 if (Lex.getKind() != lltok::APSInt) 4410 return tokError("expected signed integer"); 4411 4412 auto &S = Lex.getAPSIntVal(); 4413 if (S < Result.Min) 4414 return tokError("value for '" + Name + "' too small, limit is " + 4415 Twine(Result.Min)); 4416 if (S > Result.Max) 4417 return tokError("value for '" + Name + "' too large, limit is " + 4418 Twine(Result.Max)); 4419 Result.assign(S.getExtValue()); 4420 assert(Result.Val >= Result.Min && "Expected value in range"); 4421 assert(Result.Val <= Result.Max && "Expected value in range"); 4422 Lex.Lex(); 4423 return false; 4424 } 4425 4426 template <> 4427 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4428 switch (Lex.getKind()) { 4429 default: 4430 return tokError("expected 'true' or 'false'"); 4431 case lltok::kw_true: 4432 Result.assign(true); 4433 break; 4434 case lltok::kw_false: 4435 Result.assign(false); 4436 break; 4437 } 4438 Lex.Lex(); 4439 return false; 4440 } 4441 4442 template <> 4443 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4444 if (Lex.getKind() == lltok::kw_null) { 4445 if (!Result.AllowNull) 4446 return tokError("'" + Name + "' cannot be null"); 4447 Lex.Lex(); 4448 Result.assign(nullptr); 4449 return false; 4450 } 4451 4452 Metadata *MD; 4453 if (parseMetadata(MD, nullptr)) 4454 return true; 4455 4456 Result.assign(MD); 4457 return false; 4458 } 4459 4460 template <> 4461 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4462 MDSignedOrMDField &Result) { 4463 // Try to parse a signed int. 4464 if (Lex.getKind() == lltok::APSInt) { 4465 MDSignedField Res = Result.A; 4466 if (!parseMDField(Loc, Name, Res)) { 4467 Result.assign(Res); 4468 return false; 4469 } 4470 return true; 4471 } 4472 4473 // Otherwise, try to parse as an MDField. 4474 MDField Res = Result.B; 4475 if (!parseMDField(Loc, Name, Res)) { 4476 Result.assign(Res); 4477 return false; 4478 } 4479 4480 return true; 4481 } 4482 4483 template <> 4484 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4485 LocTy ValueLoc = Lex.getLoc(); 4486 std::string S; 4487 if (parseStringConstant(S)) 4488 return true; 4489 4490 if (!Result.AllowEmpty && S.empty()) 4491 return error(ValueLoc, "'" + Name + "' cannot be empty"); 4492 4493 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4494 return false; 4495 } 4496 4497 template <> 4498 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4499 SmallVector<Metadata *, 4> MDs; 4500 if (parseMDNodeVector(MDs)) 4501 return true; 4502 4503 Result.assign(std::move(MDs)); 4504 return false; 4505 } 4506 4507 template <> 4508 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4509 ChecksumKindField &Result) { 4510 Optional<DIFile::ChecksumKind> CSKind = 4511 DIFile::getChecksumKind(Lex.getStrVal()); 4512 4513 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4514 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() + 4515 "'"); 4516 4517 Result.assign(*CSKind); 4518 Lex.Lex(); 4519 return false; 4520 } 4521 4522 } // end namespace llvm 4523 4524 template <class ParserTy> 4525 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { 4526 do { 4527 if (Lex.getKind() != lltok::LabelStr) 4528 return tokError("expected field label here"); 4529 4530 if (ParseField()) 4531 return true; 4532 } while (EatIfPresent(lltok::comma)); 4533 4534 return false; 4535 } 4536 4537 template <class ParserTy> 4538 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { 4539 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4540 Lex.Lex(); 4541 4542 if (parseToken(lltok::lparen, "expected '(' here")) 4543 return true; 4544 if (Lex.getKind() != lltok::rparen) 4545 if (parseMDFieldsImplBody(ParseField)) 4546 return true; 4547 4548 ClosingLoc = Lex.getLoc(); 4549 return parseToken(lltok::rparen, "expected ')' here"); 4550 } 4551 4552 template <class FieldTy> 4553 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { 4554 if (Result.Seen) 4555 return tokError("field '" + Name + "' cannot be specified more than once"); 4556 4557 LocTy Loc = Lex.getLoc(); 4558 Lex.Lex(); 4559 return parseMDField(Loc, Name, Result); 4560 } 4561 4562 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4563 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4564 4565 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4566 if (Lex.getStrVal() == #CLASS) \ 4567 return parse##CLASS(N, IsDistinct); 4568 #include "llvm/IR/Metadata.def" 4569 4570 return tokError("expected metadata type"); 4571 } 4572 4573 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4574 #define NOP_FIELD(NAME, TYPE, INIT) 4575 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4576 if (!NAME.Seen) \ 4577 return error(ClosingLoc, "missing required field '" #NAME "'"); 4578 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4579 if (Lex.getStrVal() == #NAME) \ 4580 return parseMDField(#NAME, NAME); 4581 #define PARSE_MD_FIELDS() \ 4582 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4583 do { \ 4584 LocTy ClosingLoc; \ 4585 if (parseMDFieldsImpl( \ 4586 [&]() -> bool { \ 4587 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4588 return tokError(Twine("invalid field '") + Lex.getStrVal() + \ 4589 "'"); \ 4590 }, \ 4591 ClosingLoc)) \ 4592 return true; \ 4593 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4594 } while (false) 4595 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4596 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4597 4598 /// parseDILocationFields: 4599 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4600 /// isImplicitCode: true) 4601 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { 4602 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4603 OPTIONAL(line, LineField, ); \ 4604 OPTIONAL(column, ColumnField, ); \ 4605 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4606 OPTIONAL(inlinedAt, MDField, ); \ 4607 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4608 PARSE_MD_FIELDS(); 4609 #undef VISIT_MD_FIELDS 4610 4611 Result = 4612 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4613 inlinedAt.Val, isImplicitCode.Val)); 4614 return false; 4615 } 4616 4617 /// parseGenericDINode: 4618 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4619 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { 4620 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4621 REQUIRED(tag, DwarfTagField, ); \ 4622 OPTIONAL(header, MDStringField, ); \ 4623 OPTIONAL(operands, MDFieldList, ); 4624 PARSE_MD_FIELDS(); 4625 #undef VISIT_MD_FIELDS 4626 4627 Result = GET_OR_DISTINCT(GenericDINode, 4628 (Context, tag.Val, header.Val, operands.Val)); 4629 return false; 4630 } 4631 4632 /// parseDISubrange: 4633 /// ::= !DISubrange(count: 30, lowerBound: 2) 4634 /// ::= !DISubrange(count: !node, lowerBound: 2) 4635 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 4636 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { 4637 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4638 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4639 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4640 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4641 OPTIONAL(stride, MDSignedOrMDField, ); 4642 PARSE_MD_FIELDS(); 4643 #undef VISIT_MD_FIELDS 4644 4645 Metadata *Count = nullptr; 4646 Metadata *LowerBound = nullptr; 4647 Metadata *UpperBound = nullptr; 4648 Metadata *Stride = nullptr; 4649 if (count.isMDSignedField()) 4650 Count = ConstantAsMetadata::get(ConstantInt::getSigned( 4651 Type::getInt64Ty(Context), count.getMDSignedValue())); 4652 else if (count.isMDField()) 4653 Count = count.getMDFieldValue(); 4654 4655 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4656 if (Bound.isMDSignedField()) 4657 return ConstantAsMetadata::get(ConstantInt::getSigned( 4658 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 4659 if (Bound.isMDField()) 4660 return Bound.getMDFieldValue(); 4661 return nullptr; 4662 }; 4663 4664 LowerBound = convToMetadata(lowerBound); 4665 UpperBound = convToMetadata(upperBound); 4666 Stride = convToMetadata(stride); 4667 4668 Result = GET_OR_DISTINCT(DISubrange, 4669 (Context, Count, LowerBound, UpperBound, Stride)); 4670 4671 return false; 4672 } 4673 4674 /// parseDIGenericSubrange: 4675 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: 4676 /// !node3) 4677 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { 4678 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4679 OPTIONAL(count, MDSignedOrMDField, ); \ 4680 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4681 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4682 OPTIONAL(stride, MDSignedOrMDField, ); 4683 PARSE_MD_FIELDS(); 4684 #undef VISIT_MD_FIELDS 4685 4686 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4687 if (Bound.isMDSignedField()) 4688 return DIExpression::get( 4689 Context, {dwarf::DW_OP_consts, 4690 static_cast<uint64_t>(Bound.getMDSignedValue())}); 4691 if (Bound.isMDField()) 4692 return Bound.getMDFieldValue(); 4693 return nullptr; 4694 }; 4695 4696 Metadata *Count = ConvToMetadata(count); 4697 Metadata *LowerBound = ConvToMetadata(lowerBound); 4698 Metadata *UpperBound = ConvToMetadata(upperBound); 4699 Metadata *Stride = ConvToMetadata(stride); 4700 4701 Result = GET_OR_DISTINCT(DIGenericSubrange, 4702 (Context, Count, LowerBound, UpperBound, Stride)); 4703 4704 return false; 4705 } 4706 4707 /// parseDIEnumerator: 4708 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4709 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4710 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4711 REQUIRED(name, MDStringField, ); \ 4712 REQUIRED(value, MDAPSIntField, ); \ 4713 OPTIONAL(isUnsigned, MDBoolField, (false)); 4714 PARSE_MD_FIELDS(); 4715 #undef VISIT_MD_FIELDS 4716 4717 if (isUnsigned.Val && value.Val.isNegative()) 4718 return tokError("unsigned enumerator with negative value"); 4719 4720 APSInt Value(value.Val); 4721 // Add a leading zero so that unsigned values with the msb set are not 4722 // mistaken for negative values when used for signed enumerators. 4723 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 4724 Value = Value.zext(Value.getBitWidth() + 1); 4725 4726 Result = 4727 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4728 4729 return false; 4730 } 4731 4732 /// parseDIBasicType: 4733 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4734 /// encoding: DW_ATE_encoding, flags: 0) 4735 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { 4736 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4737 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4738 OPTIONAL(name, MDStringField, ); \ 4739 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4740 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4741 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4742 OPTIONAL(flags, DIFlagField, ); 4743 PARSE_MD_FIELDS(); 4744 #undef VISIT_MD_FIELDS 4745 4746 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4747 align.Val, encoding.Val, flags.Val)); 4748 return false; 4749 } 4750 4751 /// parseDIStringType: 4752 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) 4753 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { 4754 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4755 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ 4756 OPTIONAL(name, MDStringField, ); \ 4757 OPTIONAL(stringLength, MDField, ); \ 4758 OPTIONAL(stringLengthExpression, MDField, ); \ 4759 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4760 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4761 OPTIONAL(encoding, DwarfAttEncodingField, ); 4762 PARSE_MD_FIELDS(); 4763 #undef VISIT_MD_FIELDS 4764 4765 Result = GET_OR_DISTINCT(DIStringType, 4766 (Context, tag.Val, name.Val, stringLength.Val, 4767 stringLengthExpression.Val, size.Val, align.Val, 4768 encoding.Val)); 4769 return false; 4770 } 4771 4772 /// parseDIDerivedType: 4773 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4774 /// line: 7, scope: !1, baseType: !2, size: 32, 4775 /// align: 32, offset: 0, flags: 0, extraData: !3, 4776 /// dwarfAddressSpace: 3) 4777 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4778 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4779 REQUIRED(tag, DwarfTagField, ); \ 4780 OPTIONAL(name, MDStringField, ); \ 4781 OPTIONAL(file, MDField, ); \ 4782 OPTIONAL(line, LineField, ); \ 4783 OPTIONAL(scope, MDField, ); \ 4784 REQUIRED(baseType, MDField, ); \ 4785 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4786 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4787 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4788 OPTIONAL(flags, DIFlagField, ); \ 4789 OPTIONAL(extraData, MDField, ); \ 4790 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 4791 PARSE_MD_FIELDS(); 4792 #undef VISIT_MD_FIELDS 4793 4794 Optional<unsigned> DWARFAddressSpace; 4795 if (dwarfAddressSpace.Val != UINT32_MAX) 4796 DWARFAddressSpace = dwarfAddressSpace.Val; 4797 4798 Result = GET_OR_DISTINCT(DIDerivedType, 4799 (Context, tag.Val, name.Val, file.Val, line.Val, 4800 scope.Val, baseType.Val, size.Val, align.Val, 4801 offset.Val, DWARFAddressSpace, flags.Val, 4802 extraData.Val)); 4803 return false; 4804 } 4805 4806 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { 4807 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4808 REQUIRED(tag, DwarfTagField, ); \ 4809 OPTIONAL(name, MDStringField, ); \ 4810 OPTIONAL(file, MDField, ); \ 4811 OPTIONAL(line, LineField, ); \ 4812 OPTIONAL(scope, MDField, ); \ 4813 OPTIONAL(baseType, MDField, ); \ 4814 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4815 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4816 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4817 OPTIONAL(flags, DIFlagField, ); \ 4818 OPTIONAL(elements, MDField, ); \ 4819 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4820 OPTIONAL(vtableHolder, MDField, ); \ 4821 OPTIONAL(templateParams, MDField, ); \ 4822 OPTIONAL(identifier, MDStringField, ); \ 4823 OPTIONAL(discriminator, MDField, ); \ 4824 OPTIONAL(dataLocation, MDField, ); \ 4825 OPTIONAL(associated, MDField, ); \ 4826 OPTIONAL(allocated, MDField, ); \ 4827 OPTIONAL(rank, MDSignedOrMDField, ); 4828 PARSE_MD_FIELDS(); 4829 #undef VISIT_MD_FIELDS 4830 4831 Metadata *Rank = nullptr; 4832 if (rank.isMDSignedField()) 4833 Rank = ConstantAsMetadata::get(ConstantInt::getSigned( 4834 Type::getInt64Ty(Context), rank.getMDSignedValue())); 4835 else if (rank.isMDField()) 4836 Rank = rank.getMDFieldValue(); 4837 4838 // If this has an identifier try to build an ODR type. 4839 if (identifier.Val) 4840 if (auto *CT = DICompositeType::buildODRType( 4841 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4842 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4843 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 4844 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4845 Rank)) { 4846 Result = CT; 4847 return false; 4848 } 4849 4850 // Create a new node, and save it in the context if it belongs in the type 4851 // map. 4852 Result = GET_OR_DISTINCT( 4853 DICompositeType, 4854 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4855 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4856 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4857 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4858 Rank)); 4859 return false; 4860 } 4861 4862 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4863 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4864 OPTIONAL(flags, DIFlagField, ); \ 4865 OPTIONAL(cc, DwarfCCField, ); \ 4866 REQUIRED(types, MDField, ); 4867 PARSE_MD_FIELDS(); 4868 #undef VISIT_MD_FIELDS 4869 4870 Result = GET_OR_DISTINCT(DISubroutineType, 4871 (Context, flags.Val, cc.Val, types.Val)); 4872 return false; 4873 } 4874 4875 /// parseDIFileType: 4876 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4877 /// checksumkind: CSK_MD5, 4878 /// checksum: "000102030405060708090a0b0c0d0e0f", 4879 /// source: "source file contents") 4880 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { 4881 // The default constructed value for checksumkind is required, but will never 4882 // be used, as the parser checks if the field was actually Seen before using 4883 // the Val. 4884 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4885 REQUIRED(filename, MDStringField, ); \ 4886 REQUIRED(directory, MDStringField, ); \ 4887 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4888 OPTIONAL(checksum, MDStringField, ); \ 4889 OPTIONAL(source, MDStringField, ); 4890 PARSE_MD_FIELDS(); 4891 #undef VISIT_MD_FIELDS 4892 4893 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4894 if (checksumkind.Seen && checksum.Seen) 4895 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4896 else if (checksumkind.Seen || checksum.Seen) 4897 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4898 4899 Optional<MDString *> OptSource; 4900 if (source.Seen) 4901 OptSource = source.Val; 4902 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4903 OptChecksum, OptSource)); 4904 return false; 4905 } 4906 4907 /// parseDICompileUnit: 4908 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4909 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4910 /// splitDebugFilename: "abc.debug", 4911 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4912 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4913 /// sysroot: "/", sdk: "MacOSX.sdk") 4914 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4915 if (!IsDistinct) 4916 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4917 4918 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4919 REQUIRED(language, DwarfLangField, ); \ 4920 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4921 OPTIONAL(producer, MDStringField, ); \ 4922 OPTIONAL(isOptimized, MDBoolField, ); \ 4923 OPTIONAL(flags, MDStringField, ); \ 4924 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4925 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4926 OPTIONAL(emissionKind, EmissionKindField, ); \ 4927 OPTIONAL(enums, MDField, ); \ 4928 OPTIONAL(retainedTypes, MDField, ); \ 4929 OPTIONAL(globals, MDField, ); \ 4930 OPTIONAL(imports, MDField, ); \ 4931 OPTIONAL(macros, MDField, ); \ 4932 OPTIONAL(dwoId, MDUnsignedField, ); \ 4933 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4934 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4935 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4936 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 4937 OPTIONAL(sysroot, MDStringField, ); \ 4938 OPTIONAL(sdk, MDStringField, ); 4939 PARSE_MD_FIELDS(); 4940 #undef VISIT_MD_FIELDS 4941 4942 Result = DICompileUnit::getDistinct( 4943 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4944 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4945 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4946 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4947 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 4948 return false; 4949 } 4950 4951 /// parseDISubprogram: 4952 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4953 /// file: !1, line: 7, type: !2, isLocal: false, 4954 /// isDefinition: true, scopeLine: 8, containingType: !3, 4955 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4956 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4957 /// spFlags: 10, isOptimized: false, templateParams: !4, 4958 /// declaration: !5, retainedNodes: !6, thrownTypes: !7) 4959 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { 4960 auto Loc = Lex.getLoc(); 4961 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4962 OPTIONAL(scope, MDField, ); \ 4963 OPTIONAL(name, MDStringField, ); \ 4964 OPTIONAL(linkageName, MDStringField, ); \ 4965 OPTIONAL(file, MDField, ); \ 4966 OPTIONAL(line, LineField, ); \ 4967 OPTIONAL(type, MDField, ); \ 4968 OPTIONAL(isLocal, MDBoolField, ); \ 4969 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4970 OPTIONAL(scopeLine, LineField, ); \ 4971 OPTIONAL(containingType, MDField, ); \ 4972 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4973 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4974 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4975 OPTIONAL(flags, DIFlagField, ); \ 4976 OPTIONAL(spFlags, DISPFlagField, ); \ 4977 OPTIONAL(isOptimized, MDBoolField, ); \ 4978 OPTIONAL(unit, MDField, ); \ 4979 OPTIONAL(templateParams, MDField, ); \ 4980 OPTIONAL(declaration, MDField, ); \ 4981 OPTIONAL(retainedNodes, MDField, ); \ 4982 OPTIONAL(thrownTypes, MDField, ); 4983 PARSE_MD_FIELDS(); 4984 #undef VISIT_MD_FIELDS 4985 4986 // An explicit spFlags field takes precedence over individual fields in 4987 // older IR versions. 4988 DISubprogram::DISPFlags SPFlags = 4989 spFlags.Seen ? spFlags.Val 4990 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4991 isOptimized.Val, virtuality.Val); 4992 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4993 return Lex.Error( 4994 Loc, 4995 "missing 'distinct', required for !DISubprogram that is a Definition"); 4996 Result = GET_OR_DISTINCT( 4997 DISubprogram, 4998 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4999 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 5000 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 5001 declaration.Val, retainedNodes.Val, thrownTypes.Val)); 5002 return false; 5003 } 5004 5005 /// parseDILexicalBlock: 5006 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 5007 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 5008 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5009 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5010 OPTIONAL(file, MDField, ); \ 5011 OPTIONAL(line, LineField, ); \ 5012 OPTIONAL(column, ColumnField, ); 5013 PARSE_MD_FIELDS(); 5014 #undef VISIT_MD_FIELDS 5015 5016 Result = GET_OR_DISTINCT( 5017 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 5018 return false; 5019 } 5020 5021 /// parseDILexicalBlockFile: 5022 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 5023 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 5024 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5025 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5026 OPTIONAL(file, MDField, ); \ 5027 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 5028 PARSE_MD_FIELDS(); 5029 #undef VISIT_MD_FIELDS 5030 5031 Result = GET_OR_DISTINCT(DILexicalBlockFile, 5032 (Context, scope.Val, file.Val, discriminator.Val)); 5033 return false; 5034 } 5035 5036 /// parseDICommonBlock: 5037 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 5038 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { 5039 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5040 REQUIRED(scope, MDField, ); \ 5041 OPTIONAL(declaration, MDField, ); \ 5042 OPTIONAL(name, MDStringField, ); \ 5043 OPTIONAL(file, MDField, ); \ 5044 OPTIONAL(line, LineField, ); 5045 PARSE_MD_FIELDS(); 5046 #undef VISIT_MD_FIELDS 5047 5048 Result = GET_OR_DISTINCT(DICommonBlock, 5049 (Context, scope.Val, declaration.Val, name.Val, 5050 file.Val, line.Val)); 5051 return false; 5052 } 5053 5054 /// parseDINamespace: 5055 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 5056 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { 5057 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5058 REQUIRED(scope, MDField, ); \ 5059 OPTIONAL(name, MDStringField, ); \ 5060 OPTIONAL(exportSymbols, MDBoolField, ); 5061 PARSE_MD_FIELDS(); 5062 #undef VISIT_MD_FIELDS 5063 5064 Result = GET_OR_DISTINCT(DINamespace, 5065 (Context, scope.Val, name.Val, exportSymbols.Val)); 5066 return false; 5067 } 5068 5069 /// parseDIMacro: 5070 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: 5071 /// "SomeValue") 5072 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { 5073 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5074 REQUIRED(type, DwarfMacinfoTypeField, ); \ 5075 OPTIONAL(line, LineField, ); \ 5076 REQUIRED(name, MDStringField, ); \ 5077 OPTIONAL(value, MDStringField, ); 5078 PARSE_MD_FIELDS(); 5079 #undef VISIT_MD_FIELDS 5080 5081 Result = GET_OR_DISTINCT(DIMacro, 5082 (Context, type.Val, line.Val, name.Val, value.Val)); 5083 return false; 5084 } 5085 5086 /// parseDIMacroFile: 5087 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 5088 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { 5089 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5090 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 5091 OPTIONAL(line, LineField, ); \ 5092 REQUIRED(file, MDField, ); \ 5093 OPTIONAL(nodes, MDField, ); 5094 PARSE_MD_FIELDS(); 5095 #undef VISIT_MD_FIELDS 5096 5097 Result = GET_OR_DISTINCT(DIMacroFile, 5098 (Context, type.Val, line.Val, file.Val, nodes.Val)); 5099 return false; 5100 } 5101 5102 /// parseDIModule: 5103 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 5104 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 5105 /// file: !1, line: 4) 5106 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { 5107 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5108 REQUIRED(scope, MDField, ); \ 5109 REQUIRED(name, MDStringField, ); \ 5110 OPTIONAL(configMacros, MDStringField, ); \ 5111 OPTIONAL(includePath, MDStringField, ); \ 5112 OPTIONAL(apinotes, MDStringField, ); \ 5113 OPTIONAL(file, MDField, ); \ 5114 OPTIONAL(line, LineField, ); 5115 PARSE_MD_FIELDS(); 5116 #undef VISIT_MD_FIELDS 5117 5118 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 5119 configMacros.Val, includePath.Val, 5120 apinotes.Val, line.Val)); 5121 return false; 5122 } 5123 5124 /// parseDITemplateTypeParameter: 5125 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 5126 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 5127 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5128 OPTIONAL(name, MDStringField, ); \ 5129 REQUIRED(type, MDField, ); \ 5130 OPTIONAL(defaulted, MDBoolField, ); 5131 PARSE_MD_FIELDS(); 5132 #undef VISIT_MD_FIELDS 5133 5134 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 5135 (Context, name.Val, type.Val, defaulted.Val)); 5136 return false; 5137 } 5138 5139 /// parseDITemplateValueParameter: 5140 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 5141 /// name: "V", type: !1, defaulted: false, 5142 /// value: i32 7) 5143 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 5144 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5145 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 5146 OPTIONAL(name, MDStringField, ); \ 5147 OPTIONAL(type, MDField, ); \ 5148 OPTIONAL(defaulted, MDBoolField, ); \ 5149 REQUIRED(value, MDField, ); 5150 5151 PARSE_MD_FIELDS(); 5152 #undef VISIT_MD_FIELDS 5153 5154 Result = GET_OR_DISTINCT( 5155 DITemplateValueParameter, 5156 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 5157 return false; 5158 } 5159 5160 /// parseDIGlobalVariable: 5161 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 5162 /// file: !1, line: 7, type: !2, isLocal: false, 5163 /// isDefinition: true, templateParams: !3, 5164 /// declaration: !4, align: 8) 5165 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 5166 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5167 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 5168 OPTIONAL(scope, MDField, ); \ 5169 OPTIONAL(linkageName, MDStringField, ); \ 5170 OPTIONAL(file, MDField, ); \ 5171 OPTIONAL(line, LineField, ); \ 5172 OPTIONAL(type, MDField, ); \ 5173 OPTIONAL(isLocal, MDBoolField, ); \ 5174 OPTIONAL(isDefinition, MDBoolField, (true)); \ 5175 OPTIONAL(templateParams, MDField, ); \ 5176 OPTIONAL(declaration, MDField, ); \ 5177 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 5178 PARSE_MD_FIELDS(); 5179 #undef VISIT_MD_FIELDS 5180 5181 Result = 5182 GET_OR_DISTINCT(DIGlobalVariable, 5183 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 5184 line.Val, type.Val, isLocal.Val, isDefinition.Val, 5185 declaration.Val, templateParams.Val, align.Val)); 5186 return false; 5187 } 5188 5189 /// parseDILocalVariable: 5190 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 5191 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5192 /// align: 8) 5193 /// ::= !DILocalVariable(scope: !0, name: "foo", 5194 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5195 /// align: 8) 5196 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { 5197 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5198 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5199 OPTIONAL(name, MDStringField, ); \ 5200 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 5201 OPTIONAL(file, MDField, ); \ 5202 OPTIONAL(line, LineField, ); \ 5203 OPTIONAL(type, MDField, ); \ 5204 OPTIONAL(flags, DIFlagField, ); \ 5205 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 5206 PARSE_MD_FIELDS(); 5207 #undef VISIT_MD_FIELDS 5208 5209 Result = GET_OR_DISTINCT(DILocalVariable, 5210 (Context, scope.Val, name.Val, file.Val, line.Val, 5211 type.Val, arg.Val, flags.Val, align.Val)); 5212 return false; 5213 } 5214 5215 /// parseDILabel: 5216 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 5217 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { 5218 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5219 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5220 REQUIRED(name, MDStringField, ); \ 5221 REQUIRED(file, MDField, ); \ 5222 REQUIRED(line, LineField, ); 5223 PARSE_MD_FIELDS(); 5224 #undef VISIT_MD_FIELDS 5225 5226 Result = GET_OR_DISTINCT(DILabel, 5227 (Context, scope.Val, name.Val, file.Val, line.Val)); 5228 return false; 5229 } 5230 5231 /// parseDIExpression: 5232 /// ::= !DIExpression(0, 7, -1) 5233 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { 5234 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5235 Lex.Lex(); 5236 5237 if (parseToken(lltok::lparen, "expected '(' here")) 5238 return true; 5239 5240 SmallVector<uint64_t, 8> Elements; 5241 if (Lex.getKind() != lltok::rparen) 5242 do { 5243 if (Lex.getKind() == lltok::DwarfOp) { 5244 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5245 Lex.Lex(); 5246 Elements.push_back(Op); 5247 continue; 5248 } 5249 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5250 } 5251 5252 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5253 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5254 Lex.Lex(); 5255 Elements.push_back(Op); 5256 continue; 5257 } 5258 return tokError(Twine("invalid DWARF attribute encoding '") + 5259 Lex.getStrVal() + "'"); 5260 } 5261 5262 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5263 return tokError("expected unsigned integer"); 5264 5265 auto &U = Lex.getAPSIntVal(); 5266 if (U.ugt(UINT64_MAX)) 5267 return tokError("element too large, limit is " + Twine(UINT64_MAX)); 5268 Elements.push_back(U.getZExtValue()); 5269 Lex.Lex(); 5270 } while (EatIfPresent(lltok::comma)); 5271 5272 if (parseToken(lltok::rparen, "expected ')' here")) 5273 return true; 5274 5275 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5276 return false; 5277 } 5278 5279 /// parseDIGlobalVariableExpression: 5280 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5281 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, 5282 bool IsDistinct) { 5283 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5284 REQUIRED(var, MDField, ); \ 5285 REQUIRED(expr, MDField, ); 5286 PARSE_MD_FIELDS(); 5287 #undef VISIT_MD_FIELDS 5288 5289 Result = 5290 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5291 return false; 5292 } 5293 5294 /// parseDIObjCProperty: 5295 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5296 /// getter: "getFoo", attributes: 7, type: !2) 5297 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5298 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5299 OPTIONAL(name, MDStringField, ); \ 5300 OPTIONAL(file, MDField, ); \ 5301 OPTIONAL(line, LineField, ); \ 5302 OPTIONAL(setter, MDStringField, ); \ 5303 OPTIONAL(getter, MDStringField, ); \ 5304 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5305 OPTIONAL(type, MDField, ); 5306 PARSE_MD_FIELDS(); 5307 #undef VISIT_MD_FIELDS 5308 5309 Result = GET_OR_DISTINCT(DIObjCProperty, 5310 (Context, name.Val, file.Val, line.Val, setter.Val, 5311 getter.Val, attributes.Val, type.Val)); 5312 return false; 5313 } 5314 5315 /// parseDIImportedEntity: 5316 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5317 /// line: 7, name: "foo") 5318 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5319 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5320 REQUIRED(tag, DwarfTagField, ); \ 5321 REQUIRED(scope, MDField, ); \ 5322 OPTIONAL(entity, MDField, ); \ 5323 OPTIONAL(file, MDField, ); \ 5324 OPTIONAL(line, LineField, ); \ 5325 OPTIONAL(name, MDStringField, ); 5326 PARSE_MD_FIELDS(); 5327 #undef VISIT_MD_FIELDS 5328 5329 Result = GET_OR_DISTINCT( 5330 DIImportedEntity, 5331 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val)); 5332 return false; 5333 } 5334 5335 #undef PARSE_MD_FIELD 5336 #undef NOP_FIELD 5337 #undef REQUIRE_FIELD 5338 #undef DECLARE_FIELD 5339 5340 /// parseMetadataAsValue 5341 /// ::= metadata i32 %local 5342 /// ::= metadata i32 @global 5343 /// ::= metadata i32 7 5344 /// ::= metadata !0 5345 /// ::= metadata !{...} 5346 /// ::= metadata !"string" 5347 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5348 // Note: the type 'metadata' has already been parsed. 5349 Metadata *MD; 5350 if (parseMetadata(MD, &PFS)) 5351 return true; 5352 5353 V = MetadataAsValue::get(Context, MD); 5354 return false; 5355 } 5356 5357 /// parseValueAsMetadata 5358 /// ::= i32 %local 5359 /// ::= i32 @global 5360 /// ::= i32 7 5361 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5362 PerFunctionState *PFS) { 5363 Type *Ty; 5364 LocTy Loc; 5365 if (parseType(Ty, TypeMsg, Loc)) 5366 return true; 5367 if (Ty->isMetadataTy()) 5368 return error(Loc, "invalid metadata-value-metadata roundtrip"); 5369 5370 Value *V; 5371 if (parseValue(Ty, V, PFS)) 5372 return true; 5373 5374 MD = ValueAsMetadata::get(V); 5375 return false; 5376 } 5377 5378 /// parseMetadata 5379 /// ::= i32 %local 5380 /// ::= i32 @global 5381 /// ::= i32 7 5382 /// ::= !42 5383 /// ::= !{...} 5384 /// ::= !"string" 5385 /// ::= !DILocation(...) 5386 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5387 if (Lex.getKind() == lltok::MetadataVar) { 5388 MDNode *N; 5389 if (parseSpecializedMDNode(N)) 5390 return true; 5391 MD = N; 5392 return false; 5393 } 5394 5395 // ValueAsMetadata: 5396 // <type> <value> 5397 if (Lex.getKind() != lltok::exclaim) 5398 return parseValueAsMetadata(MD, "expected metadata operand", PFS); 5399 5400 // '!'. 5401 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5402 Lex.Lex(); 5403 5404 // MDString: 5405 // ::= '!' STRINGCONSTANT 5406 if (Lex.getKind() == lltok::StringConstant) { 5407 MDString *S; 5408 if (parseMDString(S)) 5409 return true; 5410 MD = S; 5411 return false; 5412 } 5413 5414 // MDNode: 5415 // !{ ... } 5416 // !7 5417 MDNode *N; 5418 if (parseMDNodeTail(N)) 5419 return true; 5420 MD = N; 5421 return false; 5422 } 5423 5424 //===----------------------------------------------------------------------===// 5425 // Function Parsing. 5426 //===----------------------------------------------------------------------===// 5427 5428 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5429 PerFunctionState *PFS, bool IsCall) { 5430 if (Ty->isFunctionTy()) 5431 return error(ID.Loc, "functions are not values, refer to them as pointers"); 5432 5433 switch (ID.Kind) { 5434 case ValID::t_LocalID: 5435 if (!PFS) 5436 return error(ID.Loc, "invalid use of function-local name"); 5437 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5438 return V == nullptr; 5439 case ValID::t_LocalName: 5440 if (!PFS) 5441 return error(ID.Loc, "invalid use of function-local name"); 5442 V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall); 5443 return V == nullptr; 5444 case ValID::t_InlineAsm: { 5445 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5446 return error(ID.Loc, "invalid type for inline asm constraint string"); 5447 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, 5448 (ID.UIntVal >> 1) & 1, 5449 (InlineAsm::AsmDialect(ID.UIntVal >> 2))); 5450 return false; 5451 } 5452 case ValID::t_GlobalName: 5453 V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall); 5454 return V == nullptr; 5455 case ValID::t_GlobalID: 5456 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5457 return V == nullptr; 5458 case ValID::t_APSInt: 5459 if (!Ty->isIntegerTy()) 5460 return error(ID.Loc, "integer constant must have integer type"); 5461 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5462 V = ConstantInt::get(Context, ID.APSIntVal); 5463 return false; 5464 case ValID::t_APFloat: 5465 if (!Ty->isFloatingPointTy() || 5466 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5467 return error(ID.Loc, "floating point constant invalid for type"); 5468 5469 // The lexer has no type info, so builds all half, bfloat, float, and double 5470 // FP constants as double. Fix this here. Long double does not need this. 5471 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5472 // Check for signaling before potentially converting and losing that info. 5473 bool IsSNAN = ID.APFloatVal.isSignaling(); 5474 bool Ignored; 5475 if (Ty->isHalfTy()) 5476 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5477 &Ignored); 5478 else if (Ty->isBFloatTy()) 5479 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 5480 &Ignored); 5481 else if (Ty->isFloatTy()) 5482 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5483 &Ignored); 5484 if (IsSNAN) { 5485 // The convert call above may quiet an SNaN, so manufacture another 5486 // SNaN. The bitcast works because the payload (significand) parameter 5487 // is truncated to fit. 5488 APInt Payload = ID.APFloatVal.bitcastToAPInt(); 5489 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(), 5490 ID.APFloatVal.isNegative(), &Payload); 5491 } 5492 } 5493 V = ConstantFP::get(Context, ID.APFloatVal); 5494 5495 if (V->getType() != Ty) 5496 return error(ID.Loc, "floating point constant does not have type '" + 5497 getTypeString(Ty) + "'"); 5498 5499 return false; 5500 case ValID::t_Null: 5501 if (!Ty->isPointerTy()) 5502 return error(ID.Loc, "null must be a pointer type"); 5503 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5504 return false; 5505 case ValID::t_Undef: 5506 // FIXME: LabelTy should not be a first-class type. 5507 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5508 return error(ID.Loc, "invalid type for undef constant"); 5509 V = UndefValue::get(Ty); 5510 return false; 5511 case ValID::t_EmptyArray: 5512 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5513 return error(ID.Loc, "invalid empty array initializer"); 5514 V = UndefValue::get(Ty); 5515 return false; 5516 case ValID::t_Zero: 5517 // FIXME: LabelTy should not be a first-class type. 5518 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5519 return error(ID.Loc, "invalid type for null constant"); 5520 V = Constant::getNullValue(Ty); 5521 return false; 5522 case ValID::t_None: 5523 if (!Ty->isTokenTy()) 5524 return error(ID.Loc, "invalid type for none constant"); 5525 V = Constant::getNullValue(Ty); 5526 return false; 5527 case ValID::t_Constant: 5528 if (ID.ConstantVal->getType() != Ty) 5529 return error(ID.Loc, "constant expression type mismatch"); 5530 5531 V = ID.ConstantVal; 5532 return false; 5533 case ValID::t_ConstantStruct: 5534 case ValID::t_PackedConstantStruct: 5535 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5536 if (ST->getNumElements() != ID.UIntVal) 5537 return error(ID.Loc, 5538 "initializer with struct type has wrong # elements"); 5539 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5540 return error(ID.Loc, "packed'ness of initializer and type don't match"); 5541 5542 // Verify that the elements are compatible with the structtype. 5543 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5544 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5545 return error( 5546 ID.Loc, 5547 "element " + Twine(i) + 5548 " of struct initializer doesn't match struct element type"); 5549 5550 V = ConstantStruct::get( 5551 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5552 } else 5553 return error(ID.Loc, "constant expression type mismatch"); 5554 return false; 5555 } 5556 llvm_unreachable("Invalid ValID"); 5557 } 5558 5559 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5560 C = nullptr; 5561 ValID ID; 5562 auto Loc = Lex.getLoc(); 5563 if (parseValID(ID, /*PFS=*/nullptr)) 5564 return true; 5565 switch (ID.Kind) { 5566 case ValID::t_APSInt: 5567 case ValID::t_APFloat: 5568 case ValID::t_Undef: 5569 case ValID::t_Constant: 5570 case ValID::t_ConstantStruct: 5571 case ValID::t_PackedConstantStruct: { 5572 Value *V; 5573 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false)) 5574 return true; 5575 assert(isa<Constant>(V) && "Expected a constant value"); 5576 C = cast<Constant>(V); 5577 return false; 5578 } 5579 case ValID::t_Null: 5580 C = Constant::getNullValue(Ty); 5581 return false; 5582 default: 5583 return error(Loc, "expected a constant value"); 5584 } 5585 } 5586 5587 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5588 V = nullptr; 5589 ValID ID; 5590 return parseValID(ID, PFS) || 5591 convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false); 5592 } 5593 5594 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5595 Type *Ty = nullptr; 5596 return parseType(Ty) || parseValue(Ty, V, PFS); 5597 } 5598 5599 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5600 PerFunctionState &PFS) { 5601 Value *V; 5602 Loc = Lex.getLoc(); 5603 if (parseTypeAndValue(V, PFS)) 5604 return true; 5605 if (!isa<BasicBlock>(V)) 5606 return error(Loc, "expected a basic block"); 5607 BB = cast<BasicBlock>(V); 5608 return false; 5609 } 5610 5611 /// FunctionHeader 5612 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5613 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5614 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5615 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5616 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) { 5617 // parse the linkage. 5618 LocTy LinkageLoc = Lex.getLoc(); 5619 unsigned Linkage; 5620 unsigned Visibility; 5621 unsigned DLLStorageClass; 5622 bool DSOLocal; 5623 AttrBuilder RetAttrs; 5624 unsigned CC; 5625 bool HasLinkage; 5626 Type *RetType = nullptr; 5627 LocTy RetTypeLoc = Lex.getLoc(); 5628 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5629 DSOLocal) || 5630 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 5631 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 5632 return true; 5633 5634 // Verify that the linkage is ok. 5635 switch ((GlobalValue::LinkageTypes)Linkage) { 5636 case GlobalValue::ExternalLinkage: 5637 break; // always ok. 5638 case GlobalValue::ExternalWeakLinkage: 5639 if (IsDefine) 5640 return error(LinkageLoc, "invalid linkage for function definition"); 5641 break; 5642 case GlobalValue::PrivateLinkage: 5643 case GlobalValue::InternalLinkage: 5644 case GlobalValue::AvailableExternallyLinkage: 5645 case GlobalValue::LinkOnceAnyLinkage: 5646 case GlobalValue::LinkOnceODRLinkage: 5647 case GlobalValue::WeakAnyLinkage: 5648 case GlobalValue::WeakODRLinkage: 5649 if (!IsDefine) 5650 return error(LinkageLoc, "invalid linkage for function declaration"); 5651 break; 5652 case GlobalValue::AppendingLinkage: 5653 case GlobalValue::CommonLinkage: 5654 return error(LinkageLoc, "invalid function linkage type"); 5655 } 5656 5657 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5658 return error(LinkageLoc, 5659 "symbol with local linkage must have default visibility"); 5660 5661 if (!FunctionType::isValidReturnType(RetType)) 5662 return error(RetTypeLoc, "invalid function return type"); 5663 5664 LocTy NameLoc = Lex.getLoc(); 5665 5666 std::string FunctionName; 5667 if (Lex.getKind() == lltok::GlobalVar) { 5668 FunctionName = Lex.getStrVal(); 5669 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5670 unsigned NameID = Lex.getUIntVal(); 5671 5672 if (NameID != NumberedVals.size()) 5673 return tokError("function expected to be numbered '%" + 5674 Twine(NumberedVals.size()) + "'"); 5675 } else { 5676 return tokError("expected function name"); 5677 } 5678 5679 Lex.Lex(); 5680 5681 if (Lex.getKind() != lltok::lparen) 5682 return tokError("expected '(' in function argument list"); 5683 5684 SmallVector<ArgInfo, 8> ArgList; 5685 bool IsVarArg; 5686 AttrBuilder FuncAttrs; 5687 std::vector<unsigned> FwdRefAttrGrps; 5688 LocTy BuiltinLoc; 5689 std::string Section; 5690 std::string Partition; 5691 MaybeAlign Alignment; 5692 std::string GC; 5693 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5694 unsigned AddrSpace = 0; 5695 Constant *Prefix = nullptr; 5696 Constant *Prologue = nullptr; 5697 Constant *PersonalityFn = nullptr; 5698 Comdat *C; 5699 5700 if (parseArgumentList(ArgList, IsVarArg) || 5701 parseOptionalUnnamedAddr(UnnamedAddr) || 5702 parseOptionalProgramAddrSpace(AddrSpace) || 5703 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5704 BuiltinLoc) || 5705 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 5706 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 5707 parseOptionalComdat(FunctionName, C) || 5708 parseOptionalAlignment(Alignment) || 5709 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 5710 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 5711 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 5712 (EatIfPresent(lltok::kw_personality) && 5713 parseGlobalTypeAndValue(PersonalityFn))) 5714 return true; 5715 5716 if (FuncAttrs.contains(Attribute::Builtin)) 5717 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 5718 5719 // If the alignment was parsed as an attribute, move to the alignment field. 5720 if (FuncAttrs.hasAlignmentAttr()) { 5721 Alignment = FuncAttrs.getAlignment(); 5722 FuncAttrs.removeAttribute(Attribute::Alignment); 5723 } 5724 5725 // Okay, if we got here, the function is syntactically valid. Convert types 5726 // and do semantic checks. 5727 std::vector<Type*> ParamTypeList; 5728 SmallVector<AttributeSet, 8> Attrs; 5729 5730 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5731 ParamTypeList.push_back(ArgList[i].Ty); 5732 Attrs.push_back(ArgList[i].Attrs); 5733 } 5734 5735 AttributeList PAL = 5736 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5737 AttributeSet::get(Context, RetAttrs), Attrs); 5738 5739 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 5740 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 5741 5742 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 5743 PointerType *PFT = PointerType::get(FT, AddrSpace); 5744 5745 Fn = nullptr; 5746 if (!FunctionName.empty()) { 5747 // If this was a definition of a forward reference, remove the definition 5748 // from the forward reference table and fill in the forward ref. 5749 auto FRVI = ForwardRefVals.find(FunctionName); 5750 if (FRVI != ForwardRefVals.end()) { 5751 Fn = M->getFunction(FunctionName); 5752 if (!Fn) 5753 return error(FRVI->second.second, "invalid forward reference to " 5754 "function as global value!"); 5755 if (Fn->getType() != PFT) 5756 return error(FRVI->second.second, 5757 "invalid forward reference to " 5758 "function '" + 5759 FunctionName + 5760 "' with wrong type: " 5761 "expected '" + 5762 getTypeString(PFT) + "' but was '" + 5763 getTypeString(Fn->getType()) + "'"); 5764 ForwardRefVals.erase(FRVI); 5765 } else if ((Fn = M->getFunction(FunctionName))) { 5766 // Reject redefinitions. 5767 return error(NameLoc, 5768 "invalid redefinition of function '" + FunctionName + "'"); 5769 } else if (M->getNamedValue(FunctionName)) { 5770 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5771 } 5772 5773 } else { 5774 // If this is a definition of a forward referenced function, make sure the 5775 // types agree. 5776 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5777 if (I != ForwardRefValIDs.end()) { 5778 Fn = cast<Function>(I->second.first); 5779 if (Fn->getType() != PFT) 5780 return error(NameLoc, "type of definition and forward reference of '@" + 5781 Twine(NumberedVals.size()) + 5782 "' disagree: " 5783 "expected '" + 5784 getTypeString(PFT) + "' but was '" + 5785 getTypeString(Fn->getType()) + "'"); 5786 ForwardRefValIDs.erase(I); 5787 } 5788 } 5789 5790 if (!Fn) 5791 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5792 FunctionName, M); 5793 else // Move the forward-reference to the correct spot in the module. 5794 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 5795 5796 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5797 5798 if (FunctionName.empty()) 5799 NumberedVals.push_back(Fn); 5800 5801 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5802 maybeSetDSOLocal(DSOLocal, *Fn); 5803 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5804 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5805 Fn->setCallingConv(CC); 5806 Fn->setAttributes(PAL); 5807 Fn->setUnnamedAddr(UnnamedAddr); 5808 Fn->setAlignment(MaybeAlign(Alignment)); 5809 Fn->setSection(Section); 5810 Fn->setPartition(Partition); 5811 Fn->setComdat(C); 5812 Fn->setPersonalityFn(PersonalityFn); 5813 if (!GC.empty()) Fn->setGC(GC); 5814 Fn->setPrefixData(Prefix); 5815 Fn->setPrologueData(Prologue); 5816 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5817 5818 // Add all of the arguments we parsed to the function. 5819 Function::arg_iterator ArgIt = Fn->arg_begin(); 5820 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5821 // If the argument has a name, insert it into the argument symbol table. 5822 if (ArgList[i].Name.empty()) continue; 5823 5824 // Set the name, if it conflicted, it will be auto-renamed. 5825 ArgIt->setName(ArgList[i].Name); 5826 5827 if (ArgIt->getName() != ArgList[i].Name) 5828 return error(ArgList[i].Loc, 5829 "redefinition of argument '%" + ArgList[i].Name + "'"); 5830 } 5831 5832 if (IsDefine) 5833 return false; 5834 5835 // Check the declaration has no block address forward references. 5836 ValID ID; 5837 if (FunctionName.empty()) { 5838 ID.Kind = ValID::t_GlobalID; 5839 ID.UIntVal = NumberedVals.size() - 1; 5840 } else { 5841 ID.Kind = ValID::t_GlobalName; 5842 ID.StrVal = FunctionName; 5843 } 5844 auto Blocks = ForwardRefBlockAddresses.find(ID); 5845 if (Blocks != ForwardRefBlockAddresses.end()) 5846 return error(Blocks->first.Loc, 5847 "cannot take blockaddress inside a declaration"); 5848 return false; 5849 } 5850 5851 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5852 ValID ID; 5853 if (FunctionNumber == -1) { 5854 ID.Kind = ValID::t_GlobalName; 5855 ID.StrVal = std::string(F.getName()); 5856 } else { 5857 ID.Kind = ValID::t_GlobalID; 5858 ID.UIntVal = FunctionNumber; 5859 } 5860 5861 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5862 if (Blocks == P.ForwardRefBlockAddresses.end()) 5863 return false; 5864 5865 for (const auto &I : Blocks->second) { 5866 const ValID &BBID = I.first; 5867 GlobalValue *GV = I.second; 5868 5869 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5870 "Expected local id or name"); 5871 BasicBlock *BB; 5872 if (BBID.Kind == ValID::t_LocalName) 5873 BB = getBB(BBID.StrVal, BBID.Loc); 5874 else 5875 BB = getBB(BBID.UIntVal, BBID.Loc); 5876 if (!BB) 5877 return P.error(BBID.Loc, "referenced value is not a basic block"); 5878 5879 GV->replaceAllUsesWith(BlockAddress::get(&F, BB)); 5880 GV->eraseFromParent(); 5881 } 5882 5883 P.ForwardRefBlockAddresses.erase(Blocks); 5884 return false; 5885 } 5886 5887 /// parseFunctionBody 5888 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5889 bool LLParser::parseFunctionBody(Function &Fn) { 5890 if (Lex.getKind() != lltok::lbrace) 5891 return tokError("expected '{' in function body"); 5892 Lex.Lex(); // eat the {. 5893 5894 int FunctionNumber = -1; 5895 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5896 5897 PerFunctionState PFS(*this, Fn, FunctionNumber); 5898 5899 // Resolve block addresses and allow basic blocks to be forward-declared 5900 // within this function. 5901 if (PFS.resolveForwardRefBlockAddresses()) 5902 return true; 5903 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5904 5905 // We need at least one basic block. 5906 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5907 return tokError("function body requires at least one basic block"); 5908 5909 while (Lex.getKind() != lltok::rbrace && 5910 Lex.getKind() != lltok::kw_uselistorder) 5911 if (parseBasicBlock(PFS)) 5912 return true; 5913 5914 while (Lex.getKind() != lltok::rbrace) 5915 if (parseUseListOrder(&PFS)) 5916 return true; 5917 5918 // Eat the }. 5919 Lex.Lex(); 5920 5921 // Verify function is ok. 5922 return PFS.finishFunction(); 5923 } 5924 5925 /// parseBasicBlock 5926 /// ::= (LabelStr|LabelID)? Instruction* 5927 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 5928 // If this basic block starts out with a name, remember it. 5929 std::string Name; 5930 int NameID = -1; 5931 LocTy NameLoc = Lex.getLoc(); 5932 if (Lex.getKind() == lltok::LabelStr) { 5933 Name = Lex.getStrVal(); 5934 Lex.Lex(); 5935 } else if (Lex.getKind() == lltok::LabelID) { 5936 NameID = Lex.getUIntVal(); 5937 Lex.Lex(); 5938 } 5939 5940 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 5941 if (!BB) 5942 return true; 5943 5944 std::string NameStr; 5945 5946 // parse the instructions in this block until we get a terminator. 5947 Instruction *Inst; 5948 do { 5949 // This instruction may have three possibilities for a name: a) none 5950 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5951 LocTy NameLoc = Lex.getLoc(); 5952 int NameID = -1; 5953 NameStr = ""; 5954 5955 if (Lex.getKind() == lltok::LocalVarID) { 5956 NameID = Lex.getUIntVal(); 5957 Lex.Lex(); 5958 if (parseToken(lltok::equal, "expected '=' after instruction id")) 5959 return true; 5960 } else if (Lex.getKind() == lltok::LocalVar) { 5961 NameStr = Lex.getStrVal(); 5962 Lex.Lex(); 5963 if (parseToken(lltok::equal, "expected '=' after instruction name")) 5964 return true; 5965 } 5966 5967 switch (parseInstruction(Inst, BB, PFS)) { 5968 default: 5969 llvm_unreachable("Unknown parseInstruction result!"); 5970 case InstError: return true; 5971 case InstNormal: 5972 BB->getInstList().push_back(Inst); 5973 5974 // With a normal result, we check to see if the instruction is followed by 5975 // a comma and metadata. 5976 if (EatIfPresent(lltok::comma)) 5977 if (parseInstructionMetadata(*Inst)) 5978 return true; 5979 break; 5980 case InstExtraComma: 5981 BB->getInstList().push_back(Inst); 5982 5983 // If the instruction parser ate an extra comma at the end of it, it 5984 // *must* be followed by metadata. 5985 if (parseInstructionMetadata(*Inst)) 5986 return true; 5987 break; 5988 } 5989 5990 // Set the name on the instruction. 5991 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 5992 return true; 5993 } while (!Inst->isTerminator()); 5994 5995 return false; 5996 } 5997 5998 //===----------------------------------------------------------------------===// 5999 // Instruction Parsing. 6000 //===----------------------------------------------------------------------===// 6001 6002 /// parseInstruction - parse one of the many different instructions. 6003 /// 6004 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 6005 PerFunctionState &PFS) { 6006 lltok::Kind Token = Lex.getKind(); 6007 if (Token == lltok::Eof) 6008 return tokError("found end of file when expecting more instructions"); 6009 LocTy Loc = Lex.getLoc(); 6010 unsigned KeywordVal = Lex.getUIntVal(); 6011 Lex.Lex(); // Eat the keyword. 6012 6013 switch (Token) { 6014 default: 6015 return error(Loc, "expected instruction opcode"); 6016 // Terminator Instructions. 6017 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 6018 case lltok::kw_ret: 6019 return parseRet(Inst, BB, PFS); 6020 case lltok::kw_br: 6021 return parseBr(Inst, PFS); 6022 case lltok::kw_switch: 6023 return parseSwitch(Inst, PFS); 6024 case lltok::kw_indirectbr: 6025 return parseIndirectBr(Inst, PFS); 6026 case lltok::kw_invoke: 6027 return parseInvoke(Inst, PFS); 6028 case lltok::kw_resume: 6029 return parseResume(Inst, PFS); 6030 case lltok::kw_cleanupret: 6031 return parseCleanupRet(Inst, PFS); 6032 case lltok::kw_catchret: 6033 return parseCatchRet(Inst, PFS); 6034 case lltok::kw_catchswitch: 6035 return parseCatchSwitch(Inst, PFS); 6036 case lltok::kw_catchpad: 6037 return parseCatchPad(Inst, PFS); 6038 case lltok::kw_cleanuppad: 6039 return parseCleanupPad(Inst, PFS); 6040 case lltok::kw_callbr: 6041 return parseCallBr(Inst, PFS); 6042 // Unary Operators. 6043 case lltok::kw_fneg: { 6044 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6045 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 6046 if (Res != 0) 6047 return Res; 6048 if (FMF.any()) 6049 Inst->setFastMathFlags(FMF); 6050 return false; 6051 } 6052 // Binary Operators. 6053 case lltok::kw_add: 6054 case lltok::kw_sub: 6055 case lltok::kw_mul: 6056 case lltok::kw_shl: { 6057 bool NUW = EatIfPresent(lltok::kw_nuw); 6058 bool NSW = EatIfPresent(lltok::kw_nsw); 6059 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 6060 6061 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6062 return true; 6063 6064 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 6065 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 6066 return false; 6067 } 6068 case lltok::kw_fadd: 6069 case lltok::kw_fsub: 6070 case lltok::kw_fmul: 6071 case lltok::kw_fdiv: 6072 case lltok::kw_frem: { 6073 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6074 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 6075 if (Res != 0) 6076 return Res; 6077 if (FMF.any()) 6078 Inst->setFastMathFlags(FMF); 6079 return 0; 6080 } 6081 6082 case lltok::kw_sdiv: 6083 case lltok::kw_udiv: 6084 case lltok::kw_lshr: 6085 case lltok::kw_ashr: { 6086 bool Exact = EatIfPresent(lltok::kw_exact); 6087 6088 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6089 return true; 6090 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 6091 return false; 6092 } 6093 6094 case lltok::kw_urem: 6095 case lltok::kw_srem: 6096 return parseArithmetic(Inst, PFS, KeywordVal, 6097 /*IsFP*/ false); 6098 case lltok::kw_and: 6099 case lltok::kw_or: 6100 case lltok::kw_xor: 6101 return parseLogical(Inst, PFS, KeywordVal); 6102 case lltok::kw_icmp: 6103 return parseCompare(Inst, PFS, KeywordVal); 6104 case lltok::kw_fcmp: { 6105 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6106 int Res = parseCompare(Inst, PFS, KeywordVal); 6107 if (Res != 0) 6108 return Res; 6109 if (FMF.any()) 6110 Inst->setFastMathFlags(FMF); 6111 return 0; 6112 } 6113 6114 // Casts. 6115 case lltok::kw_trunc: 6116 case lltok::kw_zext: 6117 case lltok::kw_sext: 6118 case lltok::kw_fptrunc: 6119 case lltok::kw_fpext: 6120 case lltok::kw_bitcast: 6121 case lltok::kw_addrspacecast: 6122 case lltok::kw_uitofp: 6123 case lltok::kw_sitofp: 6124 case lltok::kw_fptoui: 6125 case lltok::kw_fptosi: 6126 case lltok::kw_inttoptr: 6127 case lltok::kw_ptrtoint: 6128 return parseCast(Inst, PFS, KeywordVal); 6129 // Other. 6130 case lltok::kw_select: { 6131 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6132 int Res = parseSelect(Inst, PFS); 6133 if (Res != 0) 6134 return Res; 6135 if (FMF.any()) { 6136 if (!isa<FPMathOperator>(Inst)) 6137 return error(Loc, "fast-math-flags specified for select without " 6138 "floating-point scalar or vector return type"); 6139 Inst->setFastMathFlags(FMF); 6140 } 6141 return 0; 6142 } 6143 case lltok::kw_va_arg: 6144 return parseVAArg(Inst, PFS); 6145 case lltok::kw_extractelement: 6146 return parseExtractElement(Inst, PFS); 6147 case lltok::kw_insertelement: 6148 return parseInsertElement(Inst, PFS); 6149 case lltok::kw_shufflevector: 6150 return parseShuffleVector(Inst, PFS); 6151 case lltok::kw_phi: { 6152 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6153 int Res = parsePHI(Inst, PFS); 6154 if (Res != 0) 6155 return Res; 6156 if (FMF.any()) { 6157 if (!isa<FPMathOperator>(Inst)) 6158 return error(Loc, "fast-math-flags specified for phi without " 6159 "floating-point scalar or vector return type"); 6160 Inst->setFastMathFlags(FMF); 6161 } 6162 return 0; 6163 } 6164 case lltok::kw_landingpad: 6165 return parseLandingPad(Inst, PFS); 6166 case lltok::kw_freeze: 6167 return parseFreeze(Inst, PFS); 6168 // Call. 6169 case lltok::kw_call: 6170 return parseCall(Inst, PFS, CallInst::TCK_None); 6171 case lltok::kw_tail: 6172 return parseCall(Inst, PFS, CallInst::TCK_Tail); 6173 case lltok::kw_musttail: 6174 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 6175 case lltok::kw_notail: 6176 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 6177 // Memory. 6178 case lltok::kw_alloca: 6179 return parseAlloc(Inst, PFS); 6180 case lltok::kw_load: 6181 return parseLoad(Inst, PFS); 6182 case lltok::kw_store: 6183 return parseStore(Inst, PFS); 6184 case lltok::kw_cmpxchg: 6185 return parseCmpXchg(Inst, PFS); 6186 case lltok::kw_atomicrmw: 6187 return parseAtomicRMW(Inst, PFS); 6188 case lltok::kw_fence: 6189 return parseFence(Inst, PFS); 6190 case lltok::kw_getelementptr: 6191 return parseGetElementPtr(Inst, PFS); 6192 case lltok::kw_extractvalue: 6193 return parseExtractValue(Inst, PFS); 6194 case lltok::kw_insertvalue: 6195 return parseInsertValue(Inst, PFS); 6196 } 6197 } 6198 6199 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 6200 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 6201 if (Opc == Instruction::FCmp) { 6202 switch (Lex.getKind()) { 6203 default: 6204 return tokError("expected fcmp predicate (e.g. 'oeq')"); 6205 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 6206 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 6207 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 6208 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 6209 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 6210 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 6211 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 6212 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 6213 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 6214 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 6215 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 6216 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 6217 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 6218 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 6219 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 6220 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 6221 } 6222 } else { 6223 switch (Lex.getKind()) { 6224 default: 6225 return tokError("expected icmp predicate (e.g. 'eq')"); 6226 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 6227 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 6228 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 6229 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 6230 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 6231 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 6232 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 6233 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 6234 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 6235 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 6236 } 6237 } 6238 Lex.Lex(); 6239 return false; 6240 } 6241 6242 //===----------------------------------------------------------------------===// 6243 // Terminator Instructions. 6244 //===----------------------------------------------------------------------===// 6245 6246 /// parseRet - parse a return instruction. 6247 /// ::= 'ret' void (',' !dbg, !1)* 6248 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 6249 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 6250 PerFunctionState &PFS) { 6251 SMLoc TypeLoc = Lex.getLoc(); 6252 Type *Ty = nullptr; 6253 if (parseType(Ty, true /*void allowed*/)) 6254 return true; 6255 6256 Type *ResType = PFS.getFunction().getReturnType(); 6257 6258 if (Ty->isVoidTy()) { 6259 if (!ResType->isVoidTy()) 6260 return error(TypeLoc, "value doesn't match function result type '" + 6261 getTypeString(ResType) + "'"); 6262 6263 Inst = ReturnInst::Create(Context); 6264 return false; 6265 } 6266 6267 Value *RV; 6268 if (parseValue(Ty, RV, PFS)) 6269 return true; 6270 6271 if (ResType != RV->getType()) 6272 return error(TypeLoc, "value doesn't match function result type '" + 6273 getTypeString(ResType) + "'"); 6274 6275 Inst = ReturnInst::Create(Context, RV); 6276 return false; 6277 } 6278 6279 /// parseBr 6280 /// ::= 'br' TypeAndValue 6281 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6282 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 6283 LocTy Loc, Loc2; 6284 Value *Op0; 6285 BasicBlock *Op1, *Op2; 6286 if (parseTypeAndValue(Op0, Loc, PFS)) 6287 return true; 6288 6289 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6290 Inst = BranchInst::Create(BB); 6291 return false; 6292 } 6293 6294 if (Op0->getType() != Type::getInt1Ty(Context)) 6295 return error(Loc, "branch condition must have 'i1' type"); 6296 6297 if (parseToken(lltok::comma, "expected ',' after branch condition") || 6298 parseTypeAndBasicBlock(Op1, Loc, PFS) || 6299 parseToken(lltok::comma, "expected ',' after true destination") || 6300 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 6301 return true; 6302 6303 Inst = BranchInst::Create(Op1, Op2, Op0); 6304 return false; 6305 } 6306 6307 /// parseSwitch 6308 /// Instruction 6309 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6310 /// JumpTable 6311 /// ::= (TypeAndValue ',' TypeAndValue)* 6312 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6313 LocTy CondLoc, BBLoc; 6314 Value *Cond; 6315 BasicBlock *DefaultBB; 6316 if (parseTypeAndValue(Cond, CondLoc, PFS) || 6317 parseToken(lltok::comma, "expected ',' after switch condition") || 6318 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6319 parseToken(lltok::lsquare, "expected '[' with switch table")) 6320 return true; 6321 6322 if (!Cond->getType()->isIntegerTy()) 6323 return error(CondLoc, "switch condition must have integer type"); 6324 6325 // parse the jump table pairs. 6326 SmallPtrSet<Value*, 32> SeenCases; 6327 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6328 while (Lex.getKind() != lltok::rsquare) { 6329 Value *Constant; 6330 BasicBlock *DestBB; 6331 6332 if (parseTypeAndValue(Constant, CondLoc, PFS) || 6333 parseToken(lltok::comma, "expected ',' after case value") || 6334 parseTypeAndBasicBlock(DestBB, PFS)) 6335 return true; 6336 6337 if (!SeenCases.insert(Constant).second) 6338 return error(CondLoc, "duplicate case value in switch"); 6339 if (!isa<ConstantInt>(Constant)) 6340 return error(CondLoc, "case value is not a constant integer"); 6341 6342 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6343 } 6344 6345 Lex.Lex(); // Eat the ']'. 6346 6347 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6348 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6349 SI->addCase(Table[i].first, Table[i].second); 6350 Inst = SI; 6351 return false; 6352 } 6353 6354 /// parseIndirectBr 6355 /// Instruction 6356 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6357 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6358 LocTy AddrLoc; 6359 Value *Address; 6360 if (parseTypeAndValue(Address, AddrLoc, PFS) || 6361 parseToken(lltok::comma, "expected ',' after indirectbr address") || 6362 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 6363 return true; 6364 6365 if (!Address->getType()->isPointerTy()) 6366 return error(AddrLoc, "indirectbr address must have pointer type"); 6367 6368 // parse the destination list. 6369 SmallVector<BasicBlock*, 16> DestList; 6370 6371 if (Lex.getKind() != lltok::rsquare) { 6372 BasicBlock *DestBB; 6373 if (parseTypeAndBasicBlock(DestBB, PFS)) 6374 return true; 6375 DestList.push_back(DestBB); 6376 6377 while (EatIfPresent(lltok::comma)) { 6378 if (parseTypeAndBasicBlock(DestBB, PFS)) 6379 return true; 6380 DestList.push_back(DestBB); 6381 } 6382 } 6383 6384 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6385 return true; 6386 6387 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6388 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6389 IBI->addDestination(DestList[i]); 6390 Inst = IBI; 6391 return false; 6392 } 6393 6394 /// parseInvoke 6395 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6396 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6397 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6398 LocTy CallLoc = Lex.getLoc(); 6399 AttrBuilder RetAttrs, FnAttrs; 6400 std::vector<unsigned> FwdRefAttrGrps; 6401 LocTy NoBuiltinLoc; 6402 unsigned CC; 6403 unsigned InvokeAddrSpace; 6404 Type *RetType = nullptr; 6405 LocTy RetTypeLoc; 6406 ValID CalleeID; 6407 SmallVector<ParamInfo, 16> ArgList; 6408 SmallVector<OperandBundleDef, 2> BundleList; 6409 6410 BasicBlock *NormalBB, *UnwindBB; 6411 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6412 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 6413 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6414 parseValID(CalleeID) || parseParameterList(ArgList, PFS) || 6415 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6416 NoBuiltinLoc) || 6417 parseOptionalOperandBundles(BundleList, PFS) || 6418 parseToken(lltok::kw_to, "expected 'to' in invoke") || 6419 parseTypeAndBasicBlock(NormalBB, PFS) || 6420 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6421 parseTypeAndBasicBlock(UnwindBB, PFS)) 6422 return true; 6423 6424 // If RetType is a non-function pointer type, then this is the short syntax 6425 // for the call, which means that RetType is just the return type. Infer the 6426 // rest of the function argument types from the arguments that are present. 6427 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6428 if (!Ty) { 6429 // Pull out the types of all of the arguments... 6430 std::vector<Type*> ParamTypes; 6431 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6432 ParamTypes.push_back(ArgList[i].V->getType()); 6433 6434 if (!FunctionType::isValidReturnType(RetType)) 6435 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6436 6437 Ty = FunctionType::get(RetType, ParamTypes, false); 6438 } 6439 6440 CalleeID.FTy = Ty; 6441 6442 // Look up the callee. 6443 Value *Callee; 6444 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6445 Callee, &PFS, /*IsCall=*/true)) 6446 return true; 6447 6448 // Set up the Attribute for the function. 6449 SmallVector<Value *, 8> Args; 6450 SmallVector<AttributeSet, 8> ArgAttrs; 6451 6452 // Loop through FunctionType's arguments and ensure they are specified 6453 // correctly. Also, gather any parameter attributes. 6454 FunctionType::param_iterator I = Ty->param_begin(); 6455 FunctionType::param_iterator E = Ty->param_end(); 6456 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6457 Type *ExpectedTy = nullptr; 6458 if (I != E) { 6459 ExpectedTy = *I++; 6460 } else if (!Ty->isVarArg()) { 6461 return error(ArgList[i].Loc, "too many arguments specified"); 6462 } 6463 6464 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6465 return error(ArgList[i].Loc, "argument is not of expected type '" + 6466 getTypeString(ExpectedTy) + "'"); 6467 Args.push_back(ArgList[i].V); 6468 ArgAttrs.push_back(ArgList[i].Attrs); 6469 } 6470 6471 if (I != E) 6472 return error(CallLoc, "not enough parameters specified for call"); 6473 6474 if (FnAttrs.hasAlignmentAttr()) 6475 return error(CallLoc, "invoke instructions may not have an alignment"); 6476 6477 // Finish off the Attribute and check them 6478 AttributeList PAL = 6479 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6480 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6481 6482 InvokeInst *II = 6483 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6484 II->setCallingConv(CC); 6485 II->setAttributes(PAL); 6486 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6487 Inst = II; 6488 return false; 6489 } 6490 6491 /// parseResume 6492 /// ::= 'resume' TypeAndValue 6493 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 6494 Value *Exn; LocTy ExnLoc; 6495 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 6496 return true; 6497 6498 ResumeInst *RI = ResumeInst::Create(Exn); 6499 Inst = RI; 6500 return false; 6501 } 6502 6503 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 6504 PerFunctionState &PFS) { 6505 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6506 return true; 6507 6508 while (Lex.getKind() != lltok::rsquare) { 6509 // If this isn't the first argument, we need a comma. 6510 if (!Args.empty() && 6511 parseToken(lltok::comma, "expected ',' in argument list")) 6512 return true; 6513 6514 // parse the argument. 6515 LocTy ArgLoc; 6516 Type *ArgTy = nullptr; 6517 if (parseType(ArgTy, ArgLoc)) 6518 return true; 6519 6520 Value *V; 6521 if (ArgTy->isMetadataTy()) { 6522 if (parseMetadataAsValue(V, PFS)) 6523 return true; 6524 } else { 6525 if (parseValue(ArgTy, V, PFS)) 6526 return true; 6527 } 6528 Args.push_back(V); 6529 } 6530 6531 Lex.Lex(); // Lex the ']'. 6532 return false; 6533 } 6534 6535 /// parseCleanupRet 6536 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6537 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6538 Value *CleanupPad = nullptr; 6539 6540 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6541 return true; 6542 6543 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6544 return true; 6545 6546 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6547 return true; 6548 6549 BasicBlock *UnwindBB = nullptr; 6550 if (Lex.getKind() == lltok::kw_to) { 6551 Lex.Lex(); 6552 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6553 return true; 6554 } else { 6555 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 6556 return true; 6557 } 6558 } 6559 6560 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6561 return false; 6562 } 6563 6564 /// parseCatchRet 6565 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6566 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6567 Value *CatchPad = nullptr; 6568 6569 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 6570 return true; 6571 6572 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6573 return true; 6574 6575 BasicBlock *BB; 6576 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 6577 parseTypeAndBasicBlock(BB, PFS)) 6578 return true; 6579 6580 Inst = CatchReturnInst::Create(CatchPad, BB); 6581 return false; 6582 } 6583 6584 /// parseCatchSwitch 6585 /// ::= 'catchswitch' within Parent 6586 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6587 Value *ParentPad; 6588 6589 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6590 return true; 6591 6592 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6593 Lex.getKind() != lltok::LocalVarID) 6594 return tokError("expected scope value for catchswitch"); 6595 6596 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6597 return true; 6598 6599 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6600 return true; 6601 6602 SmallVector<BasicBlock *, 32> Table; 6603 do { 6604 BasicBlock *DestBB; 6605 if (parseTypeAndBasicBlock(DestBB, PFS)) 6606 return true; 6607 Table.push_back(DestBB); 6608 } while (EatIfPresent(lltok::comma)); 6609 6610 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6611 return true; 6612 6613 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 6614 return true; 6615 6616 BasicBlock *UnwindBB = nullptr; 6617 if (EatIfPresent(lltok::kw_to)) { 6618 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6619 return true; 6620 } else { 6621 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 6622 return true; 6623 } 6624 6625 auto *CatchSwitch = 6626 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6627 for (BasicBlock *DestBB : Table) 6628 CatchSwitch->addHandler(DestBB); 6629 Inst = CatchSwitch; 6630 return false; 6631 } 6632 6633 /// parseCatchPad 6634 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6635 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6636 Value *CatchSwitch = nullptr; 6637 6638 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 6639 return true; 6640 6641 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6642 return tokError("expected scope value for catchpad"); 6643 6644 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6645 return true; 6646 6647 SmallVector<Value *, 8> Args; 6648 if (parseExceptionArgs(Args, PFS)) 6649 return true; 6650 6651 Inst = CatchPadInst::Create(CatchSwitch, Args); 6652 return false; 6653 } 6654 6655 /// parseCleanupPad 6656 /// ::= 'cleanuppad' within Parent ParamList 6657 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6658 Value *ParentPad = nullptr; 6659 6660 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6661 return true; 6662 6663 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6664 Lex.getKind() != lltok::LocalVarID) 6665 return tokError("expected scope value for cleanuppad"); 6666 6667 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6668 return true; 6669 6670 SmallVector<Value *, 8> Args; 6671 if (parseExceptionArgs(Args, PFS)) 6672 return true; 6673 6674 Inst = CleanupPadInst::Create(ParentPad, Args); 6675 return false; 6676 } 6677 6678 //===----------------------------------------------------------------------===// 6679 // Unary Operators. 6680 //===----------------------------------------------------------------------===// 6681 6682 /// parseUnaryOp 6683 /// ::= UnaryOp TypeAndValue ',' Value 6684 /// 6685 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6686 /// operand is allowed. 6687 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6688 unsigned Opc, bool IsFP) { 6689 LocTy Loc; Value *LHS; 6690 if (parseTypeAndValue(LHS, Loc, PFS)) 6691 return true; 6692 6693 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6694 : LHS->getType()->isIntOrIntVectorTy(); 6695 6696 if (!Valid) 6697 return error(Loc, "invalid operand type for instruction"); 6698 6699 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6700 return false; 6701 } 6702 6703 /// parseCallBr 6704 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6705 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6706 /// '[' LabelList ']' 6707 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6708 LocTy CallLoc = Lex.getLoc(); 6709 AttrBuilder RetAttrs, FnAttrs; 6710 std::vector<unsigned> FwdRefAttrGrps; 6711 LocTy NoBuiltinLoc; 6712 unsigned CC; 6713 Type *RetType = nullptr; 6714 LocTy RetTypeLoc; 6715 ValID CalleeID; 6716 SmallVector<ParamInfo, 16> ArgList; 6717 SmallVector<OperandBundleDef, 2> BundleList; 6718 6719 BasicBlock *DefaultDest; 6720 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6721 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6722 parseValID(CalleeID) || parseParameterList(ArgList, PFS) || 6723 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6724 NoBuiltinLoc) || 6725 parseOptionalOperandBundles(BundleList, PFS) || 6726 parseToken(lltok::kw_to, "expected 'to' in callbr") || 6727 parseTypeAndBasicBlock(DefaultDest, PFS) || 6728 parseToken(lltok::lsquare, "expected '[' in callbr")) 6729 return true; 6730 6731 // parse the destination list. 6732 SmallVector<BasicBlock *, 16> IndirectDests; 6733 6734 if (Lex.getKind() != lltok::rsquare) { 6735 BasicBlock *DestBB; 6736 if (parseTypeAndBasicBlock(DestBB, PFS)) 6737 return true; 6738 IndirectDests.push_back(DestBB); 6739 6740 while (EatIfPresent(lltok::comma)) { 6741 if (parseTypeAndBasicBlock(DestBB, PFS)) 6742 return true; 6743 IndirectDests.push_back(DestBB); 6744 } 6745 } 6746 6747 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6748 return true; 6749 6750 // If RetType is a non-function pointer type, then this is the short syntax 6751 // for the call, which means that RetType is just the return type. Infer the 6752 // rest of the function argument types from the arguments that are present. 6753 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6754 if (!Ty) { 6755 // Pull out the types of all of the arguments... 6756 std::vector<Type *> ParamTypes; 6757 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6758 ParamTypes.push_back(ArgList[i].V->getType()); 6759 6760 if (!FunctionType::isValidReturnType(RetType)) 6761 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6762 6763 Ty = FunctionType::get(RetType, ParamTypes, false); 6764 } 6765 6766 CalleeID.FTy = Ty; 6767 6768 // Look up the callee. 6769 Value *Callee; 6770 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS, 6771 /*IsCall=*/true)) 6772 return true; 6773 6774 // Set up the Attribute for the function. 6775 SmallVector<Value *, 8> Args; 6776 SmallVector<AttributeSet, 8> ArgAttrs; 6777 6778 // Loop through FunctionType's arguments and ensure they are specified 6779 // correctly. Also, gather any parameter attributes. 6780 FunctionType::param_iterator I = Ty->param_begin(); 6781 FunctionType::param_iterator E = Ty->param_end(); 6782 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6783 Type *ExpectedTy = nullptr; 6784 if (I != E) { 6785 ExpectedTy = *I++; 6786 } else if (!Ty->isVarArg()) { 6787 return error(ArgList[i].Loc, "too many arguments specified"); 6788 } 6789 6790 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6791 return error(ArgList[i].Loc, "argument is not of expected type '" + 6792 getTypeString(ExpectedTy) + "'"); 6793 Args.push_back(ArgList[i].V); 6794 ArgAttrs.push_back(ArgList[i].Attrs); 6795 } 6796 6797 if (I != E) 6798 return error(CallLoc, "not enough parameters specified for call"); 6799 6800 if (FnAttrs.hasAlignmentAttr()) 6801 return error(CallLoc, "callbr instructions may not have an alignment"); 6802 6803 // Finish off the Attribute and check them 6804 AttributeList PAL = 6805 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6806 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6807 6808 CallBrInst *CBI = 6809 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6810 BundleList); 6811 CBI->setCallingConv(CC); 6812 CBI->setAttributes(PAL); 6813 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6814 Inst = CBI; 6815 return false; 6816 } 6817 6818 //===----------------------------------------------------------------------===// 6819 // Binary Operators. 6820 //===----------------------------------------------------------------------===// 6821 6822 /// parseArithmetic 6823 /// ::= ArithmeticOps TypeAndValue ',' Value 6824 /// 6825 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6826 /// operand is allowed. 6827 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6828 unsigned Opc, bool IsFP) { 6829 LocTy Loc; Value *LHS, *RHS; 6830 if (parseTypeAndValue(LHS, Loc, PFS) || 6831 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 6832 parseValue(LHS->getType(), RHS, PFS)) 6833 return true; 6834 6835 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6836 : LHS->getType()->isIntOrIntVectorTy(); 6837 6838 if (!Valid) 6839 return error(Loc, "invalid operand type for instruction"); 6840 6841 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6842 return false; 6843 } 6844 6845 /// parseLogical 6846 /// ::= ArithmeticOps TypeAndValue ',' Value { 6847 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 6848 unsigned Opc) { 6849 LocTy Loc; Value *LHS, *RHS; 6850 if (parseTypeAndValue(LHS, Loc, PFS) || 6851 parseToken(lltok::comma, "expected ',' in logical operation") || 6852 parseValue(LHS->getType(), RHS, PFS)) 6853 return true; 6854 6855 if (!LHS->getType()->isIntOrIntVectorTy()) 6856 return error(Loc, 6857 "instruction requires integer or integer vector operands"); 6858 6859 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6860 return false; 6861 } 6862 6863 /// parseCompare 6864 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6865 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6866 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 6867 unsigned Opc) { 6868 // parse the integer/fp comparison predicate. 6869 LocTy Loc; 6870 unsigned Pred; 6871 Value *LHS, *RHS; 6872 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 6873 parseToken(lltok::comma, "expected ',' after compare value") || 6874 parseValue(LHS->getType(), RHS, PFS)) 6875 return true; 6876 6877 if (Opc == Instruction::FCmp) { 6878 if (!LHS->getType()->isFPOrFPVectorTy()) 6879 return error(Loc, "fcmp requires floating point operands"); 6880 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6881 } else { 6882 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6883 if (!LHS->getType()->isIntOrIntVectorTy() && 6884 !LHS->getType()->isPtrOrPtrVectorTy()) 6885 return error(Loc, "icmp requires integer operands"); 6886 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6887 } 6888 return false; 6889 } 6890 6891 //===----------------------------------------------------------------------===// 6892 // Other Instructions. 6893 //===----------------------------------------------------------------------===// 6894 6895 /// parseCast 6896 /// ::= CastOpc TypeAndValue 'to' Type 6897 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 6898 unsigned Opc) { 6899 LocTy Loc; 6900 Value *Op; 6901 Type *DestTy = nullptr; 6902 if (parseTypeAndValue(Op, Loc, PFS) || 6903 parseToken(lltok::kw_to, "expected 'to' after cast value") || 6904 parseType(DestTy)) 6905 return true; 6906 6907 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6908 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6909 return error(Loc, "invalid cast opcode for cast from '" + 6910 getTypeString(Op->getType()) + "' to '" + 6911 getTypeString(DestTy) + "'"); 6912 } 6913 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6914 return false; 6915 } 6916 6917 /// parseSelect 6918 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6919 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6920 LocTy Loc; 6921 Value *Op0, *Op1, *Op2; 6922 if (parseTypeAndValue(Op0, Loc, PFS) || 6923 parseToken(lltok::comma, "expected ',' after select condition") || 6924 parseTypeAndValue(Op1, PFS) || 6925 parseToken(lltok::comma, "expected ',' after select value") || 6926 parseTypeAndValue(Op2, PFS)) 6927 return true; 6928 6929 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6930 return error(Loc, Reason); 6931 6932 Inst = SelectInst::Create(Op0, Op1, Op2); 6933 return false; 6934 } 6935 6936 /// parseVAArg 6937 /// ::= 'va_arg' TypeAndValue ',' Type 6938 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 6939 Value *Op; 6940 Type *EltTy = nullptr; 6941 LocTy TypeLoc; 6942 if (parseTypeAndValue(Op, PFS) || 6943 parseToken(lltok::comma, "expected ',' after vaarg operand") || 6944 parseType(EltTy, TypeLoc)) 6945 return true; 6946 6947 if (!EltTy->isFirstClassType()) 6948 return error(TypeLoc, "va_arg requires operand with first class type"); 6949 6950 Inst = new VAArgInst(Op, EltTy); 6951 return false; 6952 } 6953 6954 /// parseExtractElement 6955 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6956 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6957 LocTy Loc; 6958 Value *Op0, *Op1; 6959 if (parseTypeAndValue(Op0, Loc, PFS) || 6960 parseToken(lltok::comma, "expected ',' after extract value") || 6961 parseTypeAndValue(Op1, PFS)) 6962 return true; 6963 6964 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6965 return error(Loc, "invalid extractelement operands"); 6966 6967 Inst = ExtractElementInst::Create(Op0, Op1); 6968 return false; 6969 } 6970 6971 /// parseInsertElement 6972 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6973 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6974 LocTy Loc; 6975 Value *Op0, *Op1, *Op2; 6976 if (parseTypeAndValue(Op0, Loc, PFS) || 6977 parseToken(lltok::comma, "expected ',' after insertelement value") || 6978 parseTypeAndValue(Op1, PFS) || 6979 parseToken(lltok::comma, "expected ',' after insertelement value") || 6980 parseTypeAndValue(Op2, PFS)) 6981 return true; 6982 6983 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6984 return error(Loc, "invalid insertelement operands"); 6985 6986 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6987 return false; 6988 } 6989 6990 /// parseShuffleVector 6991 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6992 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6993 LocTy Loc; 6994 Value *Op0, *Op1, *Op2; 6995 if (parseTypeAndValue(Op0, Loc, PFS) || 6996 parseToken(lltok::comma, "expected ',' after shuffle mask") || 6997 parseTypeAndValue(Op1, PFS) || 6998 parseToken(lltok::comma, "expected ',' after shuffle value") || 6999 parseTypeAndValue(Op2, PFS)) 7000 return true; 7001 7002 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 7003 return error(Loc, "invalid shufflevector operands"); 7004 7005 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 7006 return false; 7007 } 7008 7009 /// parsePHI 7010 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 7011 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 7012 Type *Ty = nullptr; LocTy TypeLoc; 7013 Value *Op0, *Op1; 7014 7015 if (parseType(Ty, TypeLoc) || 7016 parseToken(lltok::lsquare, "expected '[' in phi value list") || 7017 parseValue(Ty, Op0, PFS) || 7018 parseToken(lltok::comma, "expected ',' after insertelement value") || 7019 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7020 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7021 return true; 7022 7023 bool AteExtraComma = false; 7024 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 7025 7026 while (true) { 7027 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 7028 7029 if (!EatIfPresent(lltok::comma)) 7030 break; 7031 7032 if (Lex.getKind() == lltok::MetadataVar) { 7033 AteExtraComma = true; 7034 break; 7035 } 7036 7037 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 7038 parseValue(Ty, Op0, PFS) || 7039 parseToken(lltok::comma, "expected ',' after insertelement value") || 7040 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7041 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7042 return true; 7043 } 7044 7045 if (!Ty->isFirstClassType()) 7046 return error(TypeLoc, "phi node must have first class type"); 7047 7048 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 7049 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 7050 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 7051 Inst = PN; 7052 return AteExtraComma ? InstExtraComma : InstNormal; 7053 } 7054 7055 /// parseLandingPad 7056 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 7057 /// Clause 7058 /// ::= 'catch' TypeAndValue 7059 /// ::= 'filter' 7060 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 7061 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 7062 Type *Ty = nullptr; LocTy TyLoc; 7063 7064 if (parseType(Ty, TyLoc)) 7065 return true; 7066 7067 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 7068 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 7069 7070 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 7071 LandingPadInst::ClauseType CT; 7072 if (EatIfPresent(lltok::kw_catch)) 7073 CT = LandingPadInst::Catch; 7074 else if (EatIfPresent(lltok::kw_filter)) 7075 CT = LandingPadInst::Filter; 7076 else 7077 return tokError("expected 'catch' or 'filter' clause type"); 7078 7079 Value *V; 7080 LocTy VLoc; 7081 if (parseTypeAndValue(V, VLoc, PFS)) 7082 return true; 7083 7084 // A 'catch' type expects a non-array constant. A filter clause expects an 7085 // array constant. 7086 if (CT == LandingPadInst::Catch) { 7087 if (isa<ArrayType>(V->getType())) 7088 error(VLoc, "'catch' clause has an invalid type"); 7089 } else { 7090 if (!isa<ArrayType>(V->getType())) 7091 error(VLoc, "'filter' clause has an invalid type"); 7092 } 7093 7094 Constant *CV = dyn_cast<Constant>(V); 7095 if (!CV) 7096 return error(VLoc, "clause argument must be a constant"); 7097 LP->addClause(CV); 7098 } 7099 7100 Inst = LP.release(); 7101 return false; 7102 } 7103 7104 /// parseFreeze 7105 /// ::= 'freeze' Type Value 7106 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 7107 LocTy Loc; 7108 Value *Op; 7109 if (parseTypeAndValue(Op, Loc, PFS)) 7110 return true; 7111 7112 Inst = new FreezeInst(Op); 7113 return false; 7114 } 7115 7116 /// parseCall 7117 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 7118 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7119 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 7120 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7121 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 7122 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7123 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 7124 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7125 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 7126 CallInst::TailCallKind TCK) { 7127 AttrBuilder RetAttrs, FnAttrs; 7128 std::vector<unsigned> FwdRefAttrGrps; 7129 LocTy BuiltinLoc; 7130 unsigned CallAddrSpace; 7131 unsigned CC; 7132 Type *RetType = nullptr; 7133 LocTy RetTypeLoc; 7134 ValID CalleeID; 7135 SmallVector<ParamInfo, 16> ArgList; 7136 SmallVector<OperandBundleDef, 2> BundleList; 7137 LocTy CallLoc = Lex.getLoc(); 7138 7139 if (TCK != CallInst::TCK_None && 7140 parseToken(lltok::kw_call, 7141 "expected 'tail call', 'musttail call', or 'notail call'")) 7142 return true; 7143 7144 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7145 7146 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7147 parseOptionalProgramAddrSpace(CallAddrSpace) || 7148 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7149 parseValID(CalleeID) || 7150 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 7151 PFS.getFunction().isVarArg()) || 7152 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 7153 parseOptionalOperandBundles(BundleList, PFS)) 7154 return true; 7155 7156 // If RetType is a non-function pointer type, then this is the short syntax 7157 // for the call, which means that RetType is just the return type. Infer the 7158 // rest of the function argument types from the arguments that are present. 7159 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 7160 if (!Ty) { 7161 // Pull out the types of all of the arguments... 7162 std::vector<Type*> ParamTypes; 7163 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 7164 ParamTypes.push_back(ArgList[i].V->getType()); 7165 7166 if (!FunctionType::isValidReturnType(RetType)) 7167 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7168 7169 Ty = FunctionType::get(RetType, ParamTypes, false); 7170 } 7171 7172 CalleeID.FTy = Ty; 7173 7174 // Look up the callee. 7175 Value *Callee; 7176 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 7177 &PFS, /*IsCall=*/true)) 7178 return true; 7179 7180 // Set up the Attribute for the function. 7181 SmallVector<AttributeSet, 8> Attrs; 7182 7183 SmallVector<Value*, 8> Args; 7184 7185 // Loop through FunctionType's arguments and ensure they are specified 7186 // correctly. Also, gather any parameter attributes. 7187 FunctionType::param_iterator I = Ty->param_begin(); 7188 FunctionType::param_iterator E = Ty->param_end(); 7189 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 7190 Type *ExpectedTy = nullptr; 7191 if (I != E) { 7192 ExpectedTy = *I++; 7193 } else if (!Ty->isVarArg()) { 7194 return error(ArgList[i].Loc, "too many arguments specified"); 7195 } 7196 7197 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 7198 return error(ArgList[i].Loc, "argument is not of expected type '" + 7199 getTypeString(ExpectedTy) + "'"); 7200 Args.push_back(ArgList[i].V); 7201 Attrs.push_back(ArgList[i].Attrs); 7202 } 7203 7204 if (I != E) 7205 return error(CallLoc, "not enough parameters specified for call"); 7206 7207 if (FnAttrs.hasAlignmentAttr()) 7208 return error(CallLoc, "call instructions may not have an alignment"); 7209 7210 // Finish off the Attribute and check them 7211 AttributeList PAL = 7212 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7213 AttributeSet::get(Context, RetAttrs), Attrs); 7214 7215 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 7216 CI->setTailCallKind(TCK); 7217 CI->setCallingConv(CC); 7218 if (FMF.any()) { 7219 if (!isa<FPMathOperator>(CI)) { 7220 CI->deleteValue(); 7221 return error(CallLoc, "fast-math-flags specified for call without " 7222 "floating-point scalar or vector return type"); 7223 } 7224 CI->setFastMathFlags(FMF); 7225 } 7226 CI->setAttributes(PAL); 7227 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 7228 Inst = CI; 7229 return false; 7230 } 7231 7232 //===----------------------------------------------------------------------===// 7233 // Memory Instructions. 7234 //===----------------------------------------------------------------------===// 7235 7236 /// parseAlloc 7237 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 7238 /// (',' 'align' i32)? (',', 'addrspace(n))? 7239 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 7240 Value *Size = nullptr; 7241 LocTy SizeLoc, TyLoc, ASLoc; 7242 MaybeAlign Alignment; 7243 unsigned AddrSpace = 0; 7244 Type *Ty = nullptr; 7245 7246 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 7247 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 7248 7249 if (parseType(Ty, TyLoc)) 7250 return true; 7251 7252 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7253 return error(TyLoc, "invalid type for alloca"); 7254 7255 bool AteExtraComma = false; 7256 if (EatIfPresent(lltok::comma)) { 7257 if (Lex.getKind() == lltok::kw_align) { 7258 if (parseOptionalAlignment(Alignment)) 7259 return true; 7260 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7261 return true; 7262 } else if (Lex.getKind() == lltok::kw_addrspace) { 7263 ASLoc = Lex.getLoc(); 7264 if (parseOptionalAddrSpace(AddrSpace)) 7265 return true; 7266 } else if (Lex.getKind() == lltok::MetadataVar) { 7267 AteExtraComma = true; 7268 } else { 7269 if (parseTypeAndValue(Size, SizeLoc, PFS)) 7270 return true; 7271 if (EatIfPresent(lltok::comma)) { 7272 if (Lex.getKind() == lltok::kw_align) { 7273 if (parseOptionalAlignment(Alignment)) 7274 return true; 7275 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7276 return true; 7277 } else if (Lex.getKind() == lltok::kw_addrspace) { 7278 ASLoc = Lex.getLoc(); 7279 if (parseOptionalAddrSpace(AddrSpace)) 7280 return true; 7281 } else if (Lex.getKind() == lltok::MetadataVar) { 7282 AteExtraComma = true; 7283 } 7284 } 7285 } 7286 } 7287 7288 if (Size && !Size->getType()->isIntegerTy()) 7289 return error(SizeLoc, "element count must have integer type"); 7290 7291 SmallPtrSet<Type *, 4> Visited; 7292 if (!Alignment && !Ty->isSized(&Visited)) 7293 return error(TyLoc, "Cannot allocate unsized type"); 7294 if (!Alignment) 7295 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7296 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7297 AI->setUsedWithInAlloca(IsInAlloca); 7298 AI->setSwiftError(IsSwiftError); 7299 Inst = AI; 7300 return AteExtraComma ? InstExtraComma : InstNormal; 7301 } 7302 7303 /// parseLoad 7304 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7305 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7306 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7307 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7308 Value *Val; LocTy Loc; 7309 MaybeAlign Alignment; 7310 bool AteExtraComma = false; 7311 bool isAtomic = false; 7312 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7313 SyncScope::ID SSID = SyncScope::System; 7314 7315 if (Lex.getKind() == lltok::kw_atomic) { 7316 isAtomic = true; 7317 Lex.Lex(); 7318 } 7319 7320 bool isVolatile = false; 7321 if (Lex.getKind() == lltok::kw_volatile) { 7322 isVolatile = true; 7323 Lex.Lex(); 7324 } 7325 7326 Type *Ty; 7327 LocTy ExplicitTypeLoc = Lex.getLoc(); 7328 if (parseType(Ty) || 7329 parseToken(lltok::comma, "expected comma after load's type") || 7330 parseTypeAndValue(Val, Loc, PFS) || 7331 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7332 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7333 return true; 7334 7335 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7336 return error(Loc, "load operand must be a pointer to a first class type"); 7337 if (isAtomic && !Alignment) 7338 return error(Loc, "atomic load must have explicit non-zero alignment"); 7339 if (Ordering == AtomicOrdering::Release || 7340 Ordering == AtomicOrdering::AcquireRelease) 7341 return error(Loc, "atomic load cannot use Release ordering"); 7342 7343 if (Ty != cast<PointerType>(Val->getType())->getElementType()) 7344 return error(ExplicitTypeLoc, 7345 "explicit pointee type doesn't match operand's pointee type"); 7346 SmallPtrSet<Type *, 4> Visited; 7347 if (!Alignment && !Ty->isSized(&Visited)) 7348 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7349 if (!Alignment) 7350 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7351 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7352 return AteExtraComma ? InstExtraComma : InstNormal; 7353 } 7354 7355 /// parseStore 7356 7357 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7358 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7359 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7360 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 7361 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7362 MaybeAlign Alignment; 7363 bool AteExtraComma = false; 7364 bool isAtomic = false; 7365 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7366 SyncScope::ID SSID = SyncScope::System; 7367 7368 if (Lex.getKind() == lltok::kw_atomic) { 7369 isAtomic = true; 7370 Lex.Lex(); 7371 } 7372 7373 bool isVolatile = false; 7374 if (Lex.getKind() == lltok::kw_volatile) { 7375 isVolatile = true; 7376 Lex.Lex(); 7377 } 7378 7379 if (parseTypeAndValue(Val, Loc, PFS) || 7380 parseToken(lltok::comma, "expected ',' after store operand") || 7381 parseTypeAndValue(Ptr, PtrLoc, PFS) || 7382 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7383 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7384 return true; 7385 7386 if (!Ptr->getType()->isPointerTy()) 7387 return error(PtrLoc, "store operand must be a pointer"); 7388 if (!Val->getType()->isFirstClassType()) 7389 return error(Loc, "store operand must be a first class value"); 7390 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7391 return error(Loc, "stored value and pointer type do not match"); 7392 if (isAtomic && !Alignment) 7393 return error(Loc, "atomic store must have explicit non-zero alignment"); 7394 if (Ordering == AtomicOrdering::Acquire || 7395 Ordering == AtomicOrdering::AcquireRelease) 7396 return error(Loc, "atomic store cannot use Acquire ordering"); 7397 SmallPtrSet<Type *, 4> Visited; 7398 if (!Alignment && !Val->getType()->isSized(&Visited)) 7399 return error(Loc, "storing unsized types is not allowed"); 7400 if (!Alignment) 7401 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7402 7403 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7404 return AteExtraComma ? InstExtraComma : InstNormal; 7405 } 7406 7407 /// parseCmpXchg 7408 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7409 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering 7410 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7411 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7412 bool AteExtraComma = false; 7413 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7414 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7415 SyncScope::ID SSID = SyncScope::System; 7416 bool isVolatile = false; 7417 bool isWeak = false; 7418 7419 if (EatIfPresent(lltok::kw_weak)) 7420 isWeak = true; 7421 7422 if (EatIfPresent(lltok::kw_volatile)) 7423 isVolatile = true; 7424 7425 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7426 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 7427 parseTypeAndValue(Cmp, CmpLoc, PFS) || 7428 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7429 parseTypeAndValue(New, NewLoc, PFS) || 7430 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7431 parseOrdering(FailureOrdering)) 7432 return true; 7433 7434 if (SuccessOrdering == AtomicOrdering::Unordered || 7435 FailureOrdering == AtomicOrdering::Unordered) 7436 return tokError("cmpxchg cannot be unordered"); 7437 if (isStrongerThan(FailureOrdering, SuccessOrdering)) 7438 return tokError("cmpxchg failure argument shall be no stronger than the " 7439 "success argument"); 7440 if (FailureOrdering == AtomicOrdering::Release || 7441 FailureOrdering == AtomicOrdering::AcquireRelease) 7442 return tokError( 7443 "cmpxchg failure ordering cannot include release semantics"); 7444 if (!Ptr->getType()->isPointerTy()) 7445 return error(PtrLoc, "cmpxchg operand must be a pointer"); 7446 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 7447 return error(CmpLoc, "compare value and pointer type do not match"); 7448 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 7449 return error(NewLoc, "new value and pointer type do not match"); 7450 if (!New->getType()->isFirstClassType()) 7451 return error(NewLoc, "cmpxchg operand must be a first class value"); 7452 7453 Align Alignment( 7454 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7455 Cmp->getType())); 7456 7457 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7458 Ptr, Cmp, New, Alignment, SuccessOrdering, FailureOrdering, SSID); 7459 CXI->setVolatile(isVolatile); 7460 CXI->setWeak(isWeak); 7461 Inst = CXI; 7462 return AteExtraComma ? InstExtraComma : InstNormal; 7463 } 7464 7465 /// parseAtomicRMW 7466 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7467 /// 'singlethread'? AtomicOrdering 7468 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7469 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7470 bool AteExtraComma = false; 7471 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7472 SyncScope::ID SSID = SyncScope::System; 7473 bool isVolatile = false; 7474 bool IsFP = false; 7475 AtomicRMWInst::BinOp Operation; 7476 7477 if (EatIfPresent(lltok::kw_volatile)) 7478 isVolatile = true; 7479 7480 switch (Lex.getKind()) { 7481 default: 7482 return tokError("expected binary operation in atomicrmw"); 7483 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7484 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7485 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7486 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7487 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7488 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7489 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7490 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7491 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7492 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7493 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7494 case lltok::kw_fadd: 7495 Operation = AtomicRMWInst::FAdd; 7496 IsFP = true; 7497 break; 7498 case lltok::kw_fsub: 7499 Operation = AtomicRMWInst::FSub; 7500 IsFP = true; 7501 break; 7502 } 7503 Lex.Lex(); // Eat the operation. 7504 7505 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7506 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 7507 parseTypeAndValue(Val, ValLoc, PFS) || 7508 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7509 return true; 7510 7511 if (Ordering == AtomicOrdering::Unordered) 7512 return tokError("atomicrmw cannot be unordered"); 7513 if (!Ptr->getType()->isPointerTy()) 7514 return error(PtrLoc, "atomicrmw operand must be a pointer"); 7515 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7516 return error(ValLoc, "atomicrmw value and pointer type do not match"); 7517 7518 if (Operation == AtomicRMWInst::Xchg) { 7519 if (!Val->getType()->isIntegerTy() && 7520 !Val->getType()->isFloatingPointTy()) { 7521 return error(ValLoc, 7522 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 7523 " operand must be an integer or floating point type"); 7524 } 7525 } else if (IsFP) { 7526 if (!Val->getType()->isFloatingPointTy()) { 7527 return error(ValLoc, "atomicrmw " + 7528 AtomicRMWInst::getOperationName(Operation) + 7529 " operand must be a floating point type"); 7530 } 7531 } else { 7532 if (!Val->getType()->isIntegerTy()) { 7533 return error(ValLoc, "atomicrmw " + 7534 AtomicRMWInst::getOperationName(Operation) + 7535 " operand must be an integer"); 7536 } 7537 } 7538 7539 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7540 if (Size < 8 || (Size & (Size - 1))) 7541 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7542 " integer"); 7543 Align Alignment( 7544 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7545 Val->getType())); 7546 AtomicRMWInst *RMWI = 7547 new AtomicRMWInst(Operation, Ptr, Val, Alignment, Ordering, SSID); 7548 RMWI->setVolatile(isVolatile); 7549 Inst = RMWI; 7550 return AteExtraComma ? InstExtraComma : InstNormal; 7551 } 7552 7553 /// parseFence 7554 /// ::= 'fence' 'singlethread'? AtomicOrdering 7555 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 7556 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7557 SyncScope::ID SSID = SyncScope::System; 7558 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7559 return true; 7560 7561 if (Ordering == AtomicOrdering::Unordered) 7562 return tokError("fence cannot be unordered"); 7563 if (Ordering == AtomicOrdering::Monotonic) 7564 return tokError("fence cannot be monotonic"); 7565 7566 Inst = new FenceInst(Context, Ordering, SSID); 7567 return InstNormal; 7568 } 7569 7570 /// parseGetElementPtr 7571 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7572 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7573 Value *Ptr = nullptr; 7574 Value *Val = nullptr; 7575 LocTy Loc, EltLoc; 7576 7577 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7578 7579 Type *Ty = nullptr; 7580 LocTy ExplicitTypeLoc = Lex.getLoc(); 7581 if (parseType(Ty) || 7582 parseToken(lltok::comma, "expected comma after getelementptr's type") || 7583 parseTypeAndValue(Ptr, Loc, PFS)) 7584 return true; 7585 7586 Type *BaseType = Ptr->getType(); 7587 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7588 if (!BasePointerType) 7589 return error(Loc, "base of getelementptr must be a pointer"); 7590 7591 if (Ty != BasePointerType->getElementType()) 7592 return error(ExplicitTypeLoc, 7593 "explicit pointee type doesn't match operand's pointee type"); 7594 7595 SmallVector<Value*, 16> Indices; 7596 bool AteExtraComma = false; 7597 // GEP returns a vector of pointers if at least one of parameters is a vector. 7598 // All vector parameters should have the same vector width. 7599 ElementCount GEPWidth = BaseType->isVectorTy() 7600 ? cast<VectorType>(BaseType)->getElementCount() 7601 : ElementCount::getFixed(0); 7602 7603 while (EatIfPresent(lltok::comma)) { 7604 if (Lex.getKind() == lltok::MetadataVar) { 7605 AteExtraComma = true; 7606 break; 7607 } 7608 if (parseTypeAndValue(Val, EltLoc, PFS)) 7609 return true; 7610 if (!Val->getType()->isIntOrIntVectorTy()) 7611 return error(EltLoc, "getelementptr index must be an integer"); 7612 7613 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7614 ElementCount ValNumEl = ValVTy->getElementCount(); 7615 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 7616 return error( 7617 EltLoc, 7618 "getelementptr vector index has a wrong number of elements"); 7619 GEPWidth = ValNumEl; 7620 } 7621 Indices.push_back(Val); 7622 } 7623 7624 SmallPtrSet<Type*, 4> Visited; 7625 if (!Indices.empty() && !Ty->isSized(&Visited)) 7626 return error(Loc, "base element of getelementptr must be sized"); 7627 7628 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7629 return error(Loc, "invalid getelementptr indices"); 7630 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7631 if (InBounds) 7632 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7633 return AteExtraComma ? InstExtraComma : InstNormal; 7634 } 7635 7636 /// parseExtractValue 7637 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7638 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7639 Value *Val; LocTy Loc; 7640 SmallVector<unsigned, 4> Indices; 7641 bool AteExtraComma; 7642 if (parseTypeAndValue(Val, Loc, PFS) || 7643 parseIndexList(Indices, AteExtraComma)) 7644 return true; 7645 7646 if (!Val->getType()->isAggregateType()) 7647 return error(Loc, "extractvalue operand must be aggregate type"); 7648 7649 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7650 return error(Loc, "invalid indices for extractvalue"); 7651 Inst = ExtractValueInst::Create(Val, Indices); 7652 return AteExtraComma ? InstExtraComma : InstNormal; 7653 } 7654 7655 /// parseInsertValue 7656 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7657 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7658 Value *Val0, *Val1; LocTy Loc0, Loc1; 7659 SmallVector<unsigned, 4> Indices; 7660 bool AteExtraComma; 7661 if (parseTypeAndValue(Val0, Loc0, PFS) || 7662 parseToken(lltok::comma, "expected comma after insertvalue operand") || 7663 parseTypeAndValue(Val1, Loc1, PFS) || 7664 parseIndexList(Indices, AteExtraComma)) 7665 return true; 7666 7667 if (!Val0->getType()->isAggregateType()) 7668 return error(Loc0, "insertvalue operand must be aggregate type"); 7669 7670 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7671 if (!IndexedType) 7672 return error(Loc0, "invalid indices for insertvalue"); 7673 if (IndexedType != Val1->getType()) 7674 return error(Loc1, "insertvalue operand and field disagree in type: '" + 7675 getTypeString(Val1->getType()) + "' instead of '" + 7676 getTypeString(IndexedType) + "'"); 7677 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7678 return AteExtraComma ? InstExtraComma : InstNormal; 7679 } 7680 7681 //===----------------------------------------------------------------------===// 7682 // Embedded metadata. 7683 //===----------------------------------------------------------------------===// 7684 7685 /// parseMDNodeVector 7686 /// ::= { Element (',' Element)* } 7687 /// Element 7688 /// ::= 'null' | TypeAndValue 7689 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7690 if (parseToken(lltok::lbrace, "expected '{' here")) 7691 return true; 7692 7693 // Check for an empty list. 7694 if (EatIfPresent(lltok::rbrace)) 7695 return false; 7696 7697 do { 7698 // Null is a special case since it is typeless. 7699 if (EatIfPresent(lltok::kw_null)) { 7700 Elts.push_back(nullptr); 7701 continue; 7702 } 7703 7704 Metadata *MD; 7705 if (parseMetadata(MD, nullptr)) 7706 return true; 7707 Elts.push_back(MD); 7708 } while (EatIfPresent(lltok::comma)); 7709 7710 return parseToken(lltok::rbrace, "expected end of metadata node"); 7711 } 7712 7713 //===----------------------------------------------------------------------===// 7714 // Use-list order directives. 7715 //===----------------------------------------------------------------------===// 7716 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7717 SMLoc Loc) { 7718 if (V->use_empty()) 7719 return error(Loc, "value has no uses"); 7720 7721 unsigned NumUses = 0; 7722 SmallDenseMap<const Use *, unsigned, 16> Order; 7723 for (const Use &U : V->uses()) { 7724 if (++NumUses > Indexes.size()) 7725 break; 7726 Order[&U] = Indexes[NumUses - 1]; 7727 } 7728 if (NumUses < 2) 7729 return error(Loc, "value only has one use"); 7730 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7731 return error(Loc, 7732 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7733 7734 V->sortUseList([&](const Use &L, const Use &R) { 7735 return Order.lookup(&L) < Order.lookup(&R); 7736 }); 7737 return false; 7738 } 7739 7740 /// parseUseListOrderIndexes 7741 /// ::= '{' uint32 (',' uint32)+ '}' 7742 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7743 SMLoc Loc = Lex.getLoc(); 7744 if (parseToken(lltok::lbrace, "expected '{' here")) 7745 return true; 7746 if (Lex.getKind() == lltok::rbrace) 7747 return Lex.Error("expected non-empty list of uselistorder indexes"); 7748 7749 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7750 // indexes should be distinct numbers in the range [0, size-1], and should 7751 // not be in order. 7752 unsigned Offset = 0; 7753 unsigned Max = 0; 7754 bool IsOrdered = true; 7755 assert(Indexes.empty() && "Expected empty order vector"); 7756 do { 7757 unsigned Index; 7758 if (parseUInt32(Index)) 7759 return true; 7760 7761 // Update consistency checks. 7762 Offset += Index - Indexes.size(); 7763 Max = std::max(Max, Index); 7764 IsOrdered &= Index == Indexes.size(); 7765 7766 Indexes.push_back(Index); 7767 } while (EatIfPresent(lltok::comma)); 7768 7769 if (parseToken(lltok::rbrace, "expected '}' here")) 7770 return true; 7771 7772 if (Indexes.size() < 2) 7773 return error(Loc, "expected >= 2 uselistorder indexes"); 7774 if (Offset != 0 || Max >= Indexes.size()) 7775 return error(Loc, 7776 "expected distinct uselistorder indexes in range [0, size)"); 7777 if (IsOrdered) 7778 return error(Loc, "expected uselistorder indexes to change the order"); 7779 7780 return false; 7781 } 7782 7783 /// parseUseListOrder 7784 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7785 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 7786 SMLoc Loc = Lex.getLoc(); 7787 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7788 return true; 7789 7790 Value *V; 7791 SmallVector<unsigned, 16> Indexes; 7792 if (parseTypeAndValue(V, PFS) || 7793 parseToken(lltok::comma, "expected comma in uselistorder directive") || 7794 parseUseListOrderIndexes(Indexes)) 7795 return true; 7796 7797 return sortUseListOrder(V, Indexes, Loc); 7798 } 7799 7800 /// parseUseListOrderBB 7801 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7802 bool LLParser::parseUseListOrderBB() { 7803 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7804 SMLoc Loc = Lex.getLoc(); 7805 Lex.Lex(); 7806 7807 ValID Fn, Label; 7808 SmallVector<unsigned, 16> Indexes; 7809 if (parseValID(Fn) || 7810 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7811 parseValID(Label) || 7812 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7813 parseUseListOrderIndexes(Indexes)) 7814 return true; 7815 7816 // Check the function. 7817 GlobalValue *GV; 7818 if (Fn.Kind == ValID::t_GlobalName) 7819 GV = M->getNamedValue(Fn.StrVal); 7820 else if (Fn.Kind == ValID::t_GlobalID) 7821 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7822 else 7823 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7824 if (!GV) 7825 return error(Fn.Loc, 7826 "invalid function forward reference in uselistorder_bb"); 7827 auto *F = dyn_cast<Function>(GV); 7828 if (!F) 7829 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7830 if (F->isDeclaration()) 7831 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7832 7833 // Check the basic block. 7834 if (Label.Kind == ValID::t_LocalID) 7835 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7836 if (Label.Kind != ValID::t_LocalName) 7837 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 7838 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7839 if (!V) 7840 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 7841 if (!isa<BasicBlock>(V)) 7842 return error(Label.Loc, "expected basic block in uselistorder_bb"); 7843 7844 return sortUseListOrder(V, Indexes, Loc); 7845 } 7846 7847 /// ModuleEntry 7848 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7849 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7850 bool LLParser::parseModuleEntry(unsigned ID) { 7851 assert(Lex.getKind() == lltok::kw_module); 7852 Lex.Lex(); 7853 7854 std::string Path; 7855 if (parseToken(lltok::colon, "expected ':' here") || 7856 parseToken(lltok::lparen, "expected '(' here") || 7857 parseToken(lltok::kw_path, "expected 'path' here") || 7858 parseToken(lltok::colon, "expected ':' here") || 7859 parseStringConstant(Path) || 7860 parseToken(lltok::comma, "expected ',' here") || 7861 parseToken(lltok::kw_hash, "expected 'hash' here") || 7862 parseToken(lltok::colon, "expected ':' here") || 7863 parseToken(lltok::lparen, "expected '(' here")) 7864 return true; 7865 7866 ModuleHash Hash; 7867 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 7868 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 7869 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 7870 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 7871 parseUInt32(Hash[4])) 7872 return true; 7873 7874 if (parseToken(lltok::rparen, "expected ')' here") || 7875 parseToken(lltok::rparen, "expected ')' here")) 7876 return true; 7877 7878 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7879 ModuleIdMap[ID] = ModuleEntry->first(); 7880 7881 return false; 7882 } 7883 7884 /// TypeIdEntry 7885 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7886 bool LLParser::parseTypeIdEntry(unsigned ID) { 7887 assert(Lex.getKind() == lltok::kw_typeid); 7888 Lex.Lex(); 7889 7890 std::string Name; 7891 if (parseToken(lltok::colon, "expected ':' here") || 7892 parseToken(lltok::lparen, "expected '(' here") || 7893 parseToken(lltok::kw_name, "expected 'name' here") || 7894 parseToken(lltok::colon, "expected ':' here") || 7895 parseStringConstant(Name)) 7896 return true; 7897 7898 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7899 if (parseToken(lltok::comma, "expected ',' here") || 7900 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 7901 return true; 7902 7903 // Check if this ID was forward referenced, and if so, update the 7904 // corresponding GUIDs. 7905 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7906 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7907 for (auto TIDRef : FwdRefTIDs->second) { 7908 assert(!*TIDRef.first && 7909 "Forward referenced type id GUID expected to be 0"); 7910 *TIDRef.first = GlobalValue::getGUID(Name); 7911 } 7912 ForwardRefTypeIds.erase(FwdRefTIDs); 7913 } 7914 7915 return false; 7916 } 7917 7918 /// TypeIdSummary 7919 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7920 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 7921 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 7922 parseToken(lltok::colon, "expected ':' here") || 7923 parseToken(lltok::lparen, "expected '(' here") || 7924 parseTypeTestResolution(TIS.TTRes)) 7925 return true; 7926 7927 if (EatIfPresent(lltok::comma)) { 7928 // Expect optional wpdResolutions field 7929 if (parseOptionalWpdResolutions(TIS.WPDRes)) 7930 return true; 7931 } 7932 7933 if (parseToken(lltok::rparen, "expected ')' here")) 7934 return true; 7935 7936 return false; 7937 } 7938 7939 static ValueInfo EmptyVI = 7940 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7941 7942 /// TypeIdCompatibleVtableEntry 7943 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7944 /// TypeIdCompatibleVtableInfo 7945 /// ')' 7946 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 7947 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7948 Lex.Lex(); 7949 7950 std::string Name; 7951 if (parseToken(lltok::colon, "expected ':' here") || 7952 parseToken(lltok::lparen, "expected '(' here") || 7953 parseToken(lltok::kw_name, "expected 'name' here") || 7954 parseToken(lltok::colon, "expected ':' here") || 7955 parseStringConstant(Name)) 7956 return true; 7957 7958 TypeIdCompatibleVtableInfo &TI = 7959 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7960 if (parseToken(lltok::comma, "expected ',' here") || 7961 parseToken(lltok::kw_summary, "expected 'summary' here") || 7962 parseToken(lltok::colon, "expected ':' here") || 7963 parseToken(lltok::lparen, "expected '(' here")) 7964 return true; 7965 7966 IdToIndexMapType IdToIndexMap; 7967 // parse each call edge 7968 do { 7969 uint64_t Offset; 7970 if (parseToken(lltok::lparen, "expected '(' here") || 7971 parseToken(lltok::kw_offset, "expected 'offset' here") || 7972 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7973 parseToken(lltok::comma, "expected ',' here")) 7974 return true; 7975 7976 LocTy Loc = Lex.getLoc(); 7977 unsigned GVId; 7978 ValueInfo VI; 7979 if (parseGVReference(VI, GVId)) 7980 return true; 7981 7982 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7983 // forward reference. We will save the location of the ValueInfo needing an 7984 // update, but can only do so once the std::vector is finalized. 7985 if (VI == EmptyVI) 7986 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7987 TI.push_back({Offset, VI}); 7988 7989 if (parseToken(lltok::rparen, "expected ')' in call")) 7990 return true; 7991 } while (EatIfPresent(lltok::comma)); 7992 7993 // Now that the TI vector is finalized, it is safe to save the locations 7994 // of any forward GV references that need updating later. 7995 for (auto I : IdToIndexMap) { 7996 auto &Infos = ForwardRefValueInfos[I.first]; 7997 for (auto P : I.second) { 7998 assert(TI[P.first].VTableVI == EmptyVI && 7999 "Forward referenced ValueInfo expected to be empty"); 8000 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 8001 } 8002 } 8003 8004 if (parseToken(lltok::rparen, "expected ')' here") || 8005 parseToken(lltok::rparen, "expected ')' here")) 8006 return true; 8007 8008 // Check if this ID was forward referenced, and if so, update the 8009 // corresponding GUIDs. 8010 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8011 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8012 for (auto TIDRef : FwdRefTIDs->second) { 8013 assert(!*TIDRef.first && 8014 "Forward referenced type id GUID expected to be 0"); 8015 *TIDRef.first = GlobalValue::getGUID(Name); 8016 } 8017 ForwardRefTypeIds.erase(FwdRefTIDs); 8018 } 8019 8020 return false; 8021 } 8022 8023 /// TypeTestResolution 8024 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 8025 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 8026 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 8027 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 8028 /// [',' 'inlinesBits' ':' UInt64]? ')' 8029 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 8030 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 8031 parseToken(lltok::colon, "expected ':' here") || 8032 parseToken(lltok::lparen, "expected '(' here") || 8033 parseToken(lltok::kw_kind, "expected 'kind' here") || 8034 parseToken(lltok::colon, "expected ':' here")) 8035 return true; 8036 8037 switch (Lex.getKind()) { 8038 case lltok::kw_unknown: 8039 TTRes.TheKind = TypeTestResolution::Unknown; 8040 break; 8041 case lltok::kw_unsat: 8042 TTRes.TheKind = TypeTestResolution::Unsat; 8043 break; 8044 case lltok::kw_byteArray: 8045 TTRes.TheKind = TypeTestResolution::ByteArray; 8046 break; 8047 case lltok::kw_inline: 8048 TTRes.TheKind = TypeTestResolution::Inline; 8049 break; 8050 case lltok::kw_single: 8051 TTRes.TheKind = TypeTestResolution::Single; 8052 break; 8053 case lltok::kw_allOnes: 8054 TTRes.TheKind = TypeTestResolution::AllOnes; 8055 break; 8056 default: 8057 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 8058 } 8059 Lex.Lex(); 8060 8061 if (parseToken(lltok::comma, "expected ',' here") || 8062 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 8063 parseToken(lltok::colon, "expected ':' here") || 8064 parseUInt32(TTRes.SizeM1BitWidth)) 8065 return true; 8066 8067 // parse optional fields 8068 while (EatIfPresent(lltok::comma)) { 8069 switch (Lex.getKind()) { 8070 case lltok::kw_alignLog2: 8071 Lex.Lex(); 8072 if (parseToken(lltok::colon, "expected ':'") || 8073 parseUInt64(TTRes.AlignLog2)) 8074 return true; 8075 break; 8076 case lltok::kw_sizeM1: 8077 Lex.Lex(); 8078 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 8079 return true; 8080 break; 8081 case lltok::kw_bitMask: { 8082 unsigned Val; 8083 Lex.Lex(); 8084 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 8085 return true; 8086 assert(Val <= 0xff); 8087 TTRes.BitMask = (uint8_t)Val; 8088 break; 8089 } 8090 case lltok::kw_inlineBits: 8091 Lex.Lex(); 8092 if (parseToken(lltok::colon, "expected ':'") || 8093 parseUInt64(TTRes.InlineBits)) 8094 return true; 8095 break; 8096 default: 8097 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 8098 } 8099 } 8100 8101 if (parseToken(lltok::rparen, "expected ')' here")) 8102 return true; 8103 8104 return false; 8105 } 8106 8107 /// OptionalWpdResolutions 8108 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 8109 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 8110 bool LLParser::parseOptionalWpdResolutions( 8111 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 8112 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 8113 parseToken(lltok::colon, "expected ':' here") || 8114 parseToken(lltok::lparen, "expected '(' here")) 8115 return true; 8116 8117 do { 8118 uint64_t Offset; 8119 WholeProgramDevirtResolution WPDRes; 8120 if (parseToken(lltok::lparen, "expected '(' here") || 8121 parseToken(lltok::kw_offset, "expected 'offset' here") || 8122 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8123 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 8124 parseToken(lltok::rparen, "expected ')' here")) 8125 return true; 8126 WPDResMap[Offset] = WPDRes; 8127 } while (EatIfPresent(lltok::comma)); 8128 8129 if (parseToken(lltok::rparen, "expected ')' here")) 8130 return true; 8131 8132 return false; 8133 } 8134 8135 /// WpdRes 8136 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 8137 /// [',' OptionalResByArg]? ')' 8138 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 8139 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 8140 /// [',' OptionalResByArg]? ')' 8141 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 8142 /// [',' OptionalResByArg]? ')' 8143 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 8144 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 8145 parseToken(lltok::colon, "expected ':' here") || 8146 parseToken(lltok::lparen, "expected '(' here") || 8147 parseToken(lltok::kw_kind, "expected 'kind' here") || 8148 parseToken(lltok::colon, "expected ':' here")) 8149 return true; 8150 8151 switch (Lex.getKind()) { 8152 case lltok::kw_indir: 8153 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 8154 break; 8155 case lltok::kw_singleImpl: 8156 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 8157 break; 8158 case lltok::kw_branchFunnel: 8159 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 8160 break; 8161 default: 8162 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 8163 } 8164 Lex.Lex(); 8165 8166 // parse optional fields 8167 while (EatIfPresent(lltok::comma)) { 8168 switch (Lex.getKind()) { 8169 case lltok::kw_singleImplName: 8170 Lex.Lex(); 8171 if (parseToken(lltok::colon, "expected ':' here") || 8172 parseStringConstant(WPDRes.SingleImplName)) 8173 return true; 8174 break; 8175 case lltok::kw_resByArg: 8176 if (parseOptionalResByArg(WPDRes.ResByArg)) 8177 return true; 8178 break; 8179 default: 8180 return error(Lex.getLoc(), 8181 "expected optional WholeProgramDevirtResolution field"); 8182 } 8183 } 8184 8185 if (parseToken(lltok::rparen, "expected ')' here")) 8186 return true; 8187 8188 return false; 8189 } 8190 8191 /// OptionalResByArg 8192 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 8193 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 8194 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 8195 /// 'virtualConstProp' ) 8196 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 8197 /// [',' 'bit' ':' UInt32]? ')' 8198 bool LLParser::parseOptionalResByArg( 8199 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 8200 &ResByArg) { 8201 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 8202 parseToken(lltok::colon, "expected ':' here") || 8203 parseToken(lltok::lparen, "expected '(' here")) 8204 return true; 8205 8206 do { 8207 std::vector<uint64_t> Args; 8208 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 8209 parseToken(lltok::kw_byArg, "expected 'byArg here") || 8210 parseToken(lltok::colon, "expected ':' here") || 8211 parseToken(lltok::lparen, "expected '(' here") || 8212 parseToken(lltok::kw_kind, "expected 'kind' here") || 8213 parseToken(lltok::colon, "expected ':' here")) 8214 return true; 8215 8216 WholeProgramDevirtResolution::ByArg ByArg; 8217 switch (Lex.getKind()) { 8218 case lltok::kw_indir: 8219 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 8220 break; 8221 case lltok::kw_uniformRetVal: 8222 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 8223 break; 8224 case lltok::kw_uniqueRetVal: 8225 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 8226 break; 8227 case lltok::kw_virtualConstProp: 8228 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 8229 break; 8230 default: 8231 return error(Lex.getLoc(), 8232 "unexpected WholeProgramDevirtResolution::ByArg kind"); 8233 } 8234 Lex.Lex(); 8235 8236 // parse optional fields 8237 while (EatIfPresent(lltok::comma)) { 8238 switch (Lex.getKind()) { 8239 case lltok::kw_info: 8240 Lex.Lex(); 8241 if (parseToken(lltok::colon, "expected ':' here") || 8242 parseUInt64(ByArg.Info)) 8243 return true; 8244 break; 8245 case lltok::kw_byte: 8246 Lex.Lex(); 8247 if (parseToken(lltok::colon, "expected ':' here") || 8248 parseUInt32(ByArg.Byte)) 8249 return true; 8250 break; 8251 case lltok::kw_bit: 8252 Lex.Lex(); 8253 if (parseToken(lltok::colon, "expected ':' here") || 8254 parseUInt32(ByArg.Bit)) 8255 return true; 8256 break; 8257 default: 8258 return error(Lex.getLoc(), 8259 "expected optional whole program devirt field"); 8260 } 8261 } 8262 8263 if (parseToken(lltok::rparen, "expected ')' here")) 8264 return true; 8265 8266 ResByArg[Args] = ByArg; 8267 } while (EatIfPresent(lltok::comma)); 8268 8269 if (parseToken(lltok::rparen, "expected ')' here")) 8270 return true; 8271 8272 return false; 8273 } 8274 8275 /// OptionalResByArg 8276 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8277 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 8278 if (parseToken(lltok::kw_args, "expected 'args' here") || 8279 parseToken(lltok::colon, "expected ':' here") || 8280 parseToken(lltok::lparen, "expected '(' here")) 8281 return true; 8282 8283 do { 8284 uint64_t Val; 8285 if (parseUInt64(Val)) 8286 return true; 8287 Args.push_back(Val); 8288 } while (EatIfPresent(lltok::comma)); 8289 8290 if (parseToken(lltok::rparen, "expected ')' here")) 8291 return true; 8292 8293 return false; 8294 } 8295 8296 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8297 8298 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8299 bool ReadOnly = Fwd->isReadOnly(); 8300 bool WriteOnly = Fwd->isWriteOnly(); 8301 assert(!(ReadOnly && WriteOnly)); 8302 *Fwd = Resolved; 8303 if (ReadOnly) 8304 Fwd->setReadOnly(); 8305 if (WriteOnly) 8306 Fwd->setWriteOnly(); 8307 } 8308 8309 /// Stores the given Name/GUID and associated summary into the Index. 8310 /// Also updates any forward references to the associated entry ID. 8311 void LLParser::addGlobalValueToIndex( 8312 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8313 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8314 // First create the ValueInfo utilizing the Name or GUID. 8315 ValueInfo VI; 8316 if (GUID != 0) { 8317 assert(Name.empty()); 8318 VI = Index->getOrInsertValueInfo(GUID); 8319 } else { 8320 assert(!Name.empty()); 8321 if (M) { 8322 auto *GV = M->getNamedValue(Name); 8323 assert(GV); 8324 VI = Index->getOrInsertValueInfo(GV); 8325 } else { 8326 assert( 8327 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8328 "Need a source_filename to compute GUID for local"); 8329 GUID = GlobalValue::getGUID( 8330 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8331 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8332 } 8333 } 8334 8335 // Resolve forward references from calls/refs 8336 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8337 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8338 for (auto VIRef : FwdRefVIs->second) { 8339 assert(VIRef.first->getRef() == FwdVIRef && 8340 "Forward referenced ValueInfo expected to be empty"); 8341 resolveFwdRef(VIRef.first, VI); 8342 } 8343 ForwardRefValueInfos.erase(FwdRefVIs); 8344 } 8345 8346 // Resolve forward references from aliases 8347 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8348 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8349 for (auto AliaseeRef : FwdRefAliasees->second) { 8350 assert(!AliaseeRef.first->hasAliasee() && 8351 "Forward referencing alias already has aliasee"); 8352 assert(Summary && "Aliasee must be a definition"); 8353 AliaseeRef.first->setAliasee(VI, Summary.get()); 8354 } 8355 ForwardRefAliasees.erase(FwdRefAliasees); 8356 } 8357 8358 // Add the summary if one was provided. 8359 if (Summary) 8360 Index->addGlobalValueSummary(VI, std::move(Summary)); 8361 8362 // Save the associated ValueInfo for use in later references by ID. 8363 if (ID == NumberedValueInfos.size()) 8364 NumberedValueInfos.push_back(VI); 8365 else { 8366 // Handle non-continuous numbers (to make test simplification easier). 8367 if (ID > NumberedValueInfos.size()) 8368 NumberedValueInfos.resize(ID + 1); 8369 NumberedValueInfos[ID] = VI; 8370 } 8371 } 8372 8373 /// parseSummaryIndexFlags 8374 /// ::= 'flags' ':' UInt64 8375 bool LLParser::parseSummaryIndexFlags() { 8376 assert(Lex.getKind() == lltok::kw_flags); 8377 Lex.Lex(); 8378 8379 if (parseToken(lltok::colon, "expected ':' here")) 8380 return true; 8381 uint64_t Flags; 8382 if (parseUInt64(Flags)) 8383 return true; 8384 if (Index) 8385 Index->setFlags(Flags); 8386 return false; 8387 } 8388 8389 /// parseBlockCount 8390 /// ::= 'blockcount' ':' UInt64 8391 bool LLParser::parseBlockCount() { 8392 assert(Lex.getKind() == lltok::kw_blockcount); 8393 Lex.Lex(); 8394 8395 if (parseToken(lltok::colon, "expected ':' here")) 8396 return true; 8397 uint64_t BlockCount; 8398 if (parseUInt64(BlockCount)) 8399 return true; 8400 if (Index) 8401 Index->setBlockCount(BlockCount); 8402 return false; 8403 } 8404 8405 /// parseGVEntry 8406 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8407 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8408 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8409 bool LLParser::parseGVEntry(unsigned ID) { 8410 assert(Lex.getKind() == lltok::kw_gv); 8411 Lex.Lex(); 8412 8413 if (parseToken(lltok::colon, "expected ':' here") || 8414 parseToken(lltok::lparen, "expected '(' here")) 8415 return true; 8416 8417 std::string Name; 8418 GlobalValue::GUID GUID = 0; 8419 switch (Lex.getKind()) { 8420 case lltok::kw_name: 8421 Lex.Lex(); 8422 if (parseToken(lltok::colon, "expected ':' here") || 8423 parseStringConstant(Name)) 8424 return true; 8425 // Can't create GUID/ValueInfo until we have the linkage. 8426 break; 8427 case lltok::kw_guid: 8428 Lex.Lex(); 8429 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 8430 return true; 8431 break; 8432 default: 8433 return error(Lex.getLoc(), "expected name or guid tag"); 8434 } 8435 8436 if (!EatIfPresent(lltok::comma)) { 8437 // No summaries. Wrap up. 8438 if (parseToken(lltok::rparen, "expected ')' here")) 8439 return true; 8440 // This was created for a call to an external or indirect target. 8441 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8442 // created for indirect calls with VP. A Name with no GUID came from 8443 // an external definition. We pass ExternalLinkage since that is only 8444 // used when the GUID must be computed from Name, and in that case 8445 // the symbol must have external linkage. 8446 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8447 nullptr); 8448 return false; 8449 } 8450 8451 // Have a list of summaries 8452 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 8453 parseToken(lltok::colon, "expected ':' here") || 8454 parseToken(lltok::lparen, "expected '(' here")) 8455 return true; 8456 do { 8457 switch (Lex.getKind()) { 8458 case lltok::kw_function: 8459 if (parseFunctionSummary(Name, GUID, ID)) 8460 return true; 8461 break; 8462 case lltok::kw_variable: 8463 if (parseVariableSummary(Name, GUID, ID)) 8464 return true; 8465 break; 8466 case lltok::kw_alias: 8467 if (parseAliasSummary(Name, GUID, ID)) 8468 return true; 8469 break; 8470 default: 8471 return error(Lex.getLoc(), "expected summary type"); 8472 } 8473 } while (EatIfPresent(lltok::comma)); 8474 8475 if (parseToken(lltok::rparen, "expected ')' here") || 8476 parseToken(lltok::rparen, "expected ')' here")) 8477 return true; 8478 8479 return false; 8480 } 8481 8482 /// FunctionSummary 8483 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8484 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8485 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8486 /// [',' OptionalRefs]? ')' 8487 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8488 unsigned ID) { 8489 assert(Lex.getKind() == lltok::kw_function); 8490 Lex.Lex(); 8491 8492 StringRef ModulePath; 8493 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8494 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8495 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8496 unsigned InstCount; 8497 std::vector<FunctionSummary::EdgeTy> Calls; 8498 FunctionSummary::TypeIdInfo TypeIdInfo; 8499 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8500 std::vector<ValueInfo> Refs; 8501 // Default is all-zeros (conservative values). 8502 FunctionSummary::FFlags FFlags = {}; 8503 if (parseToken(lltok::colon, "expected ':' here") || 8504 parseToken(lltok::lparen, "expected '(' here") || 8505 parseModuleReference(ModulePath) || 8506 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8507 parseToken(lltok::comma, "expected ',' here") || 8508 parseToken(lltok::kw_insts, "expected 'insts' here") || 8509 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 8510 return true; 8511 8512 // parse optional fields 8513 while (EatIfPresent(lltok::comma)) { 8514 switch (Lex.getKind()) { 8515 case lltok::kw_funcFlags: 8516 if (parseOptionalFFlags(FFlags)) 8517 return true; 8518 break; 8519 case lltok::kw_calls: 8520 if (parseOptionalCalls(Calls)) 8521 return true; 8522 break; 8523 case lltok::kw_typeIdInfo: 8524 if (parseOptionalTypeIdInfo(TypeIdInfo)) 8525 return true; 8526 break; 8527 case lltok::kw_refs: 8528 if (parseOptionalRefs(Refs)) 8529 return true; 8530 break; 8531 case lltok::kw_params: 8532 if (parseOptionalParamAccesses(ParamAccesses)) 8533 return true; 8534 break; 8535 default: 8536 return error(Lex.getLoc(), "expected optional function summary field"); 8537 } 8538 } 8539 8540 if (parseToken(lltok::rparen, "expected ')' here")) 8541 return true; 8542 8543 auto FS = std::make_unique<FunctionSummary>( 8544 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8545 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8546 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8547 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8548 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8549 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8550 std::move(ParamAccesses)); 8551 8552 FS->setModulePath(ModulePath); 8553 8554 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8555 ID, std::move(FS)); 8556 8557 return false; 8558 } 8559 8560 /// VariableSummary 8561 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8562 /// [',' OptionalRefs]? ')' 8563 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8564 unsigned ID) { 8565 assert(Lex.getKind() == lltok::kw_variable); 8566 Lex.Lex(); 8567 8568 StringRef ModulePath; 8569 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8570 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8571 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8572 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8573 /* WriteOnly */ false, 8574 /* Constant */ false, 8575 GlobalObject::VCallVisibilityPublic); 8576 std::vector<ValueInfo> Refs; 8577 VTableFuncList VTableFuncs; 8578 if (parseToken(lltok::colon, "expected ':' here") || 8579 parseToken(lltok::lparen, "expected '(' here") || 8580 parseModuleReference(ModulePath) || 8581 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8582 parseToken(lltok::comma, "expected ',' here") || 8583 parseGVarFlags(GVarFlags)) 8584 return true; 8585 8586 // parse optional fields 8587 while (EatIfPresent(lltok::comma)) { 8588 switch (Lex.getKind()) { 8589 case lltok::kw_vTableFuncs: 8590 if (parseOptionalVTableFuncs(VTableFuncs)) 8591 return true; 8592 break; 8593 case lltok::kw_refs: 8594 if (parseOptionalRefs(Refs)) 8595 return true; 8596 break; 8597 default: 8598 return error(Lex.getLoc(), "expected optional variable summary field"); 8599 } 8600 } 8601 8602 if (parseToken(lltok::rparen, "expected ')' here")) 8603 return true; 8604 8605 auto GS = 8606 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8607 8608 GS->setModulePath(ModulePath); 8609 GS->setVTableFuncs(std::move(VTableFuncs)); 8610 8611 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8612 ID, std::move(GS)); 8613 8614 return false; 8615 } 8616 8617 /// AliasSummary 8618 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8619 /// 'aliasee' ':' GVReference ')' 8620 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8621 unsigned ID) { 8622 assert(Lex.getKind() == lltok::kw_alias); 8623 LocTy Loc = Lex.getLoc(); 8624 Lex.Lex(); 8625 8626 StringRef ModulePath; 8627 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8628 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8629 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8630 if (parseToken(lltok::colon, "expected ':' here") || 8631 parseToken(lltok::lparen, "expected '(' here") || 8632 parseModuleReference(ModulePath) || 8633 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8634 parseToken(lltok::comma, "expected ',' here") || 8635 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8636 parseToken(lltok::colon, "expected ':' here")) 8637 return true; 8638 8639 ValueInfo AliaseeVI; 8640 unsigned GVId; 8641 if (parseGVReference(AliaseeVI, GVId)) 8642 return true; 8643 8644 if (parseToken(lltok::rparen, "expected ')' here")) 8645 return true; 8646 8647 auto AS = std::make_unique<AliasSummary>(GVFlags); 8648 8649 AS->setModulePath(ModulePath); 8650 8651 // Record forward reference if the aliasee is not parsed yet. 8652 if (AliaseeVI.getRef() == FwdVIRef) { 8653 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 8654 } else { 8655 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8656 assert(Summary && "Aliasee must be a definition"); 8657 AS->setAliasee(AliaseeVI, Summary); 8658 } 8659 8660 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8661 ID, std::move(AS)); 8662 8663 return false; 8664 } 8665 8666 /// Flag 8667 /// ::= [0|1] 8668 bool LLParser::parseFlag(unsigned &Val) { 8669 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8670 return tokError("expected integer"); 8671 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8672 Lex.Lex(); 8673 return false; 8674 } 8675 8676 /// OptionalFFlags 8677 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8678 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8679 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8680 /// [',' 'noInline' ':' Flag]? ')' 8681 /// [',' 'alwaysInline' ':' Flag]? ')' 8682 8683 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8684 assert(Lex.getKind() == lltok::kw_funcFlags); 8685 Lex.Lex(); 8686 8687 if (parseToken(lltok::colon, "expected ':' in funcFlags") | 8688 parseToken(lltok::lparen, "expected '(' in funcFlags")) 8689 return true; 8690 8691 do { 8692 unsigned Val = 0; 8693 switch (Lex.getKind()) { 8694 case lltok::kw_readNone: 8695 Lex.Lex(); 8696 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8697 return true; 8698 FFlags.ReadNone = Val; 8699 break; 8700 case lltok::kw_readOnly: 8701 Lex.Lex(); 8702 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8703 return true; 8704 FFlags.ReadOnly = Val; 8705 break; 8706 case lltok::kw_noRecurse: 8707 Lex.Lex(); 8708 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8709 return true; 8710 FFlags.NoRecurse = Val; 8711 break; 8712 case lltok::kw_returnDoesNotAlias: 8713 Lex.Lex(); 8714 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8715 return true; 8716 FFlags.ReturnDoesNotAlias = Val; 8717 break; 8718 case lltok::kw_noInline: 8719 Lex.Lex(); 8720 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8721 return true; 8722 FFlags.NoInline = Val; 8723 break; 8724 case lltok::kw_alwaysInline: 8725 Lex.Lex(); 8726 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8727 return true; 8728 FFlags.AlwaysInline = Val; 8729 break; 8730 default: 8731 return error(Lex.getLoc(), "expected function flag type"); 8732 } 8733 } while (EatIfPresent(lltok::comma)); 8734 8735 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 8736 return true; 8737 8738 return false; 8739 } 8740 8741 /// OptionalCalls 8742 /// := 'calls' ':' '(' Call [',' Call]* ')' 8743 /// Call ::= '(' 'callee' ':' GVReference 8744 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8745 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8746 assert(Lex.getKind() == lltok::kw_calls); 8747 Lex.Lex(); 8748 8749 if (parseToken(lltok::colon, "expected ':' in calls") | 8750 parseToken(lltok::lparen, "expected '(' in calls")) 8751 return true; 8752 8753 IdToIndexMapType IdToIndexMap; 8754 // parse each call edge 8755 do { 8756 ValueInfo VI; 8757 if (parseToken(lltok::lparen, "expected '(' in call") || 8758 parseToken(lltok::kw_callee, "expected 'callee' in call") || 8759 parseToken(lltok::colon, "expected ':'")) 8760 return true; 8761 8762 LocTy Loc = Lex.getLoc(); 8763 unsigned GVId; 8764 if (parseGVReference(VI, GVId)) 8765 return true; 8766 8767 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8768 unsigned RelBF = 0; 8769 if (EatIfPresent(lltok::comma)) { 8770 // Expect either hotness or relbf 8771 if (EatIfPresent(lltok::kw_hotness)) { 8772 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 8773 return true; 8774 } else { 8775 if (parseToken(lltok::kw_relbf, "expected relbf") || 8776 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 8777 return true; 8778 } 8779 } 8780 // Keep track of the Call array index needing a forward reference. 8781 // We will save the location of the ValueInfo needing an update, but 8782 // can only do so once the std::vector is finalized. 8783 if (VI.getRef() == FwdVIRef) 8784 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8785 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8786 8787 if (parseToken(lltok::rparen, "expected ')' in call")) 8788 return true; 8789 } while (EatIfPresent(lltok::comma)); 8790 8791 // Now that the Calls vector is finalized, it is safe to save the locations 8792 // of any forward GV references that need updating later. 8793 for (auto I : IdToIndexMap) { 8794 auto &Infos = ForwardRefValueInfos[I.first]; 8795 for (auto P : I.second) { 8796 assert(Calls[P.first].first.getRef() == FwdVIRef && 8797 "Forward referenced ValueInfo expected to be empty"); 8798 Infos.emplace_back(&Calls[P.first].first, P.second); 8799 } 8800 } 8801 8802 if (parseToken(lltok::rparen, "expected ')' in calls")) 8803 return true; 8804 8805 return false; 8806 } 8807 8808 /// Hotness 8809 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8810 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 8811 switch (Lex.getKind()) { 8812 case lltok::kw_unknown: 8813 Hotness = CalleeInfo::HotnessType::Unknown; 8814 break; 8815 case lltok::kw_cold: 8816 Hotness = CalleeInfo::HotnessType::Cold; 8817 break; 8818 case lltok::kw_none: 8819 Hotness = CalleeInfo::HotnessType::None; 8820 break; 8821 case lltok::kw_hot: 8822 Hotness = CalleeInfo::HotnessType::Hot; 8823 break; 8824 case lltok::kw_critical: 8825 Hotness = CalleeInfo::HotnessType::Critical; 8826 break; 8827 default: 8828 return error(Lex.getLoc(), "invalid call edge hotness"); 8829 } 8830 Lex.Lex(); 8831 return false; 8832 } 8833 8834 /// OptionalVTableFuncs 8835 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8836 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8837 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8838 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8839 Lex.Lex(); 8840 8841 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") | 8842 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8843 return true; 8844 8845 IdToIndexMapType IdToIndexMap; 8846 // parse each virtual function pair 8847 do { 8848 ValueInfo VI; 8849 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 8850 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8851 parseToken(lltok::colon, "expected ':'")) 8852 return true; 8853 8854 LocTy Loc = Lex.getLoc(); 8855 unsigned GVId; 8856 if (parseGVReference(VI, GVId)) 8857 return true; 8858 8859 uint64_t Offset; 8860 if (parseToken(lltok::comma, "expected comma") || 8861 parseToken(lltok::kw_offset, "expected offset") || 8862 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 8863 return true; 8864 8865 // Keep track of the VTableFuncs array index needing a forward reference. 8866 // We will save the location of the ValueInfo needing an update, but 8867 // can only do so once the std::vector is finalized. 8868 if (VI == EmptyVI) 8869 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8870 VTableFuncs.push_back({VI, Offset}); 8871 8872 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 8873 return true; 8874 } while (EatIfPresent(lltok::comma)); 8875 8876 // Now that the VTableFuncs vector is finalized, it is safe to save the 8877 // locations of any forward GV references that need updating later. 8878 for (auto I : IdToIndexMap) { 8879 auto &Infos = ForwardRefValueInfos[I.first]; 8880 for (auto P : I.second) { 8881 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8882 "Forward referenced ValueInfo expected to be empty"); 8883 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 8884 } 8885 } 8886 8887 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8888 return true; 8889 8890 return false; 8891 } 8892 8893 /// ParamNo := 'param' ':' UInt64 8894 bool LLParser::parseParamNo(uint64_t &ParamNo) { 8895 if (parseToken(lltok::kw_param, "expected 'param' here") || 8896 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 8897 return true; 8898 return false; 8899 } 8900 8901 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8902 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 8903 APSInt Lower; 8904 APSInt Upper; 8905 auto ParseAPSInt = [&](APSInt &Val) { 8906 if (Lex.getKind() != lltok::APSInt) 8907 return tokError("expected integer"); 8908 Val = Lex.getAPSIntVal(); 8909 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8910 Val.setIsSigned(true); 8911 Lex.Lex(); 8912 return false; 8913 }; 8914 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 8915 parseToken(lltok::colon, "expected ':' here") || 8916 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8917 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8918 parseToken(lltok::rsquare, "expected ']' here")) 8919 return true; 8920 8921 ++Upper; 8922 Range = 8923 (Lower == Upper && !Lower.isMaxValue()) 8924 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8925 : ConstantRange(Lower, Upper); 8926 8927 return false; 8928 } 8929 8930 /// ParamAccessCall 8931 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8932 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 8933 IdLocListType &IdLocList) { 8934 if (parseToken(lltok::lparen, "expected '(' here") || 8935 parseToken(lltok::kw_callee, "expected 'callee' here") || 8936 parseToken(lltok::colon, "expected ':' here")) 8937 return true; 8938 8939 unsigned GVId; 8940 ValueInfo VI; 8941 LocTy Loc = Lex.getLoc(); 8942 if (parseGVReference(VI, GVId)) 8943 return true; 8944 8945 Call.Callee = VI; 8946 IdLocList.emplace_back(GVId, Loc); 8947 8948 if (parseToken(lltok::comma, "expected ',' here") || 8949 parseParamNo(Call.ParamNo) || 8950 parseToken(lltok::comma, "expected ',' here") || 8951 parseParamAccessOffset(Call.Offsets)) 8952 return true; 8953 8954 if (parseToken(lltok::rparen, "expected ')' here")) 8955 return true; 8956 8957 return false; 8958 } 8959 8960 /// ParamAccess 8961 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8962 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8963 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 8964 IdLocListType &IdLocList) { 8965 if (parseToken(lltok::lparen, "expected '(' here") || 8966 parseParamNo(Param.ParamNo) || 8967 parseToken(lltok::comma, "expected ',' here") || 8968 parseParamAccessOffset(Param.Use)) 8969 return true; 8970 8971 if (EatIfPresent(lltok::comma)) { 8972 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 8973 parseToken(lltok::colon, "expected ':' here") || 8974 parseToken(lltok::lparen, "expected '(' here")) 8975 return true; 8976 do { 8977 FunctionSummary::ParamAccess::Call Call; 8978 if (parseParamAccessCall(Call, IdLocList)) 8979 return true; 8980 Param.Calls.push_back(Call); 8981 } while (EatIfPresent(lltok::comma)); 8982 8983 if (parseToken(lltok::rparen, "expected ')' here")) 8984 return true; 8985 } 8986 8987 if (parseToken(lltok::rparen, "expected ')' here")) 8988 return true; 8989 8990 return false; 8991 } 8992 8993 /// OptionalParamAccesses 8994 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8995 bool LLParser::parseOptionalParamAccesses( 8996 std::vector<FunctionSummary::ParamAccess> &Params) { 8997 assert(Lex.getKind() == lltok::kw_params); 8998 Lex.Lex(); 8999 9000 if (parseToken(lltok::colon, "expected ':' here") || 9001 parseToken(lltok::lparen, "expected '(' here")) 9002 return true; 9003 9004 IdLocListType VContexts; 9005 size_t CallsNum = 0; 9006 do { 9007 FunctionSummary::ParamAccess ParamAccess; 9008 if (parseParamAccess(ParamAccess, VContexts)) 9009 return true; 9010 CallsNum += ParamAccess.Calls.size(); 9011 assert(VContexts.size() == CallsNum); 9012 Params.emplace_back(std::move(ParamAccess)); 9013 } while (EatIfPresent(lltok::comma)); 9014 9015 if (parseToken(lltok::rparen, "expected ')' here")) 9016 return true; 9017 9018 // Now that the Params is finalized, it is safe to save the locations 9019 // of any forward GV references that need updating later. 9020 IdLocListType::const_iterator ItContext = VContexts.begin(); 9021 for (auto &PA : Params) { 9022 for (auto &C : PA.Calls) { 9023 if (C.Callee.getRef() == FwdVIRef) 9024 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 9025 ItContext->second); 9026 ++ItContext; 9027 } 9028 } 9029 assert(ItContext == VContexts.end()); 9030 9031 return false; 9032 } 9033 9034 /// OptionalRefs 9035 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 9036 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) { 9037 assert(Lex.getKind() == lltok::kw_refs); 9038 Lex.Lex(); 9039 9040 if (parseToken(lltok::colon, "expected ':' in refs") || 9041 parseToken(lltok::lparen, "expected '(' in refs")) 9042 return true; 9043 9044 struct ValueContext { 9045 ValueInfo VI; 9046 unsigned GVId; 9047 LocTy Loc; 9048 }; 9049 std::vector<ValueContext> VContexts; 9050 // parse each ref edge 9051 do { 9052 ValueContext VC; 9053 VC.Loc = Lex.getLoc(); 9054 if (parseGVReference(VC.VI, VC.GVId)) 9055 return true; 9056 VContexts.push_back(VC); 9057 } while (EatIfPresent(lltok::comma)); 9058 9059 // Sort value contexts so that ones with writeonly 9060 // and readonly ValueInfo are at the end of VContexts vector. 9061 // See FunctionSummary::specialRefCounts() 9062 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 9063 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 9064 }); 9065 9066 IdToIndexMapType IdToIndexMap; 9067 for (auto &VC : VContexts) { 9068 // Keep track of the Refs array index needing a forward reference. 9069 // We will save the location of the ValueInfo needing an update, but 9070 // can only do so once the std::vector is finalized. 9071 if (VC.VI.getRef() == FwdVIRef) 9072 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 9073 Refs.push_back(VC.VI); 9074 } 9075 9076 // Now that the Refs vector is finalized, it is safe to save the locations 9077 // of any forward GV references that need updating later. 9078 for (auto I : IdToIndexMap) { 9079 auto &Infos = ForwardRefValueInfos[I.first]; 9080 for (auto P : I.second) { 9081 assert(Refs[P.first].getRef() == FwdVIRef && 9082 "Forward referenced ValueInfo expected to be empty"); 9083 Infos.emplace_back(&Refs[P.first], P.second); 9084 } 9085 } 9086 9087 if (parseToken(lltok::rparen, "expected ')' in refs")) 9088 return true; 9089 9090 return false; 9091 } 9092 9093 /// OptionalTypeIdInfo 9094 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 9095 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 9096 /// [',' TypeCheckedLoadConstVCalls]? ')' 9097 bool LLParser::parseOptionalTypeIdInfo( 9098 FunctionSummary::TypeIdInfo &TypeIdInfo) { 9099 assert(Lex.getKind() == lltok::kw_typeIdInfo); 9100 Lex.Lex(); 9101 9102 if (parseToken(lltok::colon, "expected ':' here") || 9103 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9104 return true; 9105 9106 do { 9107 switch (Lex.getKind()) { 9108 case lltok::kw_typeTests: 9109 if (parseTypeTests(TypeIdInfo.TypeTests)) 9110 return true; 9111 break; 9112 case lltok::kw_typeTestAssumeVCalls: 9113 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 9114 TypeIdInfo.TypeTestAssumeVCalls)) 9115 return true; 9116 break; 9117 case lltok::kw_typeCheckedLoadVCalls: 9118 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 9119 TypeIdInfo.TypeCheckedLoadVCalls)) 9120 return true; 9121 break; 9122 case lltok::kw_typeTestAssumeConstVCalls: 9123 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 9124 TypeIdInfo.TypeTestAssumeConstVCalls)) 9125 return true; 9126 break; 9127 case lltok::kw_typeCheckedLoadConstVCalls: 9128 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 9129 TypeIdInfo.TypeCheckedLoadConstVCalls)) 9130 return true; 9131 break; 9132 default: 9133 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 9134 } 9135 } while (EatIfPresent(lltok::comma)); 9136 9137 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9138 return true; 9139 9140 return false; 9141 } 9142 9143 /// TypeTests 9144 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 9145 /// [',' (SummaryID | UInt64)]* ')' 9146 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 9147 assert(Lex.getKind() == lltok::kw_typeTests); 9148 Lex.Lex(); 9149 9150 if (parseToken(lltok::colon, "expected ':' here") || 9151 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9152 return true; 9153 9154 IdToIndexMapType IdToIndexMap; 9155 do { 9156 GlobalValue::GUID GUID = 0; 9157 if (Lex.getKind() == lltok::SummaryID) { 9158 unsigned ID = Lex.getUIntVal(); 9159 LocTy Loc = Lex.getLoc(); 9160 // Keep track of the TypeTests array index needing a forward reference. 9161 // We will save the location of the GUID needing an update, but 9162 // can only do so once the std::vector is finalized. 9163 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 9164 Lex.Lex(); 9165 } else if (parseUInt64(GUID)) 9166 return true; 9167 TypeTests.push_back(GUID); 9168 } while (EatIfPresent(lltok::comma)); 9169 9170 // Now that the TypeTests vector is finalized, it is safe to save the 9171 // locations of any forward GV references that need updating later. 9172 for (auto I : IdToIndexMap) { 9173 auto &Ids = ForwardRefTypeIds[I.first]; 9174 for (auto P : I.second) { 9175 assert(TypeTests[P.first] == 0 && 9176 "Forward referenced type id GUID expected to be 0"); 9177 Ids.emplace_back(&TypeTests[P.first], P.second); 9178 } 9179 } 9180 9181 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9182 return true; 9183 9184 return false; 9185 } 9186 9187 /// VFuncIdList 9188 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 9189 bool LLParser::parseVFuncIdList( 9190 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 9191 assert(Lex.getKind() == Kind); 9192 Lex.Lex(); 9193 9194 if (parseToken(lltok::colon, "expected ':' here") || 9195 parseToken(lltok::lparen, "expected '(' here")) 9196 return true; 9197 9198 IdToIndexMapType IdToIndexMap; 9199 do { 9200 FunctionSummary::VFuncId VFuncId; 9201 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 9202 return true; 9203 VFuncIdList.push_back(VFuncId); 9204 } while (EatIfPresent(lltok::comma)); 9205 9206 if (parseToken(lltok::rparen, "expected ')' here")) 9207 return true; 9208 9209 // Now that the VFuncIdList vector is finalized, it is safe to save the 9210 // locations of any forward GV references that need updating later. 9211 for (auto I : IdToIndexMap) { 9212 auto &Ids = ForwardRefTypeIds[I.first]; 9213 for (auto P : I.second) { 9214 assert(VFuncIdList[P.first].GUID == 0 && 9215 "Forward referenced type id GUID expected to be 0"); 9216 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 9217 } 9218 } 9219 9220 return false; 9221 } 9222 9223 /// ConstVCallList 9224 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 9225 bool LLParser::parseConstVCallList( 9226 lltok::Kind Kind, 9227 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 9228 assert(Lex.getKind() == Kind); 9229 Lex.Lex(); 9230 9231 if (parseToken(lltok::colon, "expected ':' here") || 9232 parseToken(lltok::lparen, "expected '(' here")) 9233 return true; 9234 9235 IdToIndexMapType IdToIndexMap; 9236 do { 9237 FunctionSummary::ConstVCall ConstVCall; 9238 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 9239 return true; 9240 ConstVCallList.push_back(ConstVCall); 9241 } while (EatIfPresent(lltok::comma)); 9242 9243 if (parseToken(lltok::rparen, "expected ')' here")) 9244 return true; 9245 9246 // Now that the ConstVCallList vector is finalized, it is safe to save the 9247 // locations of any forward GV references that need updating later. 9248 for (auto I : IdToIndexMap) { 9249 auto &Ids = ForwardRefTypeIds[I.first]; 9250 for (auto P : I.second) { 9251 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 9252 "Forward referenced type id GUID expected to be 0"); 9253 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 9254 } 9255 } 9256 9257 return false; 9258 } 9259 9260 /// ConstVCall 9261 /// ::= '(' VFuncId ',' Args ')' 9262 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 9263 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9264 if (parseToken(lltok::lparen, "expected '(' here") || 9265 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 9266 return true; 9267 9268 if (EatIfPresent(lltok::comma)) 9269 if (parseArgs(ConstVCall.Args)) 9270 return true; 9271 9272 if (parseToken(lltok::rparen, "expected ')' here")) 9273 return true; 9274 9275 return false; 9276 } 9277 9278 /// VFuncId 9279 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9280 /// 'offset' ':' UInt64 ')' 9281 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 9282 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9283 assert(Lex.getKind() == lltok::kw_vFuncId); 9284 Lex.Lex(); 9285 9286 if (parseToken(lltok::colon, "expected ':' here") || 9287 parseToken(lltok::lparen, "expected '(' here")) 9288 return true; 9289 9290 if (Lex.getKind() == lltok::SummaryID) { 9291 VFuncId.GUID = 0; 9292 unsigned ID = Lex.getUIntVal(); 9293 LocTy Loc = Lex.getLoc(); 9294 // Keep track of the array index needing a forward reference. 9295 // We will save the location of the GUID needing an update, but 9296 // can only do so once the caller's std::vector is finalized. 9297 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9298 Lex.Lex(); 9299 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 9300 parseToken(lltok::colon, "expected ':' here") || 9301 parseUInt64(VFuncId.GUID)) 9302 return true; 9303 9304 if (parseToken(lltok::comma, "expected ',' here") || 9305 parseToken(lltok::kw_offset, "expected 'offset' here") || 9306 parseToken(lltok::colon, "expected ':' here") || 9307 parseUInt64(VFuncId.Offset) || 9308 parseToken(lltok::rparen, "expected ')' here")) 9309 return true; 9310 9311 return false; 9312 } 9313 9314 /// GVFlags 9315 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9316 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ',' 9317 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')' 9318 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9319 assert(Lex.getKind() == lltok::kw_flags); 9320 Lex.Lex(); 9321 9322 if (parseToken(lltok::colon, "expected ':' here") || 9323 parseToken(lltok::lparen, "expected '(' here")) 9324 return true; 9325 9326 do { 9327 unsigned Flag = 0; 9328 switch (Lex.getKind()) { 9329 case lltok::kw_linkage: 9330 Lex.Lex(); 9331 if (parseToken(lltok::colon, "expected ':'")) 9332 return true; 9333 bool HasLinkage; 9334 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9335 assert(HasLinkage && "Linkage not optional in summary entry"); 9336 Lex.Lex(); 9337 break; 9338 case lltok::kw_notEligibleToImport: 9339 Lex.Lex(); 9340 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9341 return true; 9342 GVFlags.NotEligibleToImport = Flag; 9343 break; 9344 case lltok::kw_live: 9345 Lex.Lex(); 9346 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9347 return true; 9348 GVFlags.Live = Flag; 9349 break; 9350 case lltok::kw_dsoLocal: 9351 Lex.Lex(); 9352 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9353 return true; 9354 GVFlags.DSOLocal = Flag; 9355 break; 9356 case lltok::kw_canAutoHide: 9357 Lex.Lex(); 9358 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9359 return true; 9360 GVFlags.CanAutoHide = Flag; 9361 break; 9362 default: 9363 return error(Lex.getLoc(), "expected gv flag type"); 9364 } 9365 } while (EatIfPresent(lltok::comma)); 9366 9367 if (parseToken(lltok::rparen, "expected ')' here")) 9368 return true; 9369 9370 return false; 9371 } 9372 9373 /// GVarFlags 9374 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9375 /// ',' 'writeonly' ':' Flag 9376 /// ',' 'constant' ':' Flag ')' 9377 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9378 assert(Lex.getKind() == lltok::kw_varFlags); 9379 Lex.Lex(); 9380 9381 if (parseToken(lltok::colon, "expected ':' here") || 9382 parseToken(lltok::lparen, "expected '(' here")) 9383 return true; 9384 9385 auto ParseRest = [this](unsigned int &Val) { 9386 Lex.Lex(); 9387 if (parseToken(lltok::colon, "expected ':'")) 9388 return true; 9389 return parseFlag(Val); 9390 }; 9391 9392 do { 9393 unsigned Flag = 0; 9394 switch (Lex.getKind()) { 9395 case lltok::kw_readonly: 9396 if (ParseRest(Flag)) 9397 return true; 9398 GVarFlags.MaybeReadOnly = Flag; 9399 break; 9400 case lltok::kw_writeonly: 9401 if (ParseRest(Flag)) 9402 return true; 9403 GVarFlags.MaybeWriteOnly = Flag; 9404 break; 9405 case lltok::kw_constant: 9406 if (ParseRest(Flag)) 9407 return true; 9408 GVarFlags.Constant = Flag; 9409 break; 9410 case lltok::kw_vcall_visibility: 9411 if (ParseRest(Flag)) 9412 return true; 9413 GVarFlags.VCallVisibility = Flag; 9414 break; 9415 default: 9416 return error(Lex.getLoc(), "expected gvar flag type"); 9417 } 9418 } while (EatIfPresent(lltok::comma)); 9419 return parseToken(lltok::rparen, "expected ')' here"); 9420 } 9421 9422 /// ModuleReference 9423 /// ::= 'module' ':' UInt 9424 bool LLParser::parseModuleReference(StringRef &ModulePath) { 9425 // parse module id. 9426 if (parseToken(lltok::kw_module, "expected 'module' here") || 9427 parseToken(lltok::colon, "expected ':' here") || 9428 parseToken(lltok::SummaryID, "expected module ID")) 9429 return true; 9430 9431 unsigned ModuleID = Lex.getUIntVal(); 9432 auto I = ModuleIdMap.find(ModuleID); 9433 // We should have already parsed all module IDs 9434 assert(I != ModuleIdMap.end()); 9435 ModulePath = I->second; 9436 return false; 9437 } 9438 9439 /// GVReference 9440 /// ::= SummaryID 9441 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 9442 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9443 if (!ReadOnly) 9444 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9445 if (parseToken(lltok::SummaryID, "expected GV ID")) 9446 return true; 9447 9448 GVId = Lex.getUIntVal(); 9449 // Check if we already have a VI for this GV 9450 if (GVId < NumberedValueInfos.size()) { 9451 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9452 VI = NumberedValueInfos[GVId]; 9453 } else 9454 // We will create a forward reference to the stored location. 9455 VI = ValueInfo(false, FwdVIRef); 9456 9457 if (ReadOnly) 9458 VI.setReadOnly(); 9459 if (WriteOnly) 9460 VI.setWriteOnly(); 9461 return false; 9462 } 9463