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_ls: CC = CallingConv::AMDGPU_LS; break; 2138 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; 2139 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break; 2140 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; 2141 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; 2142 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; 2143 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; 2144 case lltok::kw_tailcc: CC = CallingConv::Tail; break; 2145 case lltok::kw_cc: { 2146 Lex.Lex(); 2147 return parseUInt32(CC); 2148 } 2149 } 2150 2151 Lex.Lex(); 2152 return false; 2153 } 2154 2155 /// parseMetadataAttachment 2156 /// ::= !dbg !42 2157 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) { 2158 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"); 2159 2160 std::string Name = Lex.getStrVal(); 2161 Kind = M->getMDKindID(Name); 2162 Lex.Lex(); 2163 2164 return parseMDNode(MD); 2165 } 2166 2167 /// parseInstructionMetadata 2168 /// ::= !dbg !42 (',' !dbg !57)* 2169 bool LLParser::parseInstructionMetadata(Instruction &Inst) { 2170 do { 2171 if (Lex.getKind() != lltok::MetadataVar) 2172 return tokError("expected metadata after comma"); 2173 2174 unsigned MDK; 2175 MDNode *N; 2176 if (parseMetadataAttachment(MDK, N)) 2177 return true; 2178 2179 Inst.setMetadata(MDK, N); 2180 if (MDK == LLVMContext::MD_tbaa) 2181 InstsWithTBAATag.push_back(&Inst); 2182 2183 // If this is the end of the list, we're done. 2184 } while (EatIfPresent(lltok::comma)); 2185 return false; 2186 } 2187 2188 /// parseGlobalObjectMetadataAttachment 2189 /// ::= !dbg !57 2190 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) { 2191 unsigned MDK; 2192 MDNode *N; 2193 if (parseMetadataAttachment(MDK, N)) 2194 return true; 2195 2196 GO.addMetadata(MDK, *N); 2197 return false; 2198 } 2199 2200 /// parseOptionalFunctionMetadata 2201 /// ::= (!dbg !57)* 2202 bool LLParser::parseOptionalFunctionMetadata(Function &F) { 2203 while (Lex.getKind() == lltok::MetadataVar) 2204 if (parseGlobalObjectMetadataAttachment(F)) 2205 return true; 2206 return false; 2207 } 2208 2209 /// parseOptionalAlignment 2210 /// ::= /* empty */ 2211 /// ::= 'align' 4 2212 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) { 2213 Alignment = None; 2214 if (!EatIfPresent(lltok::kw_align)) 2215 return false; 2216 LocTy AlignLoc = Lex.getLoc(); 2217 uint32_t Value = 0; 2218 2219 LocTy ParenLoc = Lex.getLoc(); 2220 bool HaveParens = false; 2221 if (AllowParens) { 2222 if (EatIfPresent(lltok::lparen)) 2223 HaveParens = true; 2224 } 2225 2226 if (parseUInt32(Value)) 2227 return true; 2228 2229 if (HaveParens && !EatIfPresent(lltok::rparen)) 2230 return error(ParenLoc, "expected ')'"); 2231 2232 if (!isPowerOf2_32(Value)) 2233 return error(AlignLoc, "alignment is not a power of two"); 2234 if (Value > Value::MaximumAlignment) 2235 return error(AlignLoc, "huge alignments are not supported yet"); 2236 Alignment = Align(Value); 2237 return false; 2238 } 2239 2240 /// parseOptionalDerefAttrBytes 2241 /// ::= /* empty */ 2242 /// ::= AttrKind '(' 4 ')' 2243 /// 2244 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'. 2245 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind, 2246 uint64_t &Bytes) { 2247 assert((AttrKind == lltok::kw_dereferenceable || 2248 AttrKind == lltok::kw_dereferenceable_or_null) && 2249 "contract!"); 2250 2251 Bytes = 0; 2252 if (!EatIfPresent(AttrKind)) 2253 return false; 2254 LocTy ParenLoc = Lex.getLoc(); 2255 if (!EatIfPresent(lltok::lparen)) 2256 return error(ParenLoc, "expected '('"); 2257 LocTy DerefLoc = Lex.getLoc(); 2258 if (parseUInt64(Bytes)) 2259 return true; 2260 ParenLoc = Lex.getLoc(); 2261 if (!EatIfPresent(lltok::rparen)) 2262 return error(ParenLoc, "expected ')'"); 2263 if (!Bytes) 2264 return error(DerefLoc, "dereferenceable bytes must be non-zero"); 2265 return false; 2266 } 2267 2268 /// parseOptionalCommaAlign 2269 /// ::= 2270 /// ::= ',' align 4 2271 /// 2272 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2273 /// end. 2274 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment, 2275 bool &AteExtraComma) { 2276 AteExtraComma = false; 2277 while (EatIfPresent(lltok::comma)) { 2278 // Metadata at the end is an early exit. 2279 if (Lex.getKind() == lltok::MetadataVar) { 2280 AteExtraComma = true; 2281 return false; 2282 } 2283 2284 if (Lex.getKind() != lltok::kw_align) 2285 return error(Lex.getLoc(), "expected metadata or 'align'"); 2286 2287 if (parseOptionalAlignment(Alignment)) 2288 return true; 2289 } 2290 2291 return false; 2292 } 2293 2294 /// parseOptionalCommaAddrSpace 2295 /// ::= 2296 /// ::= ',' addrspace(1) 2297 /// 2298 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2299 /// end. 2300 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc, 2301 bool &AteExtraComma) { 2302 AteExtraComma = false; 2303 while (EatIfPresent(lltok::comma)) { 2304 // Metadata at the end is an early exit. 2305 if (Lex.getKind() == lltok::MetadataVar) { 2306 AteExtraComma = true; 2307 return false; 2308 } 2309 2310 Loc = Lex.getLoc(); 2311 if (Lex.getKind() != lltok::kw_addrspace) 2312 return error(Lex.getLoc(), "expected metadata or 'addrspace'"); 2313 2314 if (parseOptionalAddrSpace(AddrSpace)) 2315 return true; 2316 } 2317 2318 return false; 2319 } 2320 2321 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, 2322 Optional<unsigned> &HowManyArg) { 2323 Lex.Lex(); 2324 2325 auto StartParen = Lex.getLoc(); 2326 if (!EatIfPresent(lltok::lparen)) 2327 return error(StartParen, "expected '('"); 2328 2329 if (parseUInt32(BaseSizeArg)) 2330 return true; 2331 2332 if (EatIfPresent(lltok::comma)) { 2333 auto HowManyAt = Lex.getLoc(); 2334 unsigned HowMany; 2335 if (parseUInt32(HowMany)) 2336 return true; 2337 if (HowMany == BaseSizeArg) 2338 return error(HowManyAt, 2339 "'allocsize' indices can't refer to the same parameter"); 2340 HowManyArg = HowMany; 2341 } else 2342 HowManyArg = None; 2343 2344 auto EndParen = Lex.getLoc(); 2345 if (!EatIfPresent(lltok::rparen)) 2346 return error(EndParen, "expected ')'"); 2347 return false; 2348 } 2349 2350 /// parseScopeAndOrdering 2351 /// if isAtomic: ::= SyncScope? AtomicOrdering 2352 /// else: ::= 2353 /// 2354 /// This sets Scope and Ordering to the parsed values. 2355 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID, 2356 AtomicOrdering &Ordering) { 2357 if (!IsAtomic) 2358 return false; 2359 2360 return parseScope(SSID) || parseOrdering(Ordering); 2361 } 2362 2363 /// parseScope 2364 /// ::= syncscope("singlethread" | "<target scope>")? 2365 /// 2366 /// This sets synchronization scope ID to the ID of the parsed value. 2367 bool LLParser::parseScope(SyncScope::ID &SSID) { 2368 SSID = SyncScope::System; 2369 if (EatIfPresent(lltok::kw_syncscope)) { 2370 auto StartParenAt = Lex.getLoc(); 2371 if (!EatIfPresent(lltok::lparen)) 2372 return error(StartParenAt, "Expected '(' in syncscope"); 2373 2374 std::string SSN; 2375 auto SSNAt = Lex.getLoc(); 2376 if (parseStringConstant(SSN)) 2377 return error(SSNAt, "Expected synchronization scope name"); 2378 2379 auto EndParenAt = Lex.getLoc(); 2380 if (!EatIfPresent(lltok::rparen)) 2381 return error(EndParenAt, "Expected ')' in syncscope"); 2382 2383 SSID = Context.getOrInsertSyncScopeID(SSN); 2384 } 2385 2386 return false; 2387 } 2388 2389 /// parseOrdering 2390 /// ::= AtomicOrdering 2391 /// 2392 /// This sets Ordering to the parsed value. 2393 bool LLParser::parseOrdering(AtomicOrdering &Ordering) { 2394 switch (Lex.getKind()) { 2395 default: 2396 return tokError("Expected ordering on atomic instruction"); 2397 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; 2398 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; 2399 // Not specified yet: 2400 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; 2401 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; 2402 case lltok::kw_release: Ordering = AtomicOrdering::Release; break; 2403 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; 2404 case lltok::kw_seq_cst: 2405 Ordering = AtomicOrdering::SequentiallyConsistent; 2406 break; 2407 } 2408 Lex.Lex(); 2409 return false; 2410 } 2411 2412 /// parseOptionalStackAlignment 2413 /// ::= /* empty */ 2414 /// ::= 'alignstack' '(' 4 ')' 2415 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) { 2416 Alignment = 0; 2417 if (!EatIfPresent(lltok::kw_alignstack)) 2418 return false; 2419 LocTy ParenLoc = Lex.getLoc(); 2420 if (!EatIfPresent(lltok::lparen)) 2421 return error(ParenLoc, "expected '('"); 2422 LocTy AlignLoc = Lex.getLoc(); 2423 if (parseUInt32(Alignment)) 2424 return true; 2425 ParenLoc = Lex.getLoc(); 2426 if (!EatIfPresent(lltok::rparen)) 2427 return error(ParenLoc, "expected ')'"); 2428 if (!isPowerOf2_32(Alignment)) 2429 return error(AlignLoc, "stack alignment is not a power of two"); 2430 return false; 2431 } 2432 2433 /// parseIndexList - This parses the index list for an insert/extractvalue 2434 /// instruction. This sets AteExtraComma in the case where we eat an extra 2435 /// comma at the end of the line and find that it is followed by metadata. 2436 /// Clients that don't allow metadata can call the version of this function that 2437 /// only takes one argument. 2438 /// 2439 /// parseIndexList 2440 /// ::= (',' uint32)+ 2441 /// 2442 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices, 2443 bool &AteExtraComma) { 2444 AteExtraComma = false; 2445 2446 if (Lex.getKind() != lltok::comma) 2447 return tokError("expected ',' as start of index list"); 2448 2449 while (EatIfPresent(lltok::comma)) { 2450 if (Lex.getKind() == lltok::MetadataVar) { 2451 if (Indices.empty()) 2452 return tokError("expected index"); 2453 AteExtraComma = true; 2454 return false; 2455 } 2456 unsigned Idx = 0; 2457 if (parseUInt32(Idx)) 2458 return true; 2459 Indices.push_back(Idx); 2460 } 2461 2462 return false; 2463 } 2464 2465 //===----------------------------------------------------------------------===// 2466 // Type Parsing. 2467 //===----------------------------------------------------------------------===// 2468 2469 /// parseType - parse a type. 2470 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) { 2471 SMLoc TypeLoc = Lex.getLoc(); 2472 switch (Lex.getKind()) { 2473 default: 2474 return tokError(Msg); 2475 case lltok::Type: 2476 // Type ::= 'float' | 'void' (etc) 2477 Result = Lex.getTyVal(); 2478 Lex.Lex(); 2479 break; 2480 case lltok::lbrace: 2481 // Type ::= StructType 2482 if (parseAnonStructType(Result, false)) 2483 return true; 2484 break; 2485 case lltok::lsquare: 2486 // Type ::= '[' ... ']' 2487 Lex.Lex(); // eat the lsquare. 2488 if (parseArrayVectorType(Result, false)) 2489 return true; 2490 break; 2491 case lltok::less: // Either vector or packed struct. 2492 // Type ::= '<' ... '>' 2493 Lex.Lex(); 2494 if (Lex.getKind() == lltok::lbrace) { 2495 if (parseAnonStructType(Result, true) || 2496 parseToken(lltok::greater, "expected '>' at end of packed struct")) 2497 return true; 2498 } else if (parseArrayVectorType(Result, true)) 2499 return true; 2500 break; 2501 case lltok::LocalVar: { 2502 // Type ::= %foo 2503 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 2504 2505 // If the type hasn't been defined yet, create a forward definition and 2506 // remember where that forward def'n was seen (in case it never is defined). 2507 if (!Entry.first) { 2508 Entry.first = StructType::create(Context, Lex.getStrVal()); 2509 Entry.second = Lex.getLoc(); 2510 } 2511 Result = Entry.first; 2512 Lex.Lex(); 2513 break; 2514 } 2515 2516 case lltok::LocalVarID: { 2517 // Type ::= %4 2518 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 2519 2520 // If the type hasn't been defined yet, create a forward definition and 2521 // remember where that forward def'n was seen (in case it never is defined). 2522 if (!Entry.first) { 2523 Entry.first = StructType::create(Context); 2524 Entry.second = Lex.getLoc(); 2525 } 2526 Result = Entry.first; 2527 Lex.Lex(); 2528 break; 2529 } 2530 } 2531 2532 // parse the type suffixes. 2533 while (true) { 2534 switch (Lex.getKind()) { 2535 // End of type. 2536 default: 2537 if (!AllowVoid && Result->isVoidTy()) 2538 return error(TypeLoc, "void type only allowed for function results"); 2539 return false; 2540 2541 // Type ::= Type '*' 2542 case lltok::star: 2543 if (Result->isLabelTy()) 2544 return tokError("basic block pointers are invalid"); 2545 if (Result->isVoidTy()) 2546 return tokError("pointers to void are invalid - use i8* instead"); 2547 if (!PointerType::isValidElementType(Result)) 2548 return tokError("pointer to this type is invalid"); 2549 Result = PointerType::getUnqual(Result); 2550 Lex.Lex(); 2551 break; 2552 2553 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 2554 case lltok::kw_addrspace: { 2555 if (Result->isLabelTy()) 2556 return tokError("basic block pointers are invalid"); 2557 if (Result->isVoidTy()) 2558 return tokError("pointers to void are invalid; use i8* instead"); 2559 if (!PointerType::isValidElementType(Result)) 2560 return tokError("pointer to this type is invalid"); 2561 unsigned AddrSpace; 2562 if (parseOptionalAddrSpace(AddrSpace) || 2563 parseToken(lltok::star, "expected '*' in address space")) 2564 return true; 2565 2566 Result = PointerType::get(Result, AddrSpace); 2567 break; 2568 } 2569 2570 /// Types '(' ArgTypeListI ')' OptFuncAttrs 2571 case lltok::lparen: 2572 if (parseFunctionType(Result)) 2573 return true; 2574 break; 2575 } 2576 } 2577 } 2578 2579 /// parseParameterList 2580 /// ::= '(' ')' 2581 /// ::= '(' Arg (',' Arg)* ')' 2582 /// Arg 2583 /// ::= Type OptionalAttributes Value OptionalAttributes 2584 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 2585 PerFunctionState &PFS, bool IsMustTailCall, 2586 bool InVarArgsFunc) { 2587 if (parseToken(lltok::lparen, "expected '(' in call")) 2588 return true; 2589 2590 while (Lex.getKind() != lltok::rparen) { 2591 // If this isn't the first argument, we need a comma. 2592 if (!ArgList.empty() && 2593 parseToken(lltok::comma, "expected ',' in argument list")) 2594 return true; 2595 2596 // parse an ellipsis if this is a musttail call in a variadic function. 2597 if (Lex.getKind() == lltok::dotdotdot) { 2598 const char *Msg = "unexpected ellipsis in argument list for "; 2599 if (!IsMustTailCall) 2600 return tokError(Twine(Msg) + "non-musttail call"); 2601 if (!InVarArgsFunc) 2602 return tokError(Twine(Msg) + "musttail call in non-varargs function"); 2603 Lex.Lex(); // Lex the '...', it is purely for readability. 2604 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2605 } 2606 2607 // parse the argument. 2608 LocTy ArgLoc; 2609 Type *ArgTy = nullptr; 2610 AttrBuilder ArgAttrs; 2611 Value *V; 2612 if (parseType(ArgTy, ArgLoc)) 2613 return true; 2614 2615 if (ArgTy->isMetadataTy()) { 2616 if (parseMetadataAsValue(V, PFS)) 2617 return true; 2618 } else { 2619 // Otherwise, handle normal operands. 2620 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS)) 2621 return true; 2622 } 2623 ArgList.push_back(ParamInfo( 2624 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs))); 2625 } 2626 2627 if (IsMustTailCall && InVarArgsFunc) 2628 return tokError("expected '...' at end of argument list for musttail call " 2629 "in varargs function"); 2630 2631 Lex.Lex(); // Lex the ')'. 2632 return false; 2633 } 2634 2635 /// parseByValWithOptionalType 2636 /// ::= byval 2637 /// ::= byval(<ty>) 2638 bool LLParser::parseOptionalTypeAttr(Type *&Result, lltok::Kind AttrName) { 2639 Result = nullptr; 2640 if (!EatIfPresent(AttrName)) 2641 return true; 2642 if (!EatIfPresent(lltok::lparen)) 2643 return false; 2644 if (parseType(Result)) 2645 return true; 2646 if (!EatIfPresent(lltok::rparen)) 2647 return error(Lex.getLoc(), "expected ')'"); 2648 return false; 2649 } 2650 2651 /// parseRequiredTypeAttr 2652 /// ::= attrname(<ty>) 2653 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) { 2654 Result = nullptr; 2655 if (!EatIfPresent(AttrName)) 2656 return true; 2657 if (!EatIfPresent(lltok::lparen)) 2658 return error(Lex.getLoc(), "expected '('"); 2659 if (parseType(Result)) 2660 return true; 2661 if (!EatIfPresent(lltok::rparen)) 2662 return error(Lex.getLoc(), "expected ')'"); 2663 return false; 2664 } 2665 2666 /// parsePreallocated 2667 /// ::= preallocated(<ty>) 2668 bool LLParser::parsePreallocated(Type *&Result) { 2669 return parseRequiredTypeAttr(Result, lltok::kw_preallocated); 2670 } 2671 2672 /// parseByRef 2673 /// ::= byref(<type>) 2674 bool LLParser::parseByRef(Type *&Result) { 2675 return parseRequiredTypeAttr(Result, lltok::kw_byref); 2676 } 2677 2678 /// parseOptionalOperandBundles 2679 /// ::= /*empty*/ 2680 /// ::= '[' OperandBundle [, OperandBundle ]* ']' 2681 /// 2682 /// OperandBundle 2683 /// ::= bundle-tag '(' ')' 2684 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' 2685 /// 2686 /// bundle-tag ::= String Constant 2687 bool LLParser::parseOptionalOperandBundles( 2688 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { 2689 LocTy BeginLoc = Lex.getLoc(); 2690 if (!EatIfPresent(lltok::lsquare)) 2691 return false; 2692 2693 while (Lex.getKind() != lltok::rsquare) { 2694 // If this isn't the first operand bundle, we need a comma. 2695 if (!BundleList.empty() && 2696 parseToken(lltok::comma, "expected ',' in input list")) 2697 return true; 2698 2699 std::string Tag; 2700 if (parseStringConstant(Tag)) 2701 return true; 2702 2703 if (parseToken(lltok::lparen, "expected '(' in operand bundle")) 2704 return true; 2705 2706 std::vector<Value *> Inputs; 2707 while (Lex.getKind() != lltok::rparen) { 2708 // If this isn't the first input, we need a comma. 2709 if (!Inputs.empty() && 2710 parseToken(lltok::comma, "expected ',' in input list")) 2711 return true; 2712 2713 Type *Ty = nullptr; 2714 Value *Input = nullptr; 2715 if (parseType(Ty) || parseValue(Ty, Input, PFS)) 2716 return true; 2717 Inputs.push_back(Input); 2718 } 2719 2720 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 2721 2722 Lex.Lex(); // Lex the ')'. 2723 } 2724 2725 if (BundleList.empty()) 2726 return error(BeginLoc, "operand bundle set must not be empty"); 2727 2728 Lex.Lex(); // Lex the ']'. 2729 return false; 2730 } 2731 2732 /// parseArgumentList - parse the argument list for a function type or function 2733 /// prototype. 2734 /// ::= '(' ArgTypeListI ')' 2735 /// ArgTypeListI 2736 /// ::= /*empty*/ 2737 /// ::= '...' 2738 /// ::= ArgTypeList ',' '...' 2739 /// ::= ArgType (',' ArgType)* 2740 /// 2741 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 2742 bool &IsVarArg) { 2743 unsigned CurValID = 0; 2744 IsVarArg = false; 2745 assert(Lex.getKind() == lltok::lparen); 2746 Lex.Lex(); // eat the (. 2747 2748 if (Lex.getKind() == lltok::rparen) { 2749 // empty 2750 } else if (Lex.getKind() == lltok::dotdotdot) { 2751 IsVarArg = true; 2752 Lex.Lex(); 2753 } else { 2754 LocTy TypeLoc = Lex.getLoc(); 2755 Type *ArgTy = nullptr; 2756 AttrBuilder Attrs; 2757 std::string Name; 2758 2759 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2760 return true; 2761 2762 if (ArgTy->isVoidTy()) 2763 return error(TypeLoc, "argument can not have void type"); 2764 2765 if (Lex.getKind() == lltok::LocalVar) { 2766 Name = Lex.getStrVal(); 2767 Lex.Lex(); 2768 } else if (Lex.getKind() == lltok::LocalVarID) { 2769 if (Lex.getUIntVal() != CurValID) 2770 return error(TypeLoc, "argument expected to be numbered '%" + 2771 Twine(CurValID) + "'"); 2772 ++CurValID; 2773 Lex.Lex(); 2774 } 2775 2776 if (!FunctionType::isValidArgumentType(ArgTy)) 2777 return error(TypeLoc, "invalid type for function argument"); 2778 2779 ArgList.emplace_back(TypeLoc, ArgTy, 2780 AttributeSet::get(ArgTy->getContext(), Attrs), 2781 std::move(Name)); 2782 2783 while (EatIfPresent(lltok::comma)) { 2784 // Handle ... at end of arg list. 2785 if (EatIfPresent(lltok::dotdotdot)) { 2786 IsVarArg = true; 2787 break; 2788 } 2789 2790 // Otherwise must be an argument type. 2791 TypeLoc = Lex.getLoc(); 2792 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2793 return true; 2794 2795 if (ArgTy->isVoidTy()) 2796 return error(TypeLoc, "argument can not have void type"); 2797 2798 if (Lex.getKind() == lltok::LocalVar) { 2799 Name = Lex.getStrVal(); 2800 Lex.Lex(); 2801 } else { 2802 if (Lex.getKind() == lltok::LocalVarID) { 2803 if (Lex.getUIntVal() != CurValID) 2804 return error(TypeLoc, "argument expected to be numbered '%" + 2805 Twine(CurValID) + "'"); 2806 Lex.Lex(); 2807 } 2808 ++CurValID; 2809 Name = ""; 2810 } 2811 2812 if (!ArgTy->isFirstClassType()) 2813 return error(TypeLoc, "invalid type for function argument"); 2814 2815 ArgList.emplace_back(TypeLoc, ArgTy, 2816 AttributeSet::get(ArgTy->getContext(), Attrs), 2817 std::move(Name)); 2818 } 2819 } 2820 2821 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2822 } 2823 2824 /// parseFunctionType 2825 /// ::= Type ArgumentList OptionalAttrs 2826 bool LLParser::parseFunctionType(Type *&Result) { 2827 assert(Lex.getKind() == lltok::lparen); 2828 2829 if (!FunctionType::isValidReturnType(Result)) 2830 return tokError("invalid function return type"); 2831 2832 SmallVector<ArgInfo, 8> ArgList; 2833 bool IsVarArg; 2834 if (parseArgumentList(ArgList, IsVarArg)) 2835 return true; 2836 2837 // Reject names on the arguments lists. 2838 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2839 if (!ArgList[i].Name.empty()) 2840 return error(ArgList[i].Loc, "argument name invalid in function type"); 2841 if (ArgList[i].Attrs.hasAttributes()) 2842 return error(ArgList[i].Loc, 2843 "argument attributes invalid in function type"); 2844 } 2845 2846 SmallVector<Type*, 16> ArgListTy; 2847 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2848 ArgListTy.push_back(ArgList[i].Ty); 2849 2850 Result = FunctionType::get(Result, ArgListTy, IsVarArg); 2851 return false; 2852 } 2853 2854 /// parseAnonStructType - parse an anonymous struct type, which is inlined into 2855 /// other structs. 2856 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { 2857 SmallVector<Type*, 8> Elts; 2858 if (parseStructBody(Elts)) 2859 return true; 2860 2861 Result = StructType::get(Context, Elts, Packed); 2862 return false; 2863 } 2864 2865 /// parseStructDefinition - parse a struct in a 'type' definition. 2866 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, 2867 std::pair<Type *, LocTy> &Entry, 2868 Type *&ResultTy) { 2869 // If the type was already defined, diagnose the redefinition. 2870 if (Entry.first && !Entry.second.isValid()) 2871 return error(TypeLoc, "redefinition of type"); 2872 2873 // If we have opaque, just return without filling in the definition for the 2874 // struct. This counts as a definition as far as the .ll file goes. 2875 if (EatIfPresent(lltok::kw_opaque)) { 2876 // This type is being defined, so clear the location to indicate this. 2877 Entry.second = SMLoc(); 2878 2879 // If this type number has never been uttered, create it. 2880 if (!Entry.first) 2881 Entry.first = StructType::create(Context, Name); 2882 ResultTy = Entry.first; 2883 return false; 2884 } 2885 2886 // If the type starts with '<', then it is either a packed struct or a vector. 2887 bool isPacked = EatIfPresent(lltok::less); 2888 2889 // If we don't have a struct, then we have a random type alias, which we 2890 // accept for compatibility with old files. These types are not allowed to be 2891 // forward referenced and not allowed to be recursive. 2892 if (Lex.getKind() != lltok::lbrace) { 2893 if (Entry.first) 2894 return error(TypeLoc, "forward references to non-struct type"); 2895 2896 ResultTy = nullptr; 2897 if (isPacked) 2898 return parseArrayVectorType(ResultTy, true); 2899 return parseType(ResultTy); 2900 } 2901 2902 // This type is being defined, so clear the location to indicate this. 2903 Entry.second = SMLoc(); 2904 2905 // If this type number has never been uttered, create it. 2906 if (!Entry.first) 2907 Entry.first = StructType::create(Context, Name); 2908 2909 StructType *STy = cast<StructType>(Entry.first); 2910 2911 SmallVector<Type*, 8> Body; 2912 if (parseStructBody(Body) || 2913 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct"))) 2914 return true; 2915 2916 STy->setBody(Body, isPacked); 2917 ResultTy = STy; 2918 return false; 2919 } 2920 2921 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. 2922 /// StructType 2923 /// ::= '{' '}' 2924 /// ::= '{' Type (',' Type)* '}' 2925 /// ::= '<' '{' '}' '>' 2926 /// ::= '<' '{' Type (',' Type)* '}' '>' 2927 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { 2928 assert(Lex.getKind() == lltok::lbrace); 2929 Lex.Lex(); // Consume the '{' 2930 2931 // Handle the empty struct. 2932 if (EatIfPresent(lltok::rbrace)) 2933 return false; 2934 2935 LocTy EltTyLoc = Lex.getLoc(); 2936 Type *Ty = nullptr; 2937 if (parseType(Ty)) 2938 return true; 2939 Body.push_back(Ty); 2940 2941 if (!StructType::isValidElementType(Ty)) 2942 return error(EltTyLoc, "invalid element type for struct"); 2943 2944 while (EatIfPresent(lltok::comma)) { 2945 EltTyLoc = Lex.getLoc(); 2946 if (parseType(Ty)) 2947 return true; 2948 2949 if (!StructType::isValidElementType(Ty)) 2950 return error(EltTyLoc, "invalid element type for struct"); 2951 2952 Body.push_back(Ty); 2953 } 2954 2955 return parseToken(lltok::rbrace, "expected '}' at end of struct"); 2956 } 2957 2958 /// parseArrayVectorType - parse an array or vector type, assuming the first 2959 /// token has already been consumed. 2960 /// Type 2961 /// ::= '[' APSINTVAL 'x' Types ']' 2962 /// ::= '<' APSINTVAL 'x' Types '>' 2963 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' 2964 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { 2965 bool Scalable = false; 2966 2967 if (IsVector && Lex.getKind() == lltok::kw_vscale) { 2968 Lex.Lex(); // consume the 'vscale' 2969 if (parseToken(lltok::kw_x, "expected 'x' after vscale")) 2970 return true; 2971 2972 Scalable = true; 2973 } 2974 2975 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 2976 Lex.getAPSIntVal().getBitWidth() > 64) 2977 return tokError("expected number in address space"); 2978 2979 LocTy SizeLoc = Lex.getLoc(); 2980 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 2981 Lex.Lex(); 2982 2983 if (parseToken(lltok::kw_x, "expected 'x' after element count")) 2984 return true; 2985 2986 LocTy TypeLoc = Lex.getLoc(); 2987 Type *EltTy = nullptr; 2988 if (parseType(EltTy)) 2989 return true; 2990 2991 if (parseToken(IsVector ? lltok::greater : lltok::rsquare, 2992 "expected end of sequential type")) 2993 return true; 2994 2995 if (IsVector) { 2996 if (Size == 0) 2997 return error(SizeLoc, "zero element vector is illegal"); 2998 if ((unsigned)Size != Size) 2999 return error(SizeLoc, "size too large for vector"); 3000 if (!VectorType::isValidElementType(EltTy)) 3001 return error(TypeLoc, "invalid vector element type"); 3002 Result = VectorType::get(EltTy, unsigned(Size), Scalable); 3003 } else { 3004 if (!ArrayType::isValidElementType(EltTy)) 3005 return error(TypeLoc, "invalid array element type"); 3006 Result = ArrayType::get(EltTy, Size); 3007 } 3008 return false; 3009 } 3010 3011 //===----------------------------------------------------------------------===// 3012 // Function Semantic Analysis. 3013 //===----------------------------------------------------------------------===// 3014 3015 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 3016 int functionNumber) 3017 : P(p), F(f), FunctionNumber(functionNumber) { 3018 3019 // Insert unnamed arguments into the NumberedVals list. 3020 for (Argument &A : F.args()) 3021 if (!A.hasName()) 3022 NumberedVals.push_back(&A); 3023 } 3024 3025 LLParser::PerFunctionState::~PerFunctionState() { 3026 // If there were any forward referenced non-basicblock values, delete them. 3027 3028 for (const auto &P : ForwardRefVals) { 3029 if (isa<BasicBlock>(P.second.first)) 3030 continue; 3031 P.second.first->replaceAllUsesWith( 3032 UndefValue::get(P.second.first->getType())); 3033 P.second.first->deleteValue(); 3034 } 3035 3036 for (const auto &P : ForwardRefValIDs) { 3037 if (isa<BasicBlock>(P.second.first)) 3038 continue; 3039 P.second.first->replaceAllUsesWith( 3040 UndefValue::get(P.second.first->getType())); 3041 P.second.first->deleteValue(); 3042 } 3043 } 3044 3045 bool LLParser::PerFunctionState::finishFunction() { 3046 if (!ForwardRefVals.empty()) 3047 return P.error(ForwardRefVals.begin()->second.second, 3048 "use of undefined value '%" + ForwardRefVals.begin()->first + 3049 "'"); 3050 if (!ForwardRefValIDs.empty()) 3051 return P.error(ForwardRefValIDs.begin()->second.second, 3052 "use of undefined value '%" + 3053 Twine(ForwardRefValIDs.begin()->first) + "'"); 3054 return false; 3055 } 3056 3057 /// getVal - Get a value with the specified name or ID, creating a 3058 /// forward reference record if needed. This can return null if the value 3059 /// exists but does not have the right type. 3060 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, 3061 LocTy Loc, bool IsCall) { 3062 // Look this name up in the normal function symbol table. 3063 Value *Val = F.getValueSymbolTable()->lookup(Name); 3064 3065 // If this is a forward reference for the value, see if we already created a 3066 // forward ref record. 3067 if (!Val) { 3068 auto I = ForwardRefVals.find(Name); 3069 if (I != ForwardRefVals.end()) 3070 Val = I->second.first; 3071 } 3072 3073 // If we have the value in the symbol table or fwd-ref table, return it. 3074 if (Val) 3075 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall); 3076 3077 // Don't make placeholders with invalid type. 3078 if (!Ty->isFirstClassType()) { 3079 P.error(Loc, "invalid use of a non-first-class type"); 3080 return nullptr; 3081 } 3082 3083 // Otherwise, create a new forward reference for this value and remember it. 3084 Value *FwdVal; 3085 if (Ty->isLabelTy()) { 3086 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 3087 } else { 3088 FwdVal = new Argument(Ty, Name); 3089 } 3090 3091 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 3092 return FwdVal; 3093 } 3094 3095 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc, 3096 bool IsCall) { 3097 // Look this name up in the normal function symbol table. 3098 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 3099 3100 // If this is a forward reference for the value, see if we already created a 3101 // forward ref record. 3102 if (!Val) { 3103 auto I = ForwardRefValIDs.find(ID); 3104 if (I != ForwardRefValIDs.end()) 3105 Val = I->second.first; 3106 } 3107 3108 // If we have the value in the symbol table or fwd-ref table, return it. 3109 if (Val) 3110 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall); 3111 3112 if (!Ty->isFirstClassType()) { 3113 P.error(Loc, "invalid use of a non-first-class type"); 3114 return nullptr; 3115 } 3116 3117 // Otherwise, create a new forward reference for this value and remember it. 3118 Value *FwdVal; 3119 if (Ty->isLabelTy()) { 3120 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 3121 } else { 3122 FwdVal = new Argument(Ty); 3123 } 3124 3125 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 3126 return FwdVal; 3127 } 3128 3129 /// setInstName - After an instruction is parsed and inserted into its 3130 /// basic block, this installs its name. 3131 bool LLParser::PerFunctionState::setInstName(int NameID, 3132 const std::string &NameStr, 3133 LocTy NameLoc, Instruction *Inst) { 3134 // If this instruction has void type, it cannot have a name or ID specified. 3135 if (Inst->getType()->isVoidTy()) { 3136 if (NameID != -1 || !NameStr.empty()) 3137 return P.error(NameLoc, "instructions returning void cannot have a name"); 3138 return false; 3139 } 3140 3141 // If this was a numbered instruction, verify that the instruction is the 3142 // expected value and resolve any forward references. 3143 if (NameStr.empty()) { 3144 // If neither a name nor an ID was specified, just use the next ID. 3145 if (NameID == -1) 3146 NameID = NumberedVals.size(); 3147 3148 if (unsigned(NameID) != NumberedVals.size()) 3149 return P.error(NameLoc, "instruction expected to be numbered '%" + 3150 Twine(NumberedVals.size()) + "'"); 3151 3152 auto FI = ForwardRefValIDs.find(NameID); 3153 if (FI != ForwardRefValIDs.end()) { 3154 Value *Sentinel = FI->second.first; 3155 if (Sentinel->getType() != Inst->getType()) 3156 return P.error(NameLoc, "instruction forward referenced with type '" + 3157 getTypeString(FI->second.first->getType()) + 3158 "'"); 3159 3160 Sentinel->replaceAllUsesWith(Inst); 3161 Sentinel->deleteValue(); 3162 ForwardRefValIDs.erase(FI); 3163 } 3164 3165 NumberedVals.push_back(Inst); 3166 return false; 3167 } 3168 3169 // Otherwise, the instruction had a name. Resolve forward refs and set it. 3170 auto FI = ForwardRefVals.find(NameStr); 3171 if (FI != ForwardRefVals.end()) { 3172 Value *Sentinel = FI->second.first; 3173 if (Sentinel->getType() != Inst->getType()) 3174 return P.error(NameLoc, "instruction forward referenced with type '" + 3175 getTypeString(FI->second.first->getType()) + 3176 "'"); 3177 3178 Sentinel->replaceAllUsesWith(Inst); 3179 Sentinel->deleteValue(); 3180 ForwardRefVals.erase(FI); 3181 } 3182 3183 // Set the name on the instruction. 3184 Inst->setName(NameStr); 3185 3186 if (Inst->getName() != NameStr) 3187 return P.error(NameLoc, "multiple definition of local value named '" + 3188 NameStr + "'"); 3189 return false; 3190 } 3191 3192 /// getBB - Get a basic block with the specified name or ID, creating a 3193 /// forward reference record if needed. 3194 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, 3195 LocTy Loc) { 3196 return dyn_cast_or_null<BasicBlock>( 3197 getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false)); 3198 } 3199 3200 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { 3201 return dyn_cast_or_null<BasicBlock>( 3202 getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false)); 3203 } 3204 3205 /// defineBB - Define the specified basic block, which is either named or 3206 /// unnamed. If there is an error, this returns null otherwise it returns 3207 /// the block being defined. 3208 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, 3209 int NameID, LocTy Loc) { 3210 BasicBlock *BB; 3211 if (Name.empty()) { 3212 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) { 3213 P.error(Loc, "label expected to be numbered '" + 3214 Twine(NumberedVals.size()) + "'"); 3215 return nullptr; 3216 } 3217 BB = getBB(NumberedVals.size(), Loc); 3218 if (!BB) { 3219 P.error(Loc, "unable to create block numbered '" + 3220 Twine(NumberedVals.size()) + "'"); 3221 return nullptr; 3222 } 3223 } else { 3224 BB = getBB(Name, Loc); 3225 if (!BB) { 3226 P.error(Loc, "unable to create block named '" + Name + "'"); 3227 return nullptr; 3228 } 3229 } 3230 3231 // Move the block to the end of the function. Forward ref'd blocks are 3232 // inserted wherever they happen to be referenced. 3233 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 3234 3235 // Remove the block from forward ref sets. 3236 if (Name.empty()) { 3237 ForwardRefValIDs.erase(NumberedVals.size()); 3238 NumberedVals.push_back(BB); 3239 } else { 3240 // BB forward references are already in the function symbol table. 3241 ForwardRefVals.erase(Name); 3242 } 3243 3244 return BB; 3245 } 3246 3247 //===----------------------------------------------------------------------===// 3248 // Constants. 3249 //===----------------------------------------------------------------------===// 3250 3251 /// parseValID - parse an abstract value that doesn't necessarily have a 3252 /// type implied. For example, if we parse "4" we don't know what integer type 3253 /// it has. The value will later be combined with its type and checked for 3254 /// sanity. PFS is used to convert function-local operands of metadata (since 3255 /// metadata operands are not just parsed here but also converted to values). 3256 /// PFS can be null when we are not parsing metadata values inside a function. 3257 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) { 3258 ID.Loc = Lex.getLoc(); 3259 switch (Lex.getKind()) { 3260 default: 3261 return tokError("expected value token"); 3262 case lltok::GlobalID: // @42 3263 ID.UIntVal = Lex.getUIntVal(); 3264 ID.Kind = ValID::t_GlobalID; 3265 break; 3266 case lltok::GlobalVar: // @foo 3267 ID.StrVal = Lex.getStrVal(); 3268 ID.Kind = ValID::t_GlobalName; 3269 break; 3270 case lltok::LocalVarID: // %42 3271 ID.UIntVal = Lex.getUIntVal(); 3272 ID.Kind = ValID::t_LocalID; 3273 break; 3274 case lltok::LocalVar: // %foo 3275 ID.StrVal = Lex.getStrVal(); 3276 ID.Kind = ValID::t_LocalName; 3277 break; 3278 case lltok::APSInt: 3279 ID.APSIntVal = Lex.getAPSIntVal(); 3280 ID.Kind = ValID::t_APSInt; 3281 break; 3282 case lltok::APFloat: 3283 ID.APFloatVal = Lex.getAPFloatVal(); 3284 ID.Kind = ValID::t_APFloat; 3285 break; 3286 case lltok::kw_true: 3287 ID.ConstantVal = ConstantInt::getTrue(Context); 3288 ID.Kind = ValID::t_Constant; 3289 break; 3290 case lltok::kw_false: 3291 ID.ConstantVal = ConstantInt::getFalse(Context); 3292 ID.Kind = ValID::t_Constant; 3293 break; 3294 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 3295 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 3296 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 3297 case lltok::kw_none: ID.Kind = ValID::t_None; break; 3298 3299 case lltok::lbrace: { 3300 // ValID ::= '{' ConstVector '}' 3301 Lex.Lex(); 3302 SmallVector<Constant*, 16> Elts; 3303 if (parseGlobalValueVector(Elts) || 3304 parseToken(lltok::rbrace, "expected end of struct constant")) 3305 return true; 3306 3307 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3308 ID.UIntVal = Elts.size(); 3309 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3310 Elts.size() * sizeof(Elts[0])); 3311 ID.Kind = ValID::t_ConstantStruct; 3312 return false; 3313 } 3314 case lltok::less: { 3315 // ValID ::= '<' ConstVector '>' --> Vector. 3316 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 3317 Lex.Lex(); 3318 bool isPackedStruct = EatIfPresent(lltok::lbrace); 3319 3320 SmallVector<Constant*, 16> Elts; 3321 LocTy FirstEltLoc = Lex.getLoc(); 3322 if (parseGlobalValueVector(Elts) || 3323 (isPackedStruct && 3324 parseToken(lltok::rbrace, "expected end of packed struct")) || 3325 parseToken(lltok::greater, "expected end of constant")) 3326 return true; 3327 3328 if (isPackedStruct) { 3329 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3330 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3331 Elts.size() * sizeof(Elts[0])); 3332 ID.UIntVal = Elts.size(); 3333 ID.Kind = ValID::t_PackedConstantStruct; 3334 return false; 3335 } 3336 3337 if (Elts.empty()) 3338 return error(ID.Loc, "constant vector must not be empty"); 3339 3340 if (!Elts[0]->getType()->isIntegerTy() && 3341 !Elts[0]->getType()->isFloatingPointTy() && 3342 !Elts[0]->getType()->isPointerTy()) 3343 return error( 3344 FirstEltLoc, 3345 "vector elements must have integer, pointer or floating point type"); 3346 3347 // Verify that all the vector elements have the same type. 3348 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 3349 if (Elts[i]->getType() != Elts[0]->getType()) 3350 return error(FirstEltLoc, "vector element #" + Twine(i) + 3351 " is not of type '" + 3352 getTypeString(Elts[0]->getType())); 3353 3354 ID.ConstantVal = ConstantVector::get(Elts); 3355 ID.Kind = ValID::t_Constant; 3356 return false; 3357 } 3358 case lltok::lsquare: { // Array Constant 3359 Lex.Lex(); 3360 SmallVector<Constant*, 16> Elts; 3361 LocTy FirstEltLoc = Lex.getLoc(); 3362 if (parseGlobalValueVector(Elts) || 3363 parseToken(lltok::rsquare, "expected end of array constant")) 3364 return true; 3365 3366 // Handle empty element. 3367 if (Elts.empty()) { 3368 // Use undef instead of an array because it's inconvenient to determine 3369 // the element type at this point, there being no elements to examine. 3370 ID.Kind = ValID::t_EmptyArray; 3371 return false; 3372 } 3373 3374 if (!Elts[0]->getType()->isFirstClassType()) 3375 return error(FirstEltLoc, "invalid array element type: " + 3376 getTypeString(Elts[0]->getType())); 3377 3378 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 3379 3380 // Verify all elements are correct type! 3381 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 3382 if (Elts[i]->getType() != Elts[0]->getType()) 3383 return error(FirstEltLoc, "array element #" + Twine(i) + 3384 " is not of type '" + 3385 getTypeString(Elts[0]->getType())); 3386 } 3387 3388 ID.ConstantVal = ConstantArray::get(ATy, Elts); 3389 ID.Kind = ValID::t_Constant; 3390 return false; 3391 } 3392 case lltok::kw_c: // c "foo" 3393 Lex.Lex(); 3394 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 3395 false); 3396 if (parseToken(lltok::StringConstant, "expected string")) 3397 return true; 3398 ID.Kind = ValID::t_Constant; 3399 return false; 3400 3401 case lltok::kw_asm: { 3402 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 3403 // STRINGCONSTANT 3404 bool HasSideEffect, AlignStack, AsmDialect; 3405 Lex.Lex(); 3406 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 3407 parseOptionalToken(lltok::kw_alignstack, AlignStack) || 3408 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 3409 parseStringConstant(ID.StrVal) || 3410 parseToken(lltok::comma, "expected comma in inline asm expression") || 3411 parseToken(lltok::StringConstant, "expected constraint string")) 3412 return true; 3413 ID.StrVal2 = Lex.getStrVal(); 3414 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) | 3415 (unsigned(AsmDialect)<<2); 3416 ID.Kind = ValID::t_InlineAsm; 3417 return false; 3418 } 3419 3420 case lltok::kw_blockaddress: { 3421 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 3422 Lex.Lex(); 3423 3424 ValID Fn, Label; 3425 3426 if (parseToken(lltok::lparen, "expected '(' in block address expression") || 3427 parseValID(Fn) || 3428 parseToken(lltok::comma, 3429 "expected comma in block address expression") || 3430 parseValID(Label) || 3431 parseToken(lltok::rparen, "expected ')' in block address expression")) 3432 return true; 3433 3434 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3435 return error(Fn.Loc, "expected function name in blockaddress"); 3436 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 3437 return error(Label.Loc, "expected basic block name in blockaddress"); 3438 3439 // Try to find the function (but skip it if it's forward-referenced). 3440 GlobalValue *GV = nullptr; 3441 if (Fn.Kind == ValID::t_GlobalID) { 3442 if (Fn.UIntVal < NumberedVals.size()) 3443 GV = NumberedVals[Fn.UIntVal]; 3444 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3445 GV = M->getNamedValue(Fn.StrVal); 3446 } 3447 Function *F = nullptr; 3448 if (GV) { 3449 // Confirm that it's actually a function with a definition. 3450 if (!isa<Function>(GV)) 3451 return error(Fn.Loc, "expected function name in blockaddress"); 3452 F = cast<Function>(GV); 3453 if (F->isDeclaration()) 3454 return error(Fn.Loc, "cannot take blockaddress inside a declaration"); 3455 } 3456 3457 if (!F) { 3458 // Make a global variable as a placeholder for this reference. 3459 GlobalValue *&FwdRef = 3460 ForwardRefBlockAddresses.insert(std::make_pair( 3461 std::move(Fn), 3462 std::map<ValID, GlobalValue *>())) 3463 .first->second.insert(std::make_pair(std::move(Label), nullptr)) 3464 .first->second; 3465 if (!FwdRef) 3466 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false, 3467 GlobalValue::InternalLinkage, nullptr, ""); 3468 ID.ConstantVal = FwdRef; 3469 ID.Kind = ValID::t_Constant; 3470 return false; 3471 } 3472 3473 // We found the function; now find the basic block. Don't use PFS, since we 3474 // might be inside a constant expression. 3475 BasicBlock *BB; 3476 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 3477 if (Label.Kind == ValID::t_LocalID) 3478 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc); 3479 else 3480 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc); 3481 if (!BB) 3482 return error(Label.Loc, "referenced value is not a basic block"); 3483 } else { 3484 if (Label.Kind == ValID::t_LocalID) 3485 return error(Label.Loc, "cannot take address of numeric label after " 3486 "the function is defined"); 3487 BB = dyn_cast_or_null<BasicBlock>( 3488 F->getValueSymbolTable()->lookup(Label.StrVal)); 3489 if (!BB) 3490 return error(Label.Loc, "referenced value is not a basic block"); 3491 } 3492 3493 ID.ConstantVal = BlockAddress::get(F, BB); 3494 ID.Kind = ValID::t_Constant; 3495 return false; 3496 } 3497 3498 case lltok::kw_trunc: 3499 case lltok::kw_zext: 3500 case lltok::kw_sext: 3501 case lltok::kw_fptrunc: 3502 case lltok::kw_fpext: 3503 case lltok::kw_bitcast: 3504 case lltok::kw_addrspacecast: 3505 case lltok::kw_uitofp: 3506 case lltok::kw_sitofp: 3507 case lltok::kw_fptoui: 3508 case lltok::kw_fptosi: 3509 case lltok::kw_inttoptr: 3510 case lltok::kw_ptrtoint: { 3511 unsigned Opc = Lex.getUIntVal(); 3512 Type *DestTy = nullptr; 3513 Constant *SrcVal; 3514 Lex.Lex(); 3515 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") || 3516 parseGlobalTypeAndValue(SrcVal) || 3517 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 3518 parseType(DestTy) || 3519 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 3520 return true; 3521 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 3522 return error(ID.Loc, "invalid cast opcode for cast from '" + 3523 getTypeString(SrcVal->getType()) + "' to '" + 3524 getTypeString(DestTy) + "'"); 3525 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 3526 SrcVal, DestTy); 3527 ID.Kind = ValID::t_Constant; 3528 return false; 3529 } 3530 case lltok::kw_extractvalue: { 3531 Lex.Lex(); 3532 Constant *Val; 3533 SmallVector<unsigned, 4> Indices; 3534 if (parseToken(lltok::lparen, 3535 "expected '(' in extractvalue constantexpr") || 3536 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) || 3537 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 3538 return true; 3539 3540 if (!Val->getType()->isAggregateType()) 3541 return error(ID.Loc, "extractvalue operand must be aggregate type"); 3542 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3543 return error(ID.Loc, "invalid indices for extractvalue"); 3544 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 3545 ID.Kind = ValID::t_Constant; 3546 return false; 3547 } 3548 case lltok::kw_insertvalue: { 3549 Lex.Lex(); 3550 Constant *Val0, *Val1; 3551 SmallVector<unsigned, 4> Indices; 3552 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") || 3553 parseGlobalTypeAndValue(Val0) || 3554 parseToken(lltok::comma, 3555 "expected comma in insertvalue constantexpr") || 3556 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) || 3557 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 3558 return true; 3559 if (!Val0->getType()->isAggregateType()) 3560 return error(ID.Loc, "insertvalue operand must be aggregate type"); 3561 Type *IndexedType = 3562 ExtractValueInst::getIndexedType(Val0->getType(), Indices); 3563 if (!IndexedType) 3564 return error(ID.Loc, "invalid indices for insertvalue"); 3565 if (IndexedType != Val1->getType()) 3566 return error(ID.Loc, "insertvalue operand and field disagree in type: '" + 3567 getTypeString(Val1->getType()) + 3568 "' instead of '" + getTypeString(IndexedType) + 3569 "'"); 3570 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 3571 ID.Kind = ValID::t_Constant; 3572 return false; 3573 } 3574 case lltok::kw_icmp: 3575 case lltok::kw_fcmp: { 3576 unsigned PredVal, Opc = Lex.getUIntVal(); 3577 Constant *Val0, *Val1; 3578 Lex.Lex(); 3579 if (parseCmpPredicate(PredVal, Opc) || 3580 parseToken(lltok::lparen, "expected '(' in compare constantexpr") || 3581 parseGlobalTypeAndValue(Val0) || 3582 parseToken(lltok::comma, "expected comma in compare constantexpr") || 3583 parseGlobalTypeAndValue(Val1) || 3584 parseToken(lltok::rparen, "expected ')' in compare constantexpr")) 3585 return true; 3586 3587 if (Val0->getType() != Val1->getType()) 3588 return error(ID.Loc, "compare operands must have the same type"); 3589 3590 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 3591 3592 if (Opc == Instruction::FCmp) { 3593 if (!Val0->getType()->isFPOrFPVectorTy()) 3594 return error(ID.Loc, "fcmp requires floating point operands"); 3595 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 3596 } else { 3597 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 3598 if (!Val0->getType()->isIntOrIntVectorTy() && 3599 !Val0->getType()->isPtrOrPtrVectorTy()) 3600 return error(ID.Loc, "icmp requires pointer or integer operands"); 3601 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 3602 } 3603 ID.Kind = ValID::t_Constant; 3604 return false; 3605 } 3606 3607 // Unary Operators. 3608 case lltok::kw_fneg: { 3609 unsigned Opc = Lex.getUIntVal(); 3610 Constant *Val; 3611 Lex.Lex(); 3612 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") || 3613 parseGlobalTypeAndValue(Val) || 3614 parseToken(lltok::rparen, "expected ')' in unary constantexpr")) 3615 return true; 3616 3617 // Check that the type is valid for the operator. 3618 switch (Opc) { 3619 case Instruction::FNeg: 3620 if (!Val->getType()->isFPOrFPVectorTy()) 3621 return error(ID.Loc, "constexpr requires fp operands"); 3622 break; 3623 default: llvm_unreachable("Unknown unary operator!"); 3624 } 3625 unsigned Flags = 0; 3626 Constant *C = ConstantExpr::get(Opc, Val, Flags); 3627 ID.ConstantVal = C; 3628 ID.Kind = ValID::t_Constant; 3629 return false; 3630 } 3631 // Binary Operators. 3632 case lltok::kw_add: 3633 case lltok::kw_fadd: 3634 case lltok::kw_sub: 3635 case lltok::kw_fsub: 3636 case lltok::kw_mul: 3637 case lltok::kw_fmul: 3638 case lltok::kw_udiv: 3639 case lltok::kw_sdiv: 3640 case lltok::kw_fdiv: 3641 case lltok::kw_urem: 3642 case lltok::kw_srem: 3643 case lltok::kw_frem: 3644 case lltok::kw_shl: 3645 case lltok::kw_lshr: 3646 case lltok::kw_ashr: { 3647 bool NUW = false; 3648 bool NSW = false; 3649 bool Exact = false; 3650 unsigned Opc = Lex.getUIntVal(); 3651 Constant *Val0, *Val1; 3652 Lex.Lex(); 3653 if (Opc == Instruction::Add || Opc == Instruction::Sub || 3654 Opc == Instruction::Mul || Opc == Instruction::Shl) { 3655 if (EatIfPresent(lltok::kw_nuw)) 3656 NUW = true; 3657 if (EatIfPresent(lltok::kw_nsw)) { 3658 NSW = true; 3659 if (EatIfPresent(lltok::kw_nuw)) 3660 NUW = true; 3661 } 3662 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 3663 Opc == Instruction::LShr || Opc == Instruction::AShr) { 3664 if (EatIfPresent(lltok::kw_exact)) 3665 Exact = true; 3666 } 3667 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") || 3668 parseGlobalTypeAndValue(Val0) || 3669 parseToken(lltok::comma, "expected comma in binary constantexpr") || 3670 parseGlobalTypeAndValue(Val1) || 3671 parseToken(lltok::rparen, "expected ')' in binary constantexpr")) 3672 return true; 3673 if (Val0->getType() != Val1->getType()) 3674 return error(ID.Loc, "operands of constexpr must have same type"); 3675 // Check that the type is valid for the operator. 3676 switch (Opc) { 3677 case Instruction::Add: 3678 case Instruction::Sub: 3679 case Instruction::Mul: 3680 case Instruction::UDiv: 3681 case Instruction::SDiv: 3682 case Instruction::URem: 3683 case Instruction::SRem: 3684 case Instruction::Shl: 3685 case Instruction::AShr: 3686 case Instruction::LShr: 3687 if (!Val0->getType()->isIntOrIntVectorTy()) 3688 return error(ID.Loc, "constexpr requires integer operands"); 3689 break; 3690 case Instruction::FAdd: 3691 case Instruction::FSub: 3692 case Instruction::FMul: 3693 case Instruction::FDiv: 3694 case Instruction::FRem: 3695 if (!Val0->getType()->isFPOrFPVectorTy()) 3696 return error(ID.Loc, "constexpr requires fp operands"); 3697 break; 3698 default: llvm_unreachable("Unknown binary operator!"); 3699 } 3700 unsigned Flags = 0; 3701 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3702 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 3703 if (Exact) Flags |= PossiblyExactOperator::IsExact; 3704 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 3705 ID.ConstantVal = C; 3706 ID.Kind = ValID::t_Constant; 3707 return false; 3708 } 3709 3710 // Logical Operations 3711 case lltok::kw_and: 3712 case lltok::kw_or: 3713 case lltok::kw_xor: { 3714 unsigned Opc = Lex.getUIntVal(); 3715 Constant *Val0, *Val1; 3716 Lex.Lex(); 3717 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") || 3718 parseGlobalTypeAndValue(Val0) || 3719 parseToken(lltok::comma, "expected comma in logical constantexpr") || 3720 parseGlobalTypeAndValue(Val1) || 3721 parseToken(lltok::rparen, "expected ')' in logical constantexpr")) 3722 return true; 3723 if (Val0->getType() != Val1->getType()) 3724 return error(ID.Loc, "operands of constexpr must have same type"); 3725 if (!Val0->getType()->isIntOrIntVectorTy()) 3726 return error(ID.Loc, 3727 "constexpr requires integer or integer vector operands"); 3728 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 3729 ID.Kind = ValID::t_Constant; 3730 return false; 3731 } 3732 3733 case lltok::kw_getelementptr: 3734 case lltok::kw_shufflevector: 3735 case lltok::kw_insertelement: 3736 case lltok::kw_extractelement: 3737 case lltok::kw_select: { 3738 unsigned Opc = Lex.getUIntVal(); 3739 SmallVector<Constant*, 16> Elts; 3740 bool InBounds = false; 3741 Type *Ty; 3742 Lex.Lex(); 3743 3744 if (Opc == Instruction::GetElementPtr) 3745 InBounds = EatIfPresent(lltok::kw_inbounds); 3746 3747 if (parseToken(lltok::lparen, "expected '(' in constantexpr")) 3748 return true; 3749 3750 LocTy ExplicitTypeLoc = Lex.getLoc(); 3751 if (Opc == Instruction::GetElementPtr) { 3752 if (parseType(Ty) || 3753 parseToken(lltok::comma, "expected comma after getelementptr's type")) 3754 return true; 3755 } 3756 3757 Optional<unsigned> InRangeOp; 3758 if (parseGlobalValueVector( 3759 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) || 3760 parseToken(lltok::rparen, "expected ')' in constantexpr")) 3761 return true; 3762 3763 if (Opc == Instruction::GetElementPtr) { 3764 if (Elts.size() == 0 || 3765 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 3766 return error(ID.Loc, "base of getelementptr must be a pointer"); 3767 3768 Type *BaseType = Elts[0]->getType(); 3769 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType()); 3770 if (Ty != BasePointerType->getElementType()) 3771 return error( 3772 ExplicitTypeLoc, 3773 "explicit pointee type doesn't match operand's pointee type"); 3774 3775 unsigned GEPWidth = 3776 BaseType->isVectorTy() 3777 ? cast<FixedVectorType>(BaseType)->getNumElements() 3778 : 0; 3779 3780 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3781 for (Constant *Val : Indices) { 3782 Type *ValTy = Val->getType(); 3783 if (!ValTy->isIntOrIntVectorTy()) 3784 return error(ID.Loc, "getelementptr index must be an integer"); 3785 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 3786 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 3787 if (GEPWidth && (ValNumEl != GEPWidth)) 3788 return error( 3789 ID.Loc, 3790 "getelementptr vector index has a wrong number of elements"); 3791 // GEPWidth may have been unknown because the base is a scalar, 3792 // but it is known now. 3793 GEPWidth = ValNumEl; 3794 } 3795 } 3796 3797 SmallPtrSet<Type*, 4> Visited; 3798 if (!Indices.empty() && !Ty->isSized(&Visited)) 3799 return error(ID.Loc, "base element of getelementptr must be sized"); 3800 3801 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3802 return error(ID.Loc, "invalid getelementptr indices"); 3803 3804 if (InRangeOp) { 3805 if (*InRangeOp == 0) 3806 return error(ID.Loc, 3807 "inrange keyword may not appear on pointer operand"); 3808 --*InRangeOp; 3809 } 3810 3811 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3812 InBounds, InRangeOp); 3813 } else if (Opc == Instruction::Select) { 3814 if (Elts.size() != 3) 3815 return error(ID.Loc, "expected three operands to select"); 3816 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3817 Elts[2])) 3818 return error(ID.Loc, Reason); 3819 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3820 } else if (Opc == Instruction::ShuffleVector) { 3821 if (Elts.size() != 3) 3822 return error(ID.Loc, "expected three operands to shufflevector"); 3823 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3824 return error(ID.Loc, "invalid operands to shufflevector"); 3825 SmallVector<int, 16> Mask; 3826 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 3827 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 3828 } else if (Opc == Instruction::ExtractElement) { 3829 if (Elts.size() != 2) 3830 return error(ID.Loc, "expected two operands to extractelement"); 3831 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3832 return error(ID.Loc, "invalid extractelement operands"); 3833 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3834 } else { 3835 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3836 if (Elts.size() != 3) 3837 return error(ID.Loc, "expected three operands to insertelement"); 3838 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3839 return error(ID.Loc, "invalid insertelement operands"); 3840 ID.ConstantVal = 3841 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3842 } 3843 3844 ID.Kind = ValID::t_Constant; 3845 return false; 3846 } 3847 } 3848 3849 Lex.Lex(); 3850 return false; 3851 } 3852 3853 /// parseGlobalValue - parse a global value with the specified type. 3854 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { 3855 C = nullptr; 3856 ValID ID; 3857 Value *V = nullptr; 3858 bool Parsed = parseValID(ID) || 3859 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false); 3860 if (V && !(C = dyn_cast<Constant>(V))) 3861 return error(ID.Loc, "global values must be constants"); 3862 return Parsed; 3863 } 3864 3865 bool LLParser::parseGlobalTypeAndValue(Constant *&V) { 3866 Type *Ty = nullptr; 3867 return parseType(Ty) || parseGlobalValue(Ty, V); 3868 } 3869 3870 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3871 C = nullptr; 3872 3873 LocTy KwLoc = Lex.getLoc(); 3874 if (!EatIfPresent(lltok::kw_comdat)) 3875 return false; 3876 3877 if (EatIfPresent(lltok::lparen)) { 3878 if (Lex.getKind() != lltok::ComdatVar) 3879 return tokError("expected comdat variable"); 3880 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3881 Lex.Lex(); 3882 if (parseToken(lltok::rparen, "expected ')' after comdat var")) 3883 return true; 3884 } else { 3885 if (GlobalName.empty()) 3886 return tokError("comdat cannot be unnamed"); 3887 C = getComdat(std::string(GlobalName), KwLoc); 3888 } 3889 3890 return false; 3891 } 3892 3893 /// parseGlobalValueVector 3894 /// ::= /*empty*/ 3895 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3896 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3897 Optional<unsigned> *InRangeOp) { 3898 // Empty list. 3899 if (Lex.getKind() == lltok::rbrace || 3900 Lex.getKind() == lltok::rsquare || 3901 Lex.getKind() == lltok::greater || 3902 Lex.getKind() == lltok::rparen) 3903 return false; 3904 3905 do { 3906 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3907 *InRangeOp = Elts.size(); 3908 3909 Constant *C; 3910 if (parseGlobalTypeAndValue(C)) 3911 return true; 3912 Elts.push_back(C); 3913 } while (EatIfPresent(lltok::comma)); 3914 3915 return false; 3916 } 3917 3918 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { 3919 SmallVector<Metadata *, 16> Elts; 3920 if (parseMDNodeVector(Elts)) 3921 return true; 3922 3923 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3924 return false; 3925 } 3926 3927 /// MDNode: 3928 /// ::= !{ ... } 3929 /// ::= !7 3930 /// ::= !DILocation(...) 3931 bool LLParser::parseMDNode(MDNode *&N) { 3932 if (Lex.getKind() == lltok::MetadataVar) 3933 return parseSpecializedMDNode(N); 3934 3935 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N); 3936 } 3937 3938 bool LLParser::parseMDNodeTail(MDNode *&N) { 3939 // !{ ... } 3940 if (Lex.getKind() == lltok::lbrace) 3941 return parseMDTuple(N); 3942 3943 // !42 3944 return parseMDNodeID(N); 3945 } 3946 3947 namespace { 3948 3949 /// Structure to represent an optional metadata field. 3950 template <class FieldTy> struct MDFieldImpl { 3951 typedef MDFieldImpl ImplTy; 3952 FieldTy Val; 3953 bool Seen; 3954 3955 void assign(FieldTy Val) { 3956 Seen = true; 3957 this->Val = std::move(Val); 3958 } 3959 3960 explicit MDFieldImpl(FieldTy Default) 3961 : Val(std::move(Default)), Seen(false) {} 3962 }; 3963 3964 /// Structure to represent an optional metadata field that 3965 /// can be of either type (A or B) and encapsulates the 3966 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3967 /// to reimplement the specifics for representing each Field. 3968 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3969 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3970 FieldTypeA A; 3971 FieldTypeB B; 3972 bool Seen; 3973 3974 enum { 3975 IsInvalid = 0, 3976 IsTypeA = 1, 3977 IsTypeB = 2 3978 } WhatIs; 3979 3980 void assign(FieldTypeA A) { 3981 Seen = true; 3982 this->A = std::move(A); 3983 WhatIs = IsTypeA; 3984 } 3985 3986 void assign(FieldTypeB B) { 3987 Seen = true; 3988 this->B = std::move(B); 3989 WhatIs = IsTypeB; 3990 } 3991 3992 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3993 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3994 WhatIs(IsInvalid) {} 3995 }; 3996 3997 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3998 uint64_t Max; 3999 4000 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 4001 : ImplTy(Default), Max(Max) {} 4002 }; 4003 4004 struct LineField : public MDUnsignedField { 4005 LineField() : MDUnsignedField(0, UINT32_MAX) {} 4006 }; 4007 4008 struct ColumnField : public MDUnsignedField { 4009 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 4010 }; 4011 4012 struct DwarfTagField : public MDUnsignedField { 4013 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 4014 DwarfTagField(dwarf::Tag DefaultTag) 4015 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 4016 }; 4017 4018 struct DwarfMacinfoTypeField : public MDUnsignedField { 4019 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 4020 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 4021 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 4022 }; 4023 4024 struct DwarfAttEncodingField : public MDUnsignedField { 4025 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 4026 }; 4027 4028 struct DwarfVirtualityField : public MDUnsignedField { 4029 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 4030 }; 4031 4032 struct DwarfLangField : public MDUnsignedField { 4033 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 4034 }; 4035 4036 struct DwarfCCField : public MDUnsignedField { 4037 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 4038 }; 4039 4040 struct EmissionKindField : public MDUnsignedField { 4041 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 4042 }; 4043 4044 struct NameTableKindField : public MDUnsignedField { 4045 NameTableKindField() 4046 : MDUnsignedField( 4047 0, (unsigned) 4048 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 4049 }; 4050 4051 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 4052 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 4053 }; 4054 4055 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 4056 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 4057 }; 4058 4059 struct MDAPSIntField : public MDFieldImpl<APSInt> { 4060 MDAPSIntField() : ImplTy(APSInt()) {} 4061 }; 4062 4063 struct MDSignedField : public MDFieldImpl<int64_t> { 4064 int64_t Min; 4065 int64_t Max; 4066 4067 MDSignedField(int64_t Default = 0) 4068 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 4069 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 4070 : ImplTy(Default), Min(Min), Max(Max) {} 4071 }; 4072 4073 struct MDBoolField : public MDFieldImpl<bool> { 4074 MDBoolField(bool Default = false) : ImplTy(Default) {} 4075 }; 4076 4077 struct MDField : public MDFieldImpl<Metadata *> { 4078 bool AllowNull; 4079 4080 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 4081 }; 4082 4083 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> { 4084 MDConstant() : ImplTy(nullptr) {} 4085 }; 4086 4087 struct MDStringField : public MDFieldImpl<MDString *> { 4088 bool AllowEmpty; 4089 MDStringField(bool AllowEmpty = true) 4090 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 4091 }; 4092 4093 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 4094 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 4095 }; 4096 4097 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 4098 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 4099 }; 4100 4101 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 4102 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 4103 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 4104 4105 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 4106 bool AllowNull = true) 4107 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 4108 4109 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4110 bool isMDField() const { return WhatIs == IsTypeB; } 4111 int64_t getMDSignedValue() const { 4112 assert(isMDSignedField() && "Wrong field type"); 4113 return A.Val; 4114 } 4115 Metadata *getMDFieldValue() const { 4116 assert(isMDField() && "Wrong field type"); 4117 return B.Val; 4118 } 4119 }; 4120 4121 struct MDSignedOrUnsignedField 4122 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> { 4123 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {} 4124 4125 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4126 bool isMDUnsignedField() const { return WhatIs == IsTypeB; } 4127 int64_t getMDSignedValue() const { 4128 assert(isMDSignedField() && "Wrong field type"); 4129 return A.Val; 4130 } 4131 uint64_t getMDUnsignedValue() const { 4132 assert(isMDUnsignedField() && "Wrong field type"); 4133 return B.Val; 4134 } 4135 }; 4136 4137 } // end anonymous namespace 4138 4139 namespace llvm { 4140 4141 template <> 4142 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 4143 if (Lex.getKind() != lltok::APSInt) 4144 return tokError("expected integer"); 4145 4146 Result.assign(Lex.getAPSIntVal()); 4147 Lex.Lex(); 4148 return false; 4149 } 4150 4151 template <> 4152 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4153 MDUnsignedField &Result) { 4154 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4155 return tokError("expected unsigned integer"); 4156 4157 auto &U = Lex.getAPSIntVal(); 4158 if (U.ugt(Result.Max)) 4159 return tokError("value for '" + Name + "' too large, limit is " + 4160 Twine(Result.Max)); 4161 Result.assign(U.getZExtValue()); 4162 assert(Result.Val <= Result.Max && "Expected value in range"); 4163 Lex.Lex(); 4164 return false; 4165 } 4166 4167 template <> 4168 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { 4169 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4170 } 4171 template <> 4172 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 4173 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4174 } 4175 4176 template <> 4177 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 4178 if (Lex.getKind() == lltok::APSInt) 4179 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4180 4181 if (Lex.getKind() != lltok::DwarfTag) 4182 return tokError("expected DWARF tag"); 4183 4184 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 4185 if (Tag == dwarf::DW_TAG_invalid) 4186 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 4187 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 4188 4189 Result.assign(Tag); 4190 Lex.Lex(); 4191 return false; 4192 } 4193 4194 template <> 4195 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4196 DwarfMacinfoTypeField &Result) { 4197 if (Lex.getKind() == lltok::APSInt) 4198 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4199 4200 if (Lex.getKind() != lltok::DwarfMacinfo) 4201 return tokError("expected DWARF macinfo type"); 4202 4203 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4204 if (Macinfo == dwarf::DW_MACINFO_invalid) 4205 return tokError("invalid DWARF macinfo type" + Twine(" '") + 4206 Lex.getStrVal() + "'"); 4207 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4208 4209 Result.assign(Macinfo); 4210 Lex.Lex(); 4211 return false; 4212 } 4213 4214 template <> 4215 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4216 DwarfVirtualityField &Result) { 4217 if (Lex.getKind() == lltok::APSInt) 4218 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4219 4220 if (Lex.getKind() != lltok::DwarfVirtuality) 4221 return tokError("expected DWARF virtuality code"); 4222 4223 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4224 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4225 return tokError("invalid DWARF virtuality code" + Twine(" '") + 4226 Lex.getStrVal() + "'"); 4227 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4228 Result.assign(Virtuality); 4229 Lex.Lex(); 4230 return false; 4231 } 4232 4233 template <> 4234 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4235 if (Lex.getKind() == lltok::APSInt) 4236 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4237 4238 if (Lex.getKind() != lltok::DwarfLang) 4239 return tokError("expected DWARF language"); 4240 4241 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4242 if (!Lang) 4243 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4244 "'"); 4245 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4246 Result.assign(Lang); 4247 Lex.Lex(); 4248 return false; 4249 } 4250 4251 template <> 4252 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4253 if (Lex.getKind() == lltok::APSInt) 4254 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4255 4256 if (Lex.getKind() != lltok::DwarfCC) 4257 return tokError("expected DWARF calling convention"); 4258 4259 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4260 if (!CC) 4261 return tokError("invalid DWARF calling convention" + Twine(" '") + 4262 Lex.getStrVal() + "'"); 4263 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4264 Result.assign(CC); 4265 Lex.Lex(); 4266 return false; 4267 } 4268 4269 template <> 4270 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4271 EmissionKindField &Result) { 4272 if (Lex.getKind() == lltok::APSInt) 4273 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4274 4275 if (Lex.getKind() != lltok::EmissionKind) 4276 return tokError("expected emission kind"); 4277 4278 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4279 if (!Kind) 4280 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4281 "'"); 4282 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4283 Result.assign(*Kind); 4284 Lex.Lex(); 4285 return false; 4286 } 4287 4288 template <> 4289 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4290 NameTableKindField &Result) { 4291 if (Lex.getKind() == lltok::APSInt) 4292 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4293 4294 if (Lex.getKind() != lltok::NameTableKind) 4295 return tokError("expected nameTable kind"); 4296 4297 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4298 if (!Kind) 4299 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4300 "'"); 4301 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4302 Result.assign((unsigned)*Kind); 4303 Lex.Lex(); 4304 return false; 4305 } 4306 4307 template <> 4308 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4309 DwarfAttEncodingField &Result) { 4310 if (Lex.getKind() == lltok::APSInt) 4311 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4312 4313 if (Lex.getKind() != lltok::DwarfAttEncoding) 4314 return tokError("expected DWARF type attribute encoding"); 4315 4316 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4317 if (!Encoding) 4318 return tokError("invalid DWARF type attribute encoding" + Twine(" '") + 4319 Lex.getStrVal() + "'"); 4320 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4321 Result.assign(Encoding); 4322 Lex.Lex(); 4323 return false; 4324 } 4325 4326 /// DIFlagField 4327 /// ::= uint32 4328 /// ::= DIFlagVector 4329 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4330 template <> 4331 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4332 4333 // parser for a single flag. 4334 auto parseFlag = [&](DINode::DIFlags &Val) { 4335 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4336 uint32_t TempVal = static_cast<uint32_t>(Val); 4337 bool Res = parseUInt32(TempVal); 4338 Val = static_cast<DINode::DIFlags>(TempVal); 4339 return Res; 4340 } 4341 4342 if (Lex.getKind() != lltok::DIFlag) 4343 return tokError("expected debug info flag"); 4344 4345 Val = DINode::getFlag(Lex.getStrVal()); 4346 if (!Val) 4347 return tokError(Twine("invalid debug info flag flag '") + 4348 Lex.getStrVal() + "'"); 4349 Lex.Lex(); 4350 return false; 4351 }; 4352 4353 // parse the flags and combine them together. 4354 DINode::DIFlags Combined = DINode::FlagZero; 4355 do { 4356 DINode::DIFlags Val; 4357 if (parseFlag(Val)) 4358 return true; 4359 Combined |= Val; 4360 } while (EatIfPresent(lltok::bar)); 4361 4362 Result.assign(Combined); 4363 return false; 4364 } 4365 4366 /// DISPFlagField 4367 /// ::= uint32 4368 /// ::= DISPFlagVector 4369 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4370 template <> 4371 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4372 4373 // parser for a single flag. 4374 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4375 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4376 uint32_t TempVal = static_cast<uint32_t>(Val); 4377 bool Res = parseUInt32(TempVal); 4378 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4379 return Res; 4380 } 4381 4382 if (Lex.getKind() != lltok::DISPFlag) 4383 return tokError("expected debug info flag"); 4384 4385 Val = DISubprogram::getFlag(Lex.getStrVal()); 4386 if (!Val) 4387 return tokError(Twine("invalid subprogram debug info flag '") + 4388 Lex.getStrVal() + "'"); 4389 Lex.Lex(); 4390 return false; 4391 }; 4392 4393 // parse the flags and combine them together. 4394 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4395 do { 4396 DISubprogram::DISPFlags Val; 4397 if (parseFlag(Val)) 4398 return true; 4399 Combined |= Val; 4400 } while (EatIfPresent(lltok::bar)); 4401 4402 Result.assign(Combined); 4403 return false; 4404 } 4405 4406 template <> 4407 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { 4408 if (Lex.getKind() != lltok::APSInt) 4409 return tokError("expected signed integer"); 4410 4411 auto &S = Lex.getAPSIntVal(); 4412 if (S < Result.Min) 4413 return tokError("value for '" + Name + "' too small, limit is " + 4414 Twine(Result.Min)); 4415 if (S > Result.Max) 4416 return tokError("value for '" + Name + "' too large, limit is " + 4417 Twine(Result.Max)); 4418 Result.assign(S.getExtValue()); 4419 assert(Result.Val >= Result.Min && "Expected value in range"); 4420 assert(Result.Val <= Result.Max && "Expected value in range"); 4421 Lex.Lex(); 4422 return false; 4423 } 4424 4425 template <> 4426 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4427 switch (Lex.getKind()) { 4428 default: 4429 return tokError("expected 'true' or 'false'"); 4430 case lltok::kw_true: 4431 Result.assign(true); 4432 break; 4433 case lltok::kw_false: 4434 Result.assign(false); 4435 break; 4436 } 4437 Lex.Lex(); 4438 return false; 4439 } 4440 4441 template <> 4442 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4443 if (Lex.getKind() == lltok::kw_null) { 4444 if (!Result.AllowNull) 4445 return tokError("'" + Name + "' cannot be null"); 4446 Lex.Lex(); 4447 Result.assign(nullptr); 4448 return false; 4449 } 4450 4451 Metadata *MD; 4452 if (parseMetadata(MD, nullptr)) 4453 return true; 4454 4455 Result.assign(MD); 4456 return false; 4457 } 4458 4459 template <> 4460 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4461 MDSignedOrMDField &Result) { 4462 // Try to parse a signed int. 4463 if (Lex.getKind() == lltok::APSInt) { 4464 MDSignedField Res = Result.A; 4465 if (!parseMDField(Loc, Name, Res)) { 4466 Result.assign(Res); 4467 return false; 4468 } 4469 return true; 4470 } 4471 4472 // Otherwise, try to parse as an MDField. 4473 MDField Res = Result.B; 4474 if (!parseMDField(Loc, Name, Res)) { 4475 Result.assign(Res); 4476 return false; 4477 } 4478 4479 return true; 4480 } 4481 4482 template <> 4483 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4484 LocTy ValueLoc = Lex.getLoc(); 4485 std::string S; 4486 if (parseStringConstant(S)) 4487 return true; 4488 4489 if (!Result.AllowEmpty && S.empty()) 4490 return error(ValueLoc, "'" + Name + "' cannot be empty"); 4491 4492 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4493 return false; 4494 } 4495 4496 template <> 4497 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4498 SmallVector<Metadata *, 4> MDs; 4499 if (parseMDNodeVector(MDs)) 4500 return true; 4501 4502 Result.assign(std::move(MDs)); 4503 return false; 4504 } 4505 4506 template <> 4507 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4508 ChecksumKindField &Result) { 4509 Optional<DIFile::ChecksumKind> CSKind = 4510 DIFile::getChecksumKind(Lex.getStrVal()); 4511 4512 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4513 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() + 4514 "'"); 4515 4516 Result.assign(*CSKind); 4517 Lex.Lex(); 4518 return false; 4519 } 4520 4521 } // end namespace llvm 4522 4523 template <class ParserTy> 4524 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { 4525 do { 4526 if (Lex.getKind() != lltok::LabelStr) 4527 return tokError("expected field label here"); 4528 4529 if (ParseField()) 4530 return true; 4531 } while (EatIfPresent(lltok::comma)); 4532 4533 return false; 4534 } 4535 4536 template <class ParserTy> 4537 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { 4538 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4539 Lex.Lex(); 4540 4541 if (parseToken(lltok::lparen, "expected '(' here")) 4542 return true; 4543 if (Lex.getKind() != lltok::rparen) 4544 if (parseMDFieldsImplBody(ParseField)) 4545 return true; 4546 4547 ClosingLoc = Lex.getLoc(); 4548 return parseToken(lltok::rparen, "expected ')' here"); 4549 } 4550 4551 template <class FieldTy> 4552 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { 4553 if (Result.Seen) 4554 return tokError("field '" + Name + "' cannot be specified more than once"); 4555 4556 LocTy Loc = Lex.getLoc(); 4557 Lex.Lex(); 4558 return parseMDField(Loc, Name, Result); 4559 } 4560 4561 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4562 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4563 4564 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4565 if (Lex.getStrVal() == #CLASS) \ 4566 return parse##CLASS(N, IsDistinct); 4567 #include "llvm/IR/Metadata.def" 4568 4569 return tokError("expected metadata type"); 4570 } 4571 4572 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4573 #define NOP_FIELD(NAME, TYPE, INIT) 4574 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4575 if (!NAME.Seen) \ 4576 return error(ClosingLoc, "missing required field '" #NAME "'"); 4577 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4578 if (Lex.getStrVal() == #NAME) \ 4579 return parseMDField(#NAME, NAME); 4580 #define PARSE_MD_FIELDS() \ 4581 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4582 do { \ 4583 LocTy ClosingLoc; \ 4584 if (parseMDFieldsImpl( \ 4585 [&]() -> bool { \ 4586 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4587 return tokError(Twine("invalid field '") + Lex.getStrVal() + \ 4588 "'"); \ 4589 }, \ 4590 ClosingLoc)) \ 4591 return true; \ 4592 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4593 } while (false) 4594 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4595 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4596 4597 /// parseDILocationFields: 4598 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4599 /// isImplicitCode: true) 4600 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { 4601 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4602 OPTIONAL(line, LineField, ); \ 4603 OPTIONAL(column, ColumnField, ); \ 4604 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4605 OPTIONAL(inlinedAt, MDField, ); \ 4606 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4607 PARSE_MD_FIELDS(); 4608 #undef VISIT_MD_FIELDS 4609 4610 Result = 4611 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4612 inlinedAt.Val, isImplicitCode.Val)); 4613 return false; 4614 } 4615 4616 /// parseGenericDINode: 4617 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4618 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { 4619 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4620 REQUIRED(tag, DwarfTagField, ); \ 4621 OPTIONAL(header, MDStringField, ); \ 4622 OPTIONAL(operands, MDFieldList, ); 4623 PARSE_MD_FIELDS(); 4624 #undef VISIT_MD_FIELDS 4625 4626 Result = GET_OR_DISTINCT(GenericDINode, 4627 (Context, tag.Val, header.Val, operands.Val)); 4628 return false; 4629 } 4630 4631 /// parseDISubrange: 4632 /// ::= !DISubrange(count: 30, lowerBound: 2) 4633 /// ::= !DISubrange(count: !node, lowerBound: 2) 4634 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 4635 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { 4636 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4637 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4638 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4639 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4640 OPTIONAL(stride, MDSignedOrMDField, ); 4641 PARSE_MD_FIELDS(); 4642 #undef VISIT_MD_FIELDS 4643 4644 Metadata *Count = nullptr; 4645 Metadata *LowerBound = nullptr; 4646 Metadata *UpperBound = nullptr; 4647 Metadata *Stride = nullptr; 4648 if (count.isMDSignedField()) 4649 Count = ConstantAsMetadata::get(ConstantInt::getSigned( 4650 Type::getInt64Ty(Context), count.getMDSignedValue())); 4651 else if (count.isMDField()) 4652 Count = count.getMDFieldValue(); 4653 4654 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4655 if (Bound.isMDSignedField()) 4656 return ConstantAsMetadata::get(ConstantInt::getSigned( 4657 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 4658 if (Bound.isMDField()) 4659 return Bound.getMDFieldValue(); 4660 return nullptr; 4661 }; 4662 4663 LowerBound = convToMetadata(lowerBound); 4664 UpperBound = convToMetadata(upperBound); 4665 Stride = convToMetadata(stride); 4666 4667 Result = GET_OR_DISTINCT(DISubrange, 4668 (Context, Count, LowerBound, UpperBound, Stride)); 4669 4670 return false; 4671 } 4672 4673 /// parseDIGenericSubrange: 4674 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: 4675 /// !node3) 4676 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { 4677 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4678 OPTIONAL(count, MDSignedOrMDField, ); \ 4679 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4680 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4681 OPTIONAL(stride, MDSignedOrMDField, ); 4682 PARSE_MD_FIELDS(); 4683 #undef VISIT_MD_FIELDS 4684 4685 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4686 if (Bound.isMDSignedField()) 4687 return DIExpression::get( 4688 Context, {dwarf::DW_OP_consts, 4689 static_cast<uint64_t>(Bound.getMDSignedValue())}); 4690 if (Bound.isMDField()) 4691 return Bound.getMDFieldValue(); 4692 return nullptr; 4693 }; 4694 4695 Metadata *Count = ConvToMetadata(count); 4696 Metadata *LowerBound = ConvToMetadata(lowerBound); 4697 Metadata *UpperBound = ConvToMetadata(upperBound); 4698 Metadata *Stride = ConvToMetadata(stride); 4699 4700 Result = GET_OR_DISTINCT(DIGenericSubrange, 4701 (Context, Count, LowerBound, UpperBound, Stride)); 4702 4703 return false; 4704 } 4705 4706 /// parseDIEnumerator: 4707 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4708 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4709 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4710 REQUIRED(name, MDStringField, ); \ 4711 REQUIRED(value, MDAPSIntField, ); \ 4712 OPTIONAL(isUnsigned, MDBoolField, (false)); 4713 PARSE_MD_FIELDS(); 4714 #undef VISIT_MD_FIELDS 4715 4716 if (isUnsigned.Val && value.Val.isNegative()) 4717 return tokError("unsigned enumerator with negative value"); 4718 4719 APSInt Value(value.Val); 4720 // Add a leading zero so that unsigned values with the msb set are not 4721 // mistaken for negative values when used for signed enumerators. 4722 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 4723 Value = Value.zext(Value.getBitWidth() + 1); 4724 4725 Result = 4726 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4727 4728 return false; 4729 } 4730 4731 /// parseDIBasicType: 4732 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4733 /// encoding: DW_ATE_encoding, flags: 0) 4734 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { 4735 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4736 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4737 OPTIONAL(name, MDStringField, ); \ 4738 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4739 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4740 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4741 OPTIONAL(flags, DIFlagField, ); 4742 PARSE_MD_FIELDS(); 4743 #undef VISIT_MD_FIELDS 4744 4745 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4746 align.Val, encoding.Val, flags.Val)); 4747 return false; 4748 } 4749 4750 /// parseDIStringType: 4751 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) 4752 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { 4753 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4754 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ 4755 OPTIONAL(name, MDStringField, ); \ 4756 OPTIONAL(stringLength, MDField, ); \ 4757 OPTIONAL(stringLengthExpression, MDField, ); \ 4758 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4759 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4760 OPTIONAL(encoding, DwarfAttEncodingField, ); 4761 PARSE_MD_FIELDS(); 4762 #undef VISIT_MD_FIELDS 4763 4764 Result = GET_OR_DISTINCT(DIStringType, 4765 (Context, tag.Val, name.Val, stringLength.Val, 4766 stringLengthExpression.Val, size.Val, align.Val, 4767 encoding.Val)); 4768 return false; 4769 } 4770 4771 /// parseDIDerivedType: 4772 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4773 /// line: 7, scope: !1, baseType: !2, size: 32, 4774 /// align: 32, offset: 0, flags: 0, extraData: !3, 4775 /// dwarfAddressSpace: 3) 4776 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4777 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4778 REQUIRED(tag, DwarfTagField, ); \ 4779 OPTIONAL(name, MDStringField, ); \ 4780 OPTIONAL(file, MDField, ); \ 4781 OPTIONAL(line, LineField, ); \ 4782 OPTIONAL(scope, MDField, ); \ 4783 REQUIRED(baseType, MDField, ); \ 4784 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4785 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4786 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4787 OPTIONAL(flags, DIFlagField, ); \ 4788 OPTIONAL(extraData, MDField, ); \ 4789 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 4790 PARSE_MD_FIELDS(); 4791 #undef VISIT_MD_FIELDS 4792 4793 Optional<unsigned> DWARFAddressSpace; 4794 if (dwarfAddressSpace.Val != UINT32_MAX) 4795 DWARFAddressSpace = dwarfAddressSpace.Val; 4796 4797 Result = GET_OR_DISTINCT(DIDerivedType, 4798 (Context, tag.Val, name.Val, file.Val, line.Val, 4799 scope.Val, baseType.Val, size.Val, align.Val, 4800 offset.Val, DWARFAddressSpace, flags.Val, 4801 extraData.Val)); 4802 return false; 4803 } 4804 4805 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { 4806 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4807 REQUIRED(tag, DwarfTagField, ); \ 4808 OPTIONAL(name, MDStringField, ); \ 4809 OPTIONAL(file, MDField, ); \ 4810 OPTIONAL(line, LineField, ); \ 4811 OPTIONAL(scope, MDField, ); \ 4812 OPTIONAL(baseType, MDField, ); \ 4813 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4814 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4815 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4816 OPTIONAL(flags, DIFlagField, ); \ 4817 OPTIONAL(elements, MDField, ); \ 4818 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4819 OPTIONAL(vtableHolder, MDField, ); \ 4820 OPTIONAL(templateParams, MDField, ); \ 4821 OPTIONAL(identifier, MDStringField, ); \ 4822 OPTIONAL(discriminator, MDField, ); \ 4823 OPTIONAL(dataLocation, MDField, ); \ 4824 OPTIONAL(associated, MDField, ); \ 4825 OPTIONAL(allocated, MDField, ); \ 4826 OPTIONAL(rank, MDSignedOrMDField, ); 4827 PARSE_MD_FIELDS(); 4828 #undef VISIT_MD_FIELDS 4829 4830 Metadata *Rank = nullptr; 4831 if (rank.isMDSignedField()) 4832 Rank = ConstantAsMetadata::get(ConstantInt::getSigned( 4833 Type::getInt64Ty(Context), rank.getMDSignedValue())); 4834 else if (rank.isMDField()) 4835 Rank = rank.getMDFieldValue(); 4836 4837 // If this has an identifier try to build an ODR type. 4838 if (identifier.Val) 4839 if (auto *CT = DICompositeType::buildODRType( 4840 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4841 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4842 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 4843 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4844 Rank)) { 4845 Result = CT; 4846 return false; 4847 } 4848 4849 // Create a new node, and save it in the context if it belongs in the type 4850 // map. 4851 Result = GET_OR_DISTINCT( 4852 DICompositeType, 4853 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4854 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4855 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4856 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4857 Rank)); 4858 return false; 4859 } 4860 4861 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4862 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4863 OPTIONAL(flags, DIFlagField, ); \ 4864 OPTIONAL(cc, DwarfCCField, ); \ 4865 REQUIRED(types, MDField, ); 4866 PARSE_MD_FIELDS(); 4867 #undef VISIT_MD_FIELDS 4868 4869 Result = GET_OR_DISTINCT(DISubroutineType, 4870 (Context, flags.Val, cc.Val, types.Val)); 4871 return false; 4872 } 4873 4874 /// parseDIFileType: 4875 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4876 /// checksumkind: CSK_MD5, 4877 /// checksum: "000102030405060708090a0b0c0d0e0f", 4878 /// source: "source file contents") 4879 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { 4880 // The default constructed value for checksumkind is required, but will never 4881 // be used, as the parser checks if the field was actually Seen before using 4882 // the Val. 4883 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4884 REQUIRED(filename, MDStringField, ); \ 4885 REQUIRED(directory, MDStringField, ); \ 4886 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4887 OPTIONAL(checksum, MDStringField, ); \ 4888 OPTIONAL(source, MDStringField, ); 4889 PARSE_MD_FIELDS(); 4890 #undef VISIT_MD_FIELDS 4891 4892 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4893 if (checksumkind.Seen && checksum.Seen) 4894 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4895 else if (checksumkind.Seen || checksum.Seen) 4896 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4897 4898 Optional<MDString *> OptSource; 4899 if (source.Seen) 4900 OptSource = source.Val; 4901 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4902 OptChecksum, OptSource)); 4903 return false; 4904 } 4905 4906 /// parseDICompileUnit: 4907 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4908 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4909 /// splitDebugFilename: "abc.debug", 4910 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4911 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4912 /// sysroot: "/", sdk: "MacOSX.sdk") 4913 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4914 if (!IsDistinct) 4915 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4916 4917 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4918 REQUIRED(language, DwarfLangField, ); \ 4919 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4920 OPTIONAL(producer, MDStringField, ); \ 4921 OPTIONAL(isOptimized, MDBoolField, ); \ 4922 OPTIONAL(flags, MDStringField, ); \ 4923 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4924 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4925 OPTIONAL(emissionKind, EmissionKindField, ); \ 4926 OPTIONAL(enums, MDField, ); \ 4927 OPTIONAL(retainedTypes, MDField, ); \ 4928 OPTIONAL(globals, MDField, ); \ 4929 OPTIONAL(imports, MDField, ); \ 4930 OPTIONAL(macros, MDField, ); \ 4931 OPTIONAL(dwoId, MDUnsignedField, ); \ 4932 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4933 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4934 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4935 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 4936 OPTIONAL(sysroot, MDStringField, ); \ 4937 OPTIONAL(sdk, MDStringField, ); 4938 PARSE_MD_FIELDS(); 4939 #undef VISIT_MD_FIELDS 4940 4941 Result = DICompileUnit::getDistinct( 4942 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4943 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4944 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4945 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4946 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 4947 return false; 4948 } 4949 4950 /// parseDISubprogram: 4951 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4952 /// file: !1, line: 7, type: !2, isLocal: false, 4953 /// isDefinition: true, scopeLine: 8, containingType: !3, 4954 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4955 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4956 /// spFlags: 10, isOptimized: false, templateParams: !4, 4957 /// declaration: !5, retainedNodes: !6, thrownTypes: !7) 4958 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { 4959 auto Loc = Lex.getLoc(); 4960 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4961 OPTIONAL(scope, MDField, ); \ 4962 OPTIONAL(name, MDStringField, ); \ 4963 OPTIONAL(linkageName, MDStringField, ); \ 4964 OPTIONAL(file, MDField, ); \ 4965 OPTIONAL(line, LineField, ); \ 4966 OPTIONAL(type, MDField, ); \ 4967 OPTIONAL(isLocal, MDBoolField, ); \ 4968 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4969 OPTIONAL(scopeLine, LineField, ); \ 4970 OPTIONAL(containingType, MDField, ); \ 4971 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4972 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4973 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4974 OPTIONAL(flags, DIFlagField, ); \ 4975 OPTIONAL(spFlags, DISPFlagField, ); \ 4976 OPTIONAL(isOptimized, MDBoolField, ); \ 4977 OPTIONAL(unit, MDField, ); \ 4978 OPTIONAL(templateParams, MDField, ); \ 4979 OPTIONAL(declaration, MDField, ); \ 4980 OPTIONAL(retainedNodes, MDField, ); \ 4981 OPTIONAL(thrownTypes, MDField, ); 4982 PARSE_MD_FIELDS(); 4983 #undef VISIT_MD_FIELDS 4984 4985 // An explicit spFlags field takes precedence over individual fields in 4986 // older IR versions. 4987 DISubprogram::DISPFlags SPFlags = 4988 spFlags.Seen ? spFlags.Val 4989 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4990 isOptimized.Val, virtuality.Val); 4991 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4992 return Lex.Error( 4993 Loc, 4994 "missing 'distinct', required for !DISubprogram that is a Definition"); 4995 Result = GET_OR_DISTINCT( 4996 DISubprogram, 4997 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4998 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 4999 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 5000 declaration.Val, retainedNodes.Val, thrownTypes.Val)); 5001 return false; 5002 } 5003 5004 /// parseDILexicalBlock: 5005 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 5006 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 5007 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5008 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5009 OPTIONAL(file, MDField, ); \ 5010 OPTIONAL(line, LineField, ); \ 5011 OPTIONAL(column, ColumnField, ); 5012 PARSE_MD_FIELDS(); 5013 #undef VISIT_MD_FIELDS 5014 5015 Result = GET_OR_DISTINCT( 5016 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 5017 return false; 5018 } 5019 5020 /// parseDILexicalBlockFile: 5021 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 5022 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 5023 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5024 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5025 OPTIONAL(file, MDField, ); \ 5026 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 5027 PARSE_MD_FIELDS(); 5028 #undef VISIT_MD_FIELDS 5029 5030 Result = GET_OR_DISTINCT(DILexicalBlockFile, 5031 (Context, scope.Val, file.Val, discriminator.Val)); 5032 return false; 5033 } 5034 5035 /// parseDICommonBlock: 5036 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 5037 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { 5038 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5039 REQUIRED(scope, MDField, ); \ 5040 OPTIONAL(declaration, MDField, ); \ 5041 OPTIONAL(name, MDStringField, ); \ 5042 OPTIONAL(file, MDField, ); \ 5043 OPTIONAL(line, LineField, ); 5044 PARSE_MD_FIELDS(); 5045 #undef VISIT_MD_FIELDS 5046 5047 Result = GET_OR_DISTINCT(DICommonBlock, 5048 (Context, scope.Val, declaration.Val, name.Val, 5049 file.Val, line.Val)); 5050 return false; 5051 } 5052 5053 /// parseDINamespace: 5054 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 5055 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { 5056 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5057 REQUIRED(scope, MDField, ); \ 5058 OPTIONAL(name, MDStringField, ); \ 5059 OPTIONAL(exportSymbols, MDBoolField, ); 5060 PARSE_MD_FIELDS(); 5061 #undef VISIT_MD_FIELDS 5062 5063 Result = GET_OR_DISTINCT(DINamespace, 5064 (Context, scope.Val, name.Val, exportSymbols.Val)); 5065 return false; 5066 } 5067 5068 /// parseDIMacro: 5069 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: 5070 /// "SomeValue") 5071 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { 5072 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5073 REQUIRED(type, DwarfMacinfoTypeField, ); \ 5074 OPTIONAL(line, LineField, ); \ 5075 REQUIRED(name, MDStringField, ); \ 5076 OPTIONAL(value, MDStringField, ); 5077 PARSE_MD_FIELDS(); 5078 #undef VISIT_MD_FIELDS 5079 5080 Result = GET_OR_DISTINCT(DIMacro, 5081 (Context, type.Val, line.Val, name.Val, value.Val)); 5082 return false; 5083 } 5084 5085 /// parseDIMacroFile: 5086 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 5087 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { 5088 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5089 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 5090 OPTIONAL(line, LineField, ); \ 5091 REQUIRED(file, MDField, ); \ 5092 OPTIONAL(nodes, MDField, ); 5093 PARSE_MD_FIELDS(); 5094 #undef VISIT_MD_FIELDS 5095 5096 Result = GET_OR_DISTINCT(DIMacroFile, 5097 (Context, type.Val, line.Val, file.Val, nodes.Val)); 5098 return false; 5099 } 5100 5101 /// parseDIModule: 5102 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 5103 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 5104 /// file: !1, line: 4) 5105 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { 5106 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5107 REQUIRED(scope, MDField, ); \ 5108 REQUIRED(name, MDStringField, ); \ 5109 OPTIONAL(configMacros, MDStringField, ); \ 5110 OPTIONAL(includePath, MDStringField, ); \ 5111 OPTIONAL(apinotes, MDStringField, ); \ 5112 OPTIONAL(file, MDField, ); \ 5113 OPTIONAL(line, LineField, ); 5114 PARSE_MD_FIELDS(); 5115 #undef VISIT_MD_FIELDS 5116 5117 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 5118 configMacros.Val, includePath.Val, 5119 apinotes.Val, line.Val)); 5120 return false; 5121 } 5122 5123 /// parseDITemplateTypeParameter: 5124 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 5125 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 5126 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5127 OPTIONAL(name, MDStringField, ); \ 5128 REQUIRED(type, MDField, ); \ 5129 OPTIONAL(defaulted, MDBoolField, ); 5130 PARSE_MD_FIELDS(); 5131 #undef VISIT_MD_FIELDS 5132 5133 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 5134 (Context, name.Val, type.Val, defaulted.Val)); 5135 return false; 5136 } 5137 5138 /// parseDITemplateValueParameter: 5139 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 5140 /// name: "V", type: !1, defaulted: false, 5141 /// value: i32 7) 5142 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 5143 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5144 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 5145 OPTIONAL(name, MDStringField, ); \ 5146 OPTIONAL(type, MDField, ); \ 5147 OPTIONAL(defaulted, MDBoolField, ); \ 5148 REQUIRED(value, MDField, ); 5149 5150 PARSE_MD_FIELDS(); 5151 #undef VISIT_MD_FIELDS 5152 5153 Result = GET_OR_DISTINCT( 5154 DITemplateValueParameter, 5155 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 5156 return false; 5157 } 5158 5159 /// parseDIGlobalVariable: 5160 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 5161 /// file: !1, line: 7, type: !2, isLocal: false, 5162 /// isDefinition: true, templateParams: !3, 5163 /// declaration: !4, align: 8) 5164 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 5165 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5166 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 5167 OPTIONAL(scope, MDField, ); \ 5168 OPTIONAL(linkageName, MDStringField, ); \ 5169 OPTIONAL(file, MDField, ); \ 5170 OPTIONAL(line, LineField, ); \ 5171 OPTIONAL(type, MDField, ); \ 5172 OPTIONAL(isLocal, MDBoolField, ); \ 5173 OPTIONAL(isDefinition, MDBoolField, (true)); \ 5174 OPTIONAL(templateParams, MDField, ); \ 5175 OPTIONAL(declaration, MDField, ); \ 5176 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 5177 PARSE_MD_FIELDS(); 5178 #undef VISIT_MD_FIELDS 5179 5180 Result = 5181 GET_OR_DISTINCT(DIGlobalVariable, 5182 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 5183 line.Val, type.Val, isLocal.Val, isDefinition.Val, 5184 declaration.Val, templateParams.Val, align.Val)); 5185 return false; 5186 } 5187 5188 /// parseDILocalVariable: 5189 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 5190 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5191 /// align: 8) 5192 /// ::= !DILocalVariable(scope: !0, name: "foo", 5193 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5194 /// align: 8) 5195 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { 5196 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5197 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5198 OPTIONAL(name, MDStringField, ); \ 5199 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 5200 OPTIONAL(file, MDField, ); \ 5201 OPTIONAL(line, LineField, ); \ 5202 OPTIONAL(type, MDField, ); \ 5203 OPTIONAL(flags, DIFlagField, ); \ 5204 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 5205 PARSE_MD_FIELDS(); 5206 #undef VISIT_MD_FIELDS 5207 5208 Result = GET_OR_DISTINCT(DILocalVariable, 5209 (Context, scope.Val, name.Val, file.Val, line.Val, 5210 type.Val, arg.Val, flags.Val, align.Val)); 5211 return false; 5212 } 5213 5214 /// parseDILabel: 5215 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 5216 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { 5217 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5218 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5219 REQUIRED(name, MDStringField, ); \ 5220 REQUIRED(file, MDField, ); \ 5221 REQUIRED(line, LineField, ); 5222 PARSE_MD_FIELDS(); 5223 #undef VISIT_MD_FIELDS 5224 5225 Result = GET_OR_DISTINCT(DILabel, 5226 (Context, scope.Val, name.Val, file.Val, line.Val)); 5227 return false; 5228 } 5229 5230 /// parseDIExpression: 5231 /// ::= !DIExpression(0, 7, -1) 5232 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { 5233 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5234 Lex.Lex(); 5235 5236 if (parseToken(lltok::lparen, "expected '(' here")) 5237 return true; 5238 5239 SmallVector<uint64_t, 8> Elements; 5240 if (Lex.getKind() != lltok::rparen) 5241 do { 5242 if (Lex.getKind() == lltok::DwarfOp) { 5243 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5244 Lex.Lex(); 5245 Elements.push_back(Op); 5246 continue; 5247 } 5248 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5249 } 5250 5251 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5252 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5253 Lex.Lex(); 5254 Elements.push_back(Op); 5255 continue; 5256 } 5257 return tokError(Twine("invalid DWARF attribute encoding '") + 5258 Lex.getStrVal() + "'"); 5259 } 5260 5261 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5262 return tokError("expected unsigned integer"); 5263 5264 auto &U = Lex.getAPSIntVal(); 5265 if (U.ugt(UINT64_MAX)) 5266 return tokError("element too large, limit is " + Twine(UINT64_MAX)); 5267 Elements.push_back(U.getZExtValue()); 5268 Lex.Lex(); 5269 } while (EatIfPresent(lltok::comma)); 5270 5271 if (parseToken(lltok::rparen, "expected ')' here")) 5272 return true; 5273 5274 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5275 return false; 5276 } 5277 5278 /// parseDIGlobalVariableExpression: 5279 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5280 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, 5281 bool IsDistinct) { 5282 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5283 REQUIRED(var, MDField, ); \ 5284 REQUIRED(expr, MDField, ); 5285 PARSE_MD_FIELDS(); 5286 #undef VISIT_MD_FIELDS 5287 5288 Result = 5289 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5290 return false; 5291 } 5292 5293 /// parseDIObjCProperty: 5294 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5295 /// getter: "getFoo", attributes: 7, type: !2) 5296 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5297 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5298 OPTIONAL(name, MDStringField, ); \ 5299 OPTIONAL(file, MDField, ); \ 5300 OPTIONAL(line, LineField, ); \ 5301 OPTIONAL(setter, MDStringField, ); \ 5302 OPTIONAL(getter, MDStringField, ); \ 5303 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5304 OPTIONAL(type, MDField, ); 5305 PARSE_MD_FIELDS(); 5306 #undef VISIT_MD_FIELDS 5307 5308 Result = GET_OR_DISTINCT(DIObjCProperty, 5309 (Context, name.Val, file.Val, line.Val, setter.Val, 5310 getter.Val, attributes.Val, type.Val)); 5311 return false; 5312 } 5313 5314 /// parseDIImportedEntity: 5315 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5316 /// line: 7, name: "foo") 5317 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5318 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5319 REQUIRED(tag, DwarfTagField, ); \ 5320 REQUIRED(scope, MDField, ); \ 5321 OPTIONAL(entity, MDField, ); \ 5322 OPTIONAL(file, MDField, ); \ 5323 OPTIONAL(line, LineField, ); \ 5324 OPTIONAL(name, MDStringField, ); 5325 PARSE_MD_FIELDS(); 5326 #undef VISIT_MD_FIELDS 5327 5328 Result = GET_OR_DISTINCT( 5329 DIImportedEntity, 5330 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val)); 5331 return false; 5332 } 5333 5334 #undef PARSE_MD_FIELD 5335 #undef NOP_FIELD 5336 #undef REQUIRE_FIELD 5337 #undef DECLARE_FIELD 5338 5339 /// parseMetadataAsValue 5340 /// ::= metadata i32 %local 5341 /// ::= metadata i32 @global 5342 /// ::= metadata i32 7 5343 /// ::= metadata !0 5344 /// ::= metadata !{...} 5345 /// ::= metadata !"string" 5346 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5347 // Note: the type 'metadata' has already been parsed. 5348 Metadata *MD; 5349 if (parseMetadata(MD, &PFS)) 5350 return true; 5351 5352 V = MetadataAsValue::get(Context, MD); 5353 return false; 5354 } 5355 5356 /// parseValueAsMetadata 5357 /// ::= i32 %local 5358 /// ::= i32 @global 5359 /// ::= i32 7 5360 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5361 PerFunctionState *PFS) { 5362 Type *Ty; 5363 LocTy Loc; 5364 if (parseType(Ty, TypeMsg, Loc)) 5365 return true; 5366 if (Ty->isMetadataTy()) 5367 return error(Loc, "invalid metadata-value-metadata roundtrip"); 5368 5369 Value *V; 5370 if (parseValue(Ty, V, PFS)) 5371 return true; 5372 5373 MD = ValueAsMetadata::get(V); 5374 return false; 5375 } 5376 5377 /// parseMetadata 5378 /// ::= i32 %local 5379 /// ::= i32 @global 5380 /// ::= i32 7 5381 /// ::= !42 5382 /// ::= !{...} 5383 /// ::= !"string" 5384 /// ::= !DILocation(...) 5385 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5386 if (Lex.getKind() == lltok::MetadataVar) { 5387 MDNode *N; 5388 if (parseSpecializedMDNode(N)) 5389 return true; 5390 MD = N; 5391 return false; 5392 } 5393 5394 // ValueAsMetadata: 5395 // <type> <value> 5396 if (Lex.getKind() != lltok::exclaim) 5397 return parseValueAsMetadata(MD, "expected metadata operand", PFS); 5398 5399 // '!'. 5400 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5401 Lex.Lex(); 5402 5403 // MDString: 5404 // ::= '!' STRINGCONSTANT 5405 if (Lex.getKind() == lltok::StringConstant) { 5406 MDString *S; 5407 if (parseMDString(S)) 5408 return true; 5409 MD = S; 5410 return false; 5411 } 5412 5413 // MDNode: 5414 // !{ ... } 5415 // !7 5416 MDNode *N; 5417 if (parseMDNodeTail(N)) 5418 return true; 5419 MD = N; 5420 return false; 5421 } 5422 5423 //===----------------------------------------------------------------------===// 5424 // Function Parsing. 5425 //===----------------------------------------------------------------------===// 5426 5427 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5428 PerFunctionState *PFS, bool IsCall) { 5429 if (Ty->isFunctionTy()) 5430 return error(ID.Loc, "functions are not values, refer to them as pointers"); 5431 5432 switch (ID.Kind) { 5433 case ValID::t_LocalID: 5434 if (!PFS) 5435 return error(ID.Loc, "invalid use of function-local name"); 5436 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5437 return V == nullptr; 5438 case ValID::t_LocalName: 5439 if (!PFS) 5440 return error(ID.Loc, "invalid use of function-local name"); 5441 V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall); 5442 return V == nullptr; 5443 case ValID::t_InlineAsm: { 5444 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5445 return error(ID.Loc, "invalid type for inline asm constraint string"); 5446 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, 5447 (ID.UIntVal >> 1) & 1, 5448 (InlineAsm::AsmDialect(ID.UIntVal >> 2))); 5449 return false; 5450 } 5451 case ValID::t_GlobalName: 5452 V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall); 5453 return V == nullptr; 5454 case ValID::t_GlobalID: 5455 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5456 return V == nullptr; 5457 case ValID::t_APSInt: 5458 if (!Ty->isIntegerTy()) 5459 return error(ID.Loc, "integer constant must have integer type"); 5460 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5461 V = ConstantInt::get(Context, ID.APSIntVal); 5462 return false; 5463 case ValID::t_APFloat: 5464 if (!Ty->isFloatingPointTy() || 5465 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5466 return error(ID.Loc, "floating point constant invalid for type"); 5467 5468 // The lexer has no type info, so builds all half, bfloat, float, and double 5469 // FP constants as double. Fix this here. Long double does not need this. 5470 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5471 // Check for signaling before potentially converting and losing that info. 5472 bool IsSNAN = ID.APFloatVal.isSignaling(); 5473 bool Ignored; 5474 if (Ty->isHalfTy()) 5475 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5476 &Ignored); 5477 else if (Ty->isBFloatTy()) 5478 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 5479 &Ignored); 5480 else if (Ty->isFloatTy()) 5481 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5482 &Ignored); 5483 if (IsSNAN) { 5484 // The convert call above may quiet an SNaN, so manufacture another 5485 // SNaN. The bitcast works because the payload (significand) parameter 5486 // is truncated to fit. 5487 APInt Payload = ID.APFloatVal.bitcastToAPInt(); 5488 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(), 5489 ID.APFloatVal.isNegative(), &Payload); 5490 } 5491 } 5492 V = ConstantFP::get(Context, ID.APFloatVal); 5493 5494 if (V->getType() != Ty) 5495 return error(ID.Loc, "floating point constant does not have type '" + 5496 getTypeString(Ty) + "'"); 5497 5498 return false; 5499 case ValID::t_Null: 5500 if (!Ty->isPointerTy()) 5501 return error(ID.Loc, "null must be a pointer type"); 5502 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5503 return false; 5504 case ValID::t_Undef: 5505 // FIXME: LabelTy should not be a first-class type. 5506 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5507 return error(ID.Loc, "invalid type for undef constant"); 5508 V = UndefValue::get(Ty); 5509 return false; 5510 case ValID::t_EmptyArray: 5511 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5512 return error(ID.Loc, "invalid empty array initializer"); 5513 V = UndefValue::get(Ty); 5514 return false; 5515 case ValID::t_Zero: 5516 // FIXME: LabelTy should not be a first-class type. 5517 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5518 return error(ID.Loc, "invalid type for null constant"); 5519 V = Constant::getNullValue(Ty); 5520 return false; 5521 case ValID::t_None: 5522 if (!Ty->isTokenTy()) 5523 return error(ID.Loc, "invalid type for none constant"); 5524 V = Constant::getNullValue(Ty); 5525 return false; 5526 case ValID::t_Constant: 5527 if (ID.ConstantVal->getType() != Ty) 5528 return error(ID.Loc, "constant expression type mismatch"); 5529 5530 V = ID.ConstantVal; 5531 return false; 5532 case ValID::t_ConstantStruct: 5533 case ValID::t_PackedConstantStruct: 5534 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5535 if (ST->getNumElements() != ID.UIntVal) 5536 return error(ID.Loc, 5537 "initializer with struct type has wrong # elements"); 5538 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5539 return error(ID.Loc, "packed'ness of initializer and type don't match"); 5540 5541 // Verify that the elements are compatible with the structtype. 5542 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5543 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5544 return error( 5545 ID.Loc, 5546 "element " + Twine(i) + 5547 " of struct initializer doesn't match struct element type"); 5548 5549 V = ConstantStruct::get( 5550 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5551 } else 5552 return error(ID.Loc, "constant expression type mismatch"); 5553 return false; 5554 } 5555 llvm_unreachable("Invalid ValID"); 5556 } 5557 5558 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5559 C = nullptr; 5560 ValID ID; 5561 auto Loc = Lex.getLoc(); 5562 if (parseValID(ID, /*PFS=*/nullptr)) 5563 return true; 5564 switch (ID.Kind) { 5565 case ValID::t_APSInt: 5566 case ValID::t_APFloat: 5567 case ValID::t_Undef: 5568 case ValID::t_Constant: 5569 case ValID::t_ConstantStruct: 5570 case ValID::t_PackedConstantStruct: { 5571 Value *V; 5572 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false)) 5573 return true; 5574 assert(isa<Constant>(V) && "Expected a constant value"); 5575 C = cast<Constant>(V); 5576 return false; 5577 } 5578 case ValID::t_Null: 5579 C = Constant::getNullValue(Ty); 5580 return false; 5581 default: 5582 return error(Loc, "expected a constant value"); 5583 } 5584 } 5585 5586 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5587 V = nullptr; 5588 ValID ID; 5589 return parseValID(ID, PFS) || 5590 convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false); 5591 } 5592 5593 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5594 Type *Ty = nullptr; 5595 return parseType(Ty) || parseValue(Ty, V, PFS); 5596 } 5597 5598 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5599 PerFunctionState &PFS) { 5600 Value *V; 5601 Loc = Lex.getLoc(); 5602 if (parseTypeAndValue(V, PFS)) 5603 return true; 5604 if (!isa<BasicBlock>(V)) 5605 return error(Loc, "expected a basic block"); 5606 BB = cast<BasicBlock>(V); 5607 return false; 5608 } 5609 5610 /// FunctionHeader 5611 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5612 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5613 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5614 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5615 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) { 5616 // parse the linkage. 5617 LocTy LinkageLoc = Lex.getLoc(); 5618 unsigned Linkage; 5619 unsigned Visibility; 5620 unsigned DLLStorageClass; 5621 bool DSOLocal; 5622 AttrBuilder RetAttrs; 5623 unsigned CC; 5624 bool HasLinkage; 5625 Type *RetType = nullptr; 5626 LocTy RetTypeLoc = Lex.getLoc(); 5627 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5628 DSOLocal) || 5629 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 5630 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 5631 return true; 5632 5633 // Verify that the linkage is ok. 5634 switch ((GlobalValue::LinkageTypes)Linkage) { 5635 case GlobalValue::ExternalLinkage: 5636 break; // always ok. 5637 case GlobalValue::ExternalWeakLinkage: 5638 if (IsDefine) 5639 return error(LinkageLoc, "invalid linkage for function definition"); 5640 break; 5641 case GlobalValue::PrivateLinkage: 5642 case GlobalValue::InternalLinkage: 5643 case GlobalValue::AvailableExternallyLinkage: 5644 case GlobalValue::LinkOnceAnyLinkage: 5645 case GlobalValue::LinkOnceODRLinkage: 5646 case GlobalValue::WeakAnyLinkage: 5647 case GlobalValue::WeakODRLinkage: 5648 if (!IsDefine) 5649 return error(LinkageLoc, "invalid linkage for function declaration"); 5650 break; 5651 case GlobalValue::AppendingLinkage: 5652 case GlobalValue::CommonLinkage: 5653 return error(LinkageLoc, "invalid function linkage type"); 5654 } 5655 5656 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5657 return error(LinkageLoc, 5658 "symbol with local linkage must have default visibility"); 5659 5660 if (!FunctionType::isValidReturnType(RetType)) 5661 return error(RetTypeLoc, "invalid function return type"); 5662 5663 LocTy NameLoc = Lex.getLoc(); 5664 5665 std::string FunctionName; 5666 if (Lex.getKind() == lltok::GlobalVar) { 5667 FunctionName = Lex.getStrVal(); 5668 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5669 unsigned NameID = Lex.getUIntVal(); 5670 5671 if (NameID != NumberedVals.size()) 5672 return tokError("function expected to be numbered '%" + 5673 Twine(NumberedVals.size()) + "'"); 5674 } else { 5675 return tokError("expected function name"); 5676 } 5677 5678 Lex.Lex(); 5679 5680 if (Lex.getKind() != lltok::lparen) 5681 return tokError("expected '(' in function argument list"); 5682 5683 SmallVector<ArgInfo, 8> ArgList; 5684 bool IsVarArg; 5685 AttrBuilder FuncAttrs; 5686 std::vector<unsigned> FwdRefAttrGrps; 5687 LocTy BuiltinLoc; 5688 std::string Section; 5689 std::string Partition; 5690 MaybeAlign Alignment; 5691 std::string GC; 5692 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5693 unsigned AddrSpace = 0; 5694 Constant *Prefix = nullptr; 5695 Constant *Prologue = nullptr; 5696 Constant *PersonalityFn = nullptr; 5697 Comdat *C; 5698 5699 if (parseArgumentList(ArgList, IsVarArg) || 5700 parseOptionalUnnamedAddr(UnnamedAddr) || 5701 parseOptionalProgramAddrSpace(AddrSpace) || 5702 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5703 BuiltinLoc) || 5704 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 5705 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 5706 parseOptionalComdat(FunctionName, C) || 5707 parseOptionalAlignment(Alignment) || 5708 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 5709 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 5710 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 5711 (EatIfPresent(lltok::kw_personality) && 5712 parseGlobalTypeAndValue(PersonalityFn))) 5713 return true; 5714 5715 if (FuncAttrs.contains(Attribute::Builtin)) 5716 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 5717 5718 // If the alignment was parsed as an attribute, move to the alignment field. 5719 if (FuncAttrs.hasAlignmentAttr()) { 5720 Alignment = FuncAttrs.getAlignment(); 5721 FuncAttrs.removeAttribute(Attribute::Alignment); 5722 } 5723 5724 // Okay, if we got here, the function is syntactically valid. Convert types 5725 // and do semantic checks. 5726 std::vector<Type*> ParamTypeList; 5727 SmallVector<AttributeSet, 8> Attrs; 5728 5729 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5730 ParamTypeList.push_back(ArgList[i].Ty); 5731 Attrs.push_back(ArgList[i].Attrs); 5732 } 5733 5734 AttributeList PAL = 5735 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5736 AttributeSet::get(Context, RetAttrs), Attrs); 5737 5738 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 5739 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 5740 5741 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 5742 PointerType *PFT = PointerType::get(FT, AddrSpace); 5743 5744 Fn = nullptr; 5745 if (!FunctionName.empty()) { 5746 // If this was a definition of a forward reference, remove the definition 5747 // from the forward reference table and fill in the forward ref. 5748 auto FRVI = ForwardRefVals.find(FunctionName); 5749 if (FRVI != ForwardRefVals.end()) { 5750 Fn = M->getFunction(FunctionName); 5751 if (!Fn) 5752 return error(FRVI->second.second, "invalid forward reference to " 5753 "function as global value!"); 5754 if (Fn->getType() != PFT) 5755 return error(FRVI->second.second, 5756 "invalid forward reference to " 5757 "function '" + 5758 FunctionName + 5759 "' with wrong type: " 5760 "expected '" + 5761 getTypeString(PFT) + "' but was '" + 5762 getTypeString(Fn->getType()) + "'"); 5763 ForwardRefVals.erase(FRVI); 5764 } else if ((Fn = M->getFunction(FunctionName))) { 5765 // Reject redefinitions. 5766 return error(NameLoc, 5767 "invalid redefinition of function '" + FunctionName + "'"); 5768 } else if (M->getNamedValue(FunctionName)) { 5769 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5770 } 5771 5772 } else { 5773 // If this is a definition of a forward referenced function, make sure the 5774 // types agree. 5775 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5776 if (I != ForwardRefValIDs.end()) { 5777 Fn = cast<Function>(I->second.first); 5778 if (Fn->getType() != PFT) 5779 return error(NameLoc, "type of definition and forward reference of '@" + 5780 Twine(NumberedVals.size()) + 5781 "' disagree: " 5782 "expected '" + 5783 getTypeString(PFT) + "' but was '" + 5784 getTypeString(Fn->getType()) + "'"); 5785 ForwardRefValIDs.erase(I); 5786 } 5787 } 5788 5789 if (!Fn) 5790 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5791 FunctionName, M); 5792 else // Move the forward-reference to the correct spot in the module. 5793 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 5794 5795 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5796 5797 if (FunctionName.empty()) 5798 NumberedVals.push_back(Fn); 5799 5800 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5801 maybeSetDSOLocal(DSOLocal, *Fn); 5802 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5803 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5804 Fn->setCallingConv(CC); 5805 Fn->setAttributes(PAL); 5806 Fn->setUnnamedAddr(UnnamedAddr); 5807 Fn->setAlignment(MaybeAlign(Alignment)); 5808 Fn->setSection(Section); 5809 Fn->setPartition(Partition); 5810 Fn->setComdat(C); 5811 Fn->setPersonalityFn(PersonalityFn); 5812 if (!GC.empty()) Fn->setGC(GC); 5813 Fn->setPrefixData(Prefix); 5814 Fn->setPrologueData(Prologue); 5815 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5816 5817 // Add all of the arguments we parsed to the function. 5818 Function::arg_iterator ArgIt = Fn->arg_begin(); 5819 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5820 // If the argument has a name, insert it into the argument symbol table. 5821 if (ArgList[i].Name.empty()) continue; 5822 5823 // Set the name, if it conflicted, it will be auto-renamed. 5824 ArgIt->setName(ArgList[i].Name); 5825 5826 if (ArgIt->getName() != ArgList[i].Name) 5827 return error(ArgList[i].Loc, 5828 "redefinition of argument '%" + ArgList[i].Name + "'"); 5829 } 5830 5831 if (IsDefine) 5832 return false; 5833 5834 // Check the declaration has no block address forward references. 5835 ValID ID; 5836 if (FunctionName.empty()) { 5837 ID.Kind = ValID::t_GlobalID; 5838 ID.UIntVal = NumberedVals.size() - 1; 5839 } else { 5840 ID.Kind = ValID::t_GlobalName; 5841 ID.StrVal = FunctionName; 5842 } 5843 auto Blocks = ForwardRefBlockAddresses.find(ID); 5844 if (Blocks != ForwardRefBlockAddresses.end()) 5845 return error(Blocks->first.Loc, 5846 "cannot take blockaddress inside a declaration"); 5847 return false; 5848 } 5849 5850 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5851 ValID ID; 5852 if (FunctionNumber == -1) { 5853 ID.Kind = ValID::t_GlobalName; 5854 ID.StrVal = std::string(F.getName()); 5855 } else { 5856 ID.Kind = ValID::t_GlobalID; 5857 ID.UIntVal = FunctionNumber; 5858 } 5859 5860 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5861 if (Blocks == P.ForwardRefBlockAddresses.end()) 5862 return false; 5863 5864 for (const auto &I : Blocks->second) { 5865 const ValID &BBID = I.first; 5866 GlobalValue *GV = I.second; 5867 5868 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5869 "Expected local id or name"); 5870 BasicBlock *BB; 5871 if (BBID.Kind == ValID::t_LocalName) 5872 BB = getBB(BBID.StrVal, BBID.Loc); 5873 else 5874 BB = getBB(BBID.UIntVal, BBID.Loc); 5875 if (!BB) 5876 return P.error(BBID.Loc, "referenced value is not a basic block"); 5877 5878 GV->replaceAllUsesWith(BlockAddress::get(&F, BB)); 5879 GV->eraseFromParent(); 5880 } 5881 5882 P.ForwardRefBlockAddresses.erase(Blocks); 5883 return false; 5884 } 5885 5886 /// parseFunctionBody 5887 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5888 bool LLParser::parseFunctionBody(Function &Fn) { 5889 if (Lex.getKind() != lltok::lbrace) 5890 return tokError("expected '{' in function body"); 5891 Lex.Lex(); // eat the {. 5892 5893 int FunctionNumber = -1; 5894 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5895 5896 PerFunctionState PFS(*this, Fn, FunctionNumber); 5897 5898 // Resolve block addresses and allow basic blocks to be forward-declared 5899 // within this function. 5900 if (PFS.resolveForwardRefBlockAddresses()) 5901 return true; 5902 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5903 5904 // We need at least one basic block. 5905 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5906 return tokError("function body requires at least one basic block"); 5907 5908 while (Lex.getKind() != lltok::rbrace && 5909 Lex.getKind() != lltok::kw_uselistorder) 5910 if (parseBasicBlock(PFS)) 5911 return true; 5912 5913 while (Lex.getKind() != lltok::rbrace) 5914 if (parseUseListOrder(&PFS)) 5915 return true; 5916 5917 // Eat the }. 5918 Lex.Lex(); 5919 5920 // Verify function is ok. 5921 return PFS.finishFunction(); 5922 } 5923 5924 /// parseBasicBlock 5925 /// ::= (LabelStr|LabelID)? Instruction* 5926 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 5927 // If this basic block starts out with a name, remember it. 5928 std::string Name; 5929 int NameID = -1; 5930 LocTy NameLoc = Lex.getLoc(); 5931 if (Lex.getKind() == lltok::LabelStr) { 5932 Name = Lex.getStrVal(); 5933 Lex.Lex(); 5934 } else if (Lex.getKind() == lltok::LabelID) { 5935 NameID = Lex.getUIntVal(); 5936 Lex.Lex(); 5937 } 5938 5939 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 5940 if (!BB) 5941 return true; 5942 5943 std::string NameStr; 5944 5945 // parse the instructions in this block until we get a terminator. 5946 Instruction *Inst; 5947 do { 5948 // This instruction may have three possibilities for a name: a) none 5949 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5950 LocTy NameLoc = Lex.getLoc(); 5951 int NameID = -1; 5952 NameStr = ""; 5953 5954 if (Lex.getKind() == lltok::LocalVarID) { 5955 NameID = Lex.getUIntVal(); 5956 Lex.Lex(); 5957 if (parseToken(lltok::equal, "expected '=' after instruction id")) 5958 return true; 5959 } else if (Lex.getKind() == lltok::LocalVar) { 5960 NameStr = Lex.getStrVal(); 5961 Lex.Lex(); 5962 if (parseToken(lltok::equal, "expected '=' after instruction name")) 5963 return true; 5964 } 5965 5966 switch (parseInstruction(Inst, BB, PFS)) { 5967 default: 5968 llvm_unreachable("Unknown parseInstruction result!"); 5969 case InstError: return true; 5970 case InstNormal: 5971 BB->getInstList().push_back(Inst); 5972 5973 // With a normal result, we check to see if the instruction is followed by 5974 // a comma and metadata. 5975 if (EatIfPresent(lltok::comma)) 5976 if (parseInstructionMetadata(*Inst)) 5977 return true; 5978 break; 5979 case InstExtraComma: 5980 BB->getInstList().push_back(Inst); 5981 5982 // If the instruction parser ate an extra comma at the end of it, it 5983 // *must* be followed by metadata. 5984 if (parseInstructionMetadata(*Inst)) 5985 return true; 5986 break; 5987 } 5988 5989 // Set the name on the instruction. 5990 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 5991 return true; 5992 } while (!Inst->isTerminator()); 5993 5994 return false; 5995 } 5996 5997 //===----------------------------------------------------------------------===// 5998 // Instruction Parsing. 5999 //===----------------------------------------------------------------------===// 6000 6001 /// parseInstruction - parse one of the many different instructions. 6002 /// 6003 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 6004 PerFunctionState &PFS) { 6005 lltok::Kind Token = Lex.getKind(); 6006 if (Token == lltok::Eof) 6007 return tokError("found end of file when expecting more instructions"); 6008 LocTy Loc = Lex.getLoc(); 6009 unsigned KeywordVal = Lex.getUIntVal(); 6010 Lex.Lex(); // Eat the keyword. 6011 6012 switch (Token) { 6013 default: 6014 return error(Loc, "expected instruction opcode"); 6015 // Terminator Instructions. 6016 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 6017 case lltok::kw_ret: 6018 return parseRet(Inst, BB, PFS); 6019 case lltok::kw_br: 6020 return parseBr(Inst, PFS); 6021 case lltok::kw_switch: 6022 return parseSwitch(Inst, PFS); 6023 case lltok::kw_indirectbr: 6024 return parseIndirectBr(Inst, PFS); 6025 case lltok::kw_invoke: 6026 return parseInvoke(Inst, PFS); 6027 case lltok::kw_resume: 6028 return parseResume(Inst, PFS); 6029 case lltok::kw_cleanupret: 6030 return parseCleanupRet(Inst, PFS); 6031 case lltok::kw_catchret: 6032 return parseCatchRet(Inst, PFS); 6033 case lltok::kw_catchswitch: 6034 return parseCatchSwitch(Inst, PFS); 6035 case lltok::kw_catchpad: 6036 return parseCatchPad(Inst, PFS); 6037 case lltok::kw_cleanuppad: 6038 return parseCleanupPad(Inst, PFS); 6039 case lltok::kw_callbr: 6040 return parseCallBr(Inst, PFS); 6041 // Unary Operators. 6042 case lltok::kw_fneg: { 6043 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6044 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 6045 if (Res != 0) 6046 return Res; 6047 if (FMF.any()) 6048 Inst->setFastMathFlags(FMF); 6049 return false; 6050 } 6051 // Binary Operators. 6052 case lltok::kw_add: 6053 case lltok::kw_sub: 6054 case lltok::kw_mul: 6055 case lltok::kw_shl: { 6056 bool NUW = EatIfPresent(lltok::kw_nuw); 6057 bool NSW = EatIfPresent(lltok::kw_nsw); 6058 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 6059 6060 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6061 return true; 6062 6063 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 6064 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 6065 return false; 6066 } 6067 case lltok::kw_fadd: 6068 case lltok::kw_fsub: 6069 case lltok::kw_fmul: 6070 case lltok::kw_fdiv: 6071 case lltok::kw_frem: { 6072 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6073 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 6074 if (Res != 0) 6075 return Res; 6076 if (FMF.any()) 6077 Inst->setFastMathFlags(FMF); 6078 return 0; 6079 } 6080 6081 case lltok::kw_sdiv: 6082 case lltok::kw_udiv: 6083 case lltok::kw_lshr: 6084 case lltok::kw_ashr: { 6085 bool Exact = EatIfPresent(lltok::kw_exact); 6086 6087 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6088 return true; 6089 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 6090 return false; 6091 } 6092 6093 case lltok::kw_urem: 6094 case lltok::kw_srem: 6095 return parseArithmetic(Inst, PFS, KeywordVal, 6096 /*IsFP*/ false); 6097 case lltok::kw_and: 6098 case lltok::kw_or: 6099 case lltok::kw_xor: 6100 return parseLogical(Inst, PFS, KeywordVal); 6101 case lltok::kw_icmp: 6102 return parseCompare(Inst, PFS, KeywordVal); 6103 case lltok::kw_fcmp: { 6104 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6105 int Res = parseCompare(Inst, PFS, KeywordVal); 6106 if (Res != 0) 6107 return Res; 6108 if (FMF.any()) 6109 Inst->setFastMathFlags(FMF); 6110 return 0; 6111 } 6112 6113 // Casts. 6114 case lltok::kw_trunc: 6115 case lltok::kw_zext: 6116 case lltok::kw_sext: 6117 case lltok::kw_fptrunc: 6118 case lltok::kw_fpext: 6119 case lltok::kw_bitcast: 6120 case lltok::kw_addrspacecast: 6121 case lltok::kw_uitofp: 6122 case lltok::kw_sitofp: 6123 case lltok::kw_fptoui: 6124 case lltok::kw_fptosi: 6125 case lltok::kw_inttoptr: 6126 case lltok::kw_ptrtoint: 6127 return parseCast(Inst, PFS, KeywordVal); 6128 // Other. 6129 case lltok::kw_select: { 6130 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6131 int Res = parseSelect(Inst, PFS); 6132 if (Res != 0) 6133 return Res; 6134 if (FMF.any()) { 6135 if (!isa<FPMathOperator>(Inst)) 6136 return error(Loc, "fast-math-flags specified for select without " 6137 "floating-point scalar or vector return type"); 6138 Inst->setFastMathFlags(FMF); 6139 } 6140 return 0; 6141 } 6142 case lltok::kw_va_arg: 6143 return parseVAArg(Inst, PFS); 6144 case lltok::kw_extractelement: 6145 return parseExtractElement(Inst, PFS); 6146 case lltok::kw_insertelement: 6147 return parseInsertElement(Inst, PFS); 6148 case lltok::kw_shufflevector: 6149 return parseShuffleVector(Inst, PFS); 6150 case lltok::kw_phi: { 6151 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6152 int Res = parsePHI(Inst, PFS); 6153 if (Res != 0) 6154 return Res; 6155 if (FMF.any()) { 6156 if (!isa<FPMathOperator>(Inst)) 6157 return error(Loc, "fast-math-flags specified for phi without " 6158 "floating-point scalar or vector return type"); 6159 Inst->setFastMathFlags(FMF); 6160 } 6161 return 0; 6162 } 6163 case lltok::kw_landingpad: 6164 return parseLandingPad(Inst, PFS); 6165 case lltok::kw_freeze: 6166 return parseFreeze(Inst, PFS); 6167 // Call. 6168 case lltok::kw_call: 6169 return parseCall(Inst, PFS, CallInst::TCK_None); 6170 case lltok::kw_tail: 6171 return parseCall(Inst, PFS, CallInst::TCK_Tail); 6172 case lltok::kw_musttail: 6173 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 6174 case lltok::kw_notail: 6175 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 6176 // Memory. 6177 case lltok::kw_alloca: 6178 return parseAlloc(Inst, PFS); 6179 case lltok::kw_load: 6180 return parseLoad(Inst, PFS); 6181 case lltok::kw_store: 6182 return parseStore(Inst, PFS); 6183 case lltok::kw_cmpxchg: 6184 return parseCmpXchg(Inst, PFS); 6185 case lltok::kw_atomicrmw: 6186 return parseAtomicRMW(Inst, PFS); 6187 case lltok::kw_fence: 6188 return parseFence(Inst, PFS); 6189 case lltok::kw_getelementptr: 6190 return parseGetElementPtr(Inst, PFS); 6191 case lltok::kw_extractvalue: 6192 return parseExtractValue(Inst, PFS); 6193 case lltok::kw_insertvalue: 6194 return parseInsertValue(Inst, PFS); 6195 } 6196 } 6197 6198 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 6199 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 6200 if (Opc == Instruction::FCmp) { 6201 switch (Lex.getKind()) { 6202 default: 6203 return tokError("expected fcmp predicate (e.g. 'oeq')"); 6204 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 6205 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 6206 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 6207 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 6208 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 6209 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 6210 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 6211 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 6212 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 6213 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 6214 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 6215 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 6216 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 6217 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 6218 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 6219 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 6220 } 6221 } else { 6222 switch (Lex.getKind()) { 6223 default: 6224 return tokError("expected icmp predicate (e.g. 'eq')"); 6225 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 6226 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 6227 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 6228 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 6229 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 6230 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 6231 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 6232 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 6233 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 6234 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 6235 } 6236 } 6237 Lex.Lex(); 6238 return false; 6239 } 6240 6241 //===----------------------------------------------------------------------===// 6242 // Terminator Instructions. 6243 //===----------------------------------------------------------------------===// 6244 6245 /// parseRet - parse a return instruction. 6246 /// ::= 'ret' void (',' !dbg, !1)* 6247 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 6248 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 6249 PerFunctionState &PFS) { 6250 SMLoc TypeLoc = Lex.getLoc(); 6251 Type *Ty = nullptr; 6252 if (parseType(Ty, true /*void allowed*/)) 6253 return true; 6254 6255 Type *ResType = PFS.getFunction().getReturnType(); 6256 6257 if (Ty->isVoidTy()) { 6258 if (!ResType->isVoidTy()) 6259 return error(TypeLoc, "value doesn't match function result type '" + 6260 getTypeString(ResType) + "'"); 6261 6262 Inst = ReturnInst::Create(Context); 6263 return false; 6264 } 6265 6266 Value *RV; 6267 if (parseValue(Ty, RV, PFS)) 6268 return true; 6269 6270 if (ResType != RV->getType()) 6271 return error(TypeLoc, "value doesn't match function result type '" + 6272 getTypeString(ResType) + "'"); 6273 6274 Inst = ReturnInst::Create(Context, RV); 6275 return false; 6276 } 6277 6278 /// parseBr 6279 /// ::= 'br' TypeAndValue 6280 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6281 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 6282 LocTy Loc, Loc2; 6283 Value *Op0; 6284 BasicBlock *Op1, *Op2; 6285 if (parseTypeAndValue(Op0, Loc, PFS)) 6286 return true; 6287 6288 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6289 Inst = BranchInst::Create(BB); 6290 return false; 6291 } 6292 6293 if (Op0->getType() != Type::getInt1Ty(Context)) 6294 return error(Loc, "branch condition must have 'i1' type"); 6295 6296 if (parseToken(lltok::comma, "expected ',' after branch condition") || 6297 parseTypeAndBasicBlock(Op1, Loc, PFS) || 6298 parseToken(lltok::comma, "expected ',' after true destination") || 6299 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 6300 return true; 6301 6302 Inst = BranchInst::Create(Op1, Op2, Op0); 6303 return false; 6304 } 6305 6306 /// parseSwitch 6307 /// Instruction 6308 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6309 /// JumpTable 6310 /// ::= (TypeAndValue ',' TypeAndValue)* 6311 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6312 LocTy CondLoc, BBLoc; 6313 Value *Cond; 6314 BasicBlock *DefaultBB; 6315 if (parseTypeAndValue(Cond, CondLoc, PFS) || 6316 parseToken(lltok::comma, "expected ',' after switch condition") || 6317 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6318 parseToken(lltok::lsquare, "expected '[' with switch table")) 6319 return true; 6320 6321 if (!Cond->getType()->isIntegerTy()) 6322 return error(CondLoc, "switch condition must have integer type"); 6323 6324 // parse the jump table pairs. 6325 SmallPtrSet<Value*, 32> SeenCases; 6326 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6327 while (Lex.getKind() != lltok::rsquare) { 6328 Value *Constant; 6329 BasicBlock *DestBB; 6330 6331 if (parseTypeAndValue(Constant, CondLoc, PFS) || 6332 parseToken(lltok::comma, "expected ',' after case value") || 6333 parseTypeAndBasicBlock(DestBB, PFS)) 6334 return true; 6335 6336 if (!SeenCases.insert(Constant).second) 6337 return error(CondLoc, "duplicate case value in switch"); 6338 if (!isa<ConstantInt>(Constant)) 6339 return error(CondLoc, "case value is not a constant integer"); 6340 6341 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6342 } 6343 6344 Lex.Lex(); // Eat the ']'. 6345 6346 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6347 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6348 SI->addCase(Table[i].first, Table[i].second); 6349 Inst = SI; 6350 return false; 6351 } 6352 6353 /// parseIndirectBr 6354 /// Instruction 6355 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6356 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6357 LocTy AddrLoc; 6358 Value *Address; 6359 if (parseTypeAndValue(Address, AddrLoc, PFS) || 6360 parseToken(lltok::comma, "expected ',' after indirectbr address") || 6361 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 6362 return true; 6363 6364 if (!Address->getType()->isPointerTy()) 6365 return error(AddrLoc, "indirectbr address must have pointer type"); 6366 6367 // parse the destination list. 6368 SmallVector<BasicBlock*, 16> DestList; 6369 6370 if (Lex.getKind() != lltok::rsquare) { 6371 BasicBlock *DestBB; 6372 if (parseTypeAndBasicBlock(DestBB, PFS)) 6373 return true; 6374 DestList.push_back(DestBB); 6375 6376 while (EatIfPresent(lltok::comma)) { 6377 if (parseTypeAndBasicBlock(DestBB, PFS)) 6378 return true; 6379 DestList.push_back(DestBB); 6380 } 6381 } 6382 6383 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6384 return true; 6385 6386 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6387 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6388 IBI->addDestination(DestList[i]); 6389 Inst = IBI; 6390 return false; 6391 } 6392 6393 /// parseInvoke 6394 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6395 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6396 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6397 LocTy CallLoc = Lex.getLoc(); 6398 AttrBuilder RetAttrs, FnAttrs; 6399 std::vector<unsigned> FwdRefAttrGrps; 6400 LocTy NoBuiltinLoc; 6401 unsigned CC; 6402 unsigned InvokeAddrSpace; 6403 Type *RetType = nullptr; 6404 LocTy RetTypeLoc; 6405 ValID CalleeID; 6406 SmallVector<ParamInfo, 16> ArgList; 6407 SmallVector<OperandBundleDef, 2> BundleList; 6408 6409 BasicBlock *NormalBB, *UnwindBB; 6410 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6411 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 6412 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6413 parseValID(CalleeID) || parseParameterList(ArgList, PFS) || 6414 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6415 NoBuiltinLoc) || 6416 parseOptionalOperandBundles(BundleList, PFS) || 6417 parseToken(lltok::kw_to, "expected 'to' in invoke") || 6418 parseTypeAndBasicBlock(NormalBB, PFS) || 6419 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6420 parseTypeAndBasicBlock(UnwindBB, PFS)) 6421 return true; 6422 6423 // If RetType is a non-function pointer type, then this is the short syntax 6424 // for the call, which means that RetType is just the return type. Infer the 6425 // rest of the function argument types from the arguments that are present. 6426 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6427 if (!Ty) { 6428 // Pull out the types of all of the arguments... 6429 std::vector<Type*> ParamTypes; 6430 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6431 ParamTypes.push_back(ArgList[i].V->getType()); 6432 6433 if (!FunctionType::isValidReturnType(RetType)) 6434 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6435 6436 Ty = FunctionType::get(RetType, ParamTypes, false); 6437 } 6438 6439 CalleeID.FTy = Ty; 6440 6441 // Look up the callee. 6442 Value *Callee; 6443 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6444 Callee, &PFS, /*IsCall=*/true)) 6445 return true; 6446 6447 // Set up the Attribute for the function. 6448 SmallVector<Value *, 8> Args; 6449 SmallVector<AttributeSet, 8> ArgAttrs; 6450 6451 // Loop through FunctionType's arguments and ensure they are specified 6452 // correctly. Also, gather any parameter attributes. 6453 FunctionType::param_iterator I = Ty->param_begin(); 6454 FunctionType::param_iterator E = Ty->param_end(); 6455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6456 Type *ExpectedTy = nullptr; 6457 if (I != E) { 6458 ExpectedTy = *I++; 6459 } else if (!Ty->isVarArg()) { 6460 return error(ArgList[i].Loc, "too many arguments specified"); 6461 } 6462 6463 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6464 return error(ArgList[i].Loc, "argument is not of expected type '" + 6465 getTypeString(ExpectedTy) + "'"); 6466 Args.push_back(ArgList[i].V); 6467 ArgAttrs.push_back(ArgList[i].Attrs); 6468 } 6469 6470 if (I != E) 6471 return error(CallLoc, "not enough parameters specified for call"); 6472 6473 if (FnAttrs.hasAlignmentAttr()) 6474 return error(CallLoc, "invoke instructions may not have an alignment"); 6475 6476 // Finish off the Attribute and check them 6477 AttributeList PAL = 6478 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6479 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6480 6481 InvokeInst *II = 6482 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6483 II->setCallingConv(CC); 6484 II->setAttributes(PAL); 6485 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6486 Inst = II; 6487 return false; 6488 } 6489 6490 /// parseResume 6491 /// ::= 'resume' TypeAndValue 6492 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 6493 Value *Exn; LocTy ExnLoc; 6494 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 6495 return true; 6496 6497 ResumeInst *RI = ResumeInst::Create(Exn); 6498 Inst = RI; 6499 return false; 6500 } 6501 6502 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 6503 PerFunctionState &PFS) { 6504 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6505 return true; 6506 6507 while (Lex.getKind() != lltok::rsquare) { 6508 // If this isn't the first argument, we need a comma. 6509 if (!Args.empty() && 6510 parseToken(lltok::comma, "expected ',' in argument list")) 6511 return true; 6512 6513 // parse the argument. 6514 LocTy ArgLoc; 6515 Type *ArgTy = nullptr; 6516 if (parseType(ArgTy, ArgLoc)) 6517 return true; 6518 6519 Value *V; 6520 if (ArgTy->isMetadataTy()) { 6521 if (parseMetadataAsValue(V, PFS)) 6522 return true; 6523 } else { 6524 if (parseValue(ArgTy, V, PFS)) 6525 return true; 6526 } 6527 Args.push_back(V); 6528 } 6529 6530 Lex.Lex(); // Lex the ']'. 6531 return false; 6532 } 6533 6534 /// parseCleanupRet 6535 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6536 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6537 Value *CleanupPad = nullptr; 6538 6539 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6540 return true; 6541 6542 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6543 return true; 6544 6545 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6546 return true; 6547 6548 BasicBlock *UnwindBB = nullptr; 6549 if (Lex.getKind() == lltok::kw_to) { 6550 Lex.Lex(); 6551 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6552 return true; 6553 } else { 6554 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 6555 return true; 6556 } 6557 } 6558 6559 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6560 return false; 6561 } 6562 6563 /// parseCatchRet 6564 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6565 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6566 Value *CatchPad = nullptr; 6567 6568 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 6569 return true; 6570 6571 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6572 return true; 6573 6574 BasicBlock *BB; 6575 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 6576 parseTypeAndBasicBlock(BB, PFS)) 6577 return true; 6578 6579 Inst = CatchReturnInst::Create(CatchPad, BB); 6580 return false; 6581 } 6582 6583 /// parseCatchSwitch 6584 /// ::= 'catchswitch' within Parent 6585 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6586 Value *ParentPad; 6587 6588 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6589 return true; 6590 6591 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6592 Lex.getKind() != lltok::LocalVarID) 6593 return tokError("expected scope value for catchswitch"); 6594 6595 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6596 return true; 6597 6598 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6599 return true; 6600 6601 SmallVector<BasicBlock *, 32> Table; 6602 do { 6603 BasicBlock *DestBB; 6604 if (parseTypeAndBasicBlock(DestBB, PFS)) 6605 return true; 6606 Table.push_back(DestBB); 6607 } while (EatIfPresent(lltok::comma)); 6608 6609 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6610 return true; 6611 6612 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 6613 return true; 6614 6615 BasicBlock *UnwindBB = nullptr; 6616 if (EatIfPresent(lltok::kw_to)) { 6617 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6618 return true; 6619 } else { 6620 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 6621 return true; 6622 } 6623 6624 auto *CatchSwitch = 6625 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6626 for (BasicBlock *DestBB : Table) 6627 CatchSwitch->addHandler(DestBB); 6628 Inst = CatchSwitch; 6629 return false; 6630 } 6631 6632 /// parseCatchPad 6633 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6634 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6635 Value *CatchSwitch = nullptr; 6636 6637 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 6638 return true; 6639 6640 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6641 return tokError("expected scope value for catchpad"); 6642 6643 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6644 return true; 6645 6646 SmallVector<Value *, 8> Args; 6647 if (parseExceptionArgs(Args, PFS)) 6648 return true; 6649 6650 Inst = CatchPadInst::Create(CatchSwitch, Args); 6651 return false; 6652 } 6653 6654 /// parseCleanupPad 6655 /// ::= 'cleanuppad' within Parent ParamList 6656 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6657 Value *ParentPad = nullptr; 6658 6659 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6660 return true; 6661 6662 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6663 Lex.getKind() != lltok::LocalVarID) 6664 return tokError("expected scope value for cleanuppad"); 6665 6666 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6667 return true; 6668 6669 SmallVector<Value *, 8> Args; 6670 if (parseExceptionArgs(Args, PFS)) 6671 return true; 6672 6673 Inst = CleanupPadInst::Create(ParentPad, Args); 6674 return false; 6675 } 6676 6677 //===----------------------------------------------------------------------===// 6678 // Unary Operators. 6679 //===----------------------------------------------------------------------===// 6680 6681 /// parseUnaryOp 6682 /// ::= UnaryOp TypeAndValue ',' Value 6683 /// 6684 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6685 /// operand is allowed. 6686 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6687 unsigned Opc, bool IsFP) { 6688 LocTy Loc; Value *LHS; 6689 if (parseTypeAndValue(LHS, Loc, PFS)) 6690 return true; 6691 6692 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6693 : LHS->getType()->isIntOrIntVectorTy(); 6694 6695 if (!Valid) 6696 return error(Loc, "invalid operand type for instruction"); 6697 6698 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6699 return false; 6700 } 6701 6702 /// parseCallBr 6703 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6704 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6705 /// '[' LabelList ']' 6706 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6707 LocTy CallLoc = Lex.getLoc(); 6708 AttrBuilder RetAttrs, FnAttrs; 6709 std::vector<unsigned> FwdRefAttrGrps; 6710 LocTy NoBuiltinLoc; 6711 unsigned CC; 6712 Type *RetType = nullptr; 6713 LocTy RetTypeLoc; 6714 ValID CalleeID; 6715 SmallVector<ParamInfo, 16> ArgList; 6716 SmallVector<OperandBundleDef, 2> BundleList; 6717 6718 BasicBlock *DefaultDest; 6719 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6720 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6721 parseValID(CalleeID) || parseParameterList(ArgList, PFS) || 6722 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6723 NoBuiltinLoc) || 6724 parseOptionalOperandBundles(BundleList, PFS) || 6725 parseToken(lltok::kw_to, "expected 'to' in callbr") || 6726 parseTypeAndBasicBlock(DefaultDest, PFS) || 6727 parseToken(lltok::lsquare, "expected '[' in callbr")) 6728 return true; 6729 6730 // parse the destination list. 6731 SmallVector<BasicBlock *, 16> IndirectDests; 6732 6733 if (Lex.getKind() != lltok::rsquare) { 6734 BasicBlock *DestBB; 6735 if (parseTypeAndBasicBlock(DestBB, PFS)) 6736 return true; 6737 IndirectDests.push_back(DestBB); 6738 6739 while (EatIfPresent(lltok::comma)) { 6740 if (parseTypeAndBasicBlock(DestBB, PFS)) 6741 return true; 6742 IndirectDests.push_back(DestBB); 6743 } 6744 } 6745 6746 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6747 return true; 6748 6749 // If RetType is a non-function pointer type, then this is the short syntax 6750 // for the call, which means that RetType is just the return type. Infer the 6751 // rest of the function argument types from the arguments that are present. 6752 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6753 if (!Ty) { 6754 // Pull out the types of all of the arguments... 6755 std::vector<Type *> ParamTypes; 6756 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6757 ParamTypes.push_back(ArgList[i].V->getType()); 6758 6759 if (!FunctionType::isValidReturnType(RetType)) 6760 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6761 6762 Ty = FunctionType::get(RetType, ParamTypes, false); 6763 } 6764 6765 CalleeID.FTy = Ty; 6766 6767 // Look up the callee. 6768 Value *Callee; 6769 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS, 6770 /*IsCall=*/true)) 6771 return true; 6772 6773 // Set up the Attribute for the function. 6774 SmallVector<Value *, 8> Args; 6775 SmallVector<AttributeSet, 8> ArgAttrs; 6776 6777 // Loop through FunctionType's arguments and ensure they are specified 6778 // correctly. Also, gather any parameter attributes. 6779 FunctionType::param_iterator I = Ty->param_begin(); 6780 FunctionType::param_iterator E = Ty->param_end(); 6781 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6782 Type *ExpectedTy = nullptr; 6783 if (I != E) { 6784 ExpectedTy = *I++; 6785 } else if (!Ty->isVarArg()) { 6786 return error(ArgList[i].Loc, "too many arguments specified"); 6787 } 6788 6789 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6790 return error(ArgList[i].Loc, "argument is not of expected type '" + 6791 getTypeString(ExpectedTy) + "'"); 6792 Args.push_back(ArgList[i].V); 6793 ArgAttrs.push_back(ArgList[i].Attrs); 6794 } 6795 6796 if (I != E) 6797 return error(CallLoc, "not enough parameters specified for call"); 6798 6799 if (FnAttrs.hasAlignmentAttr()) 6800 return error(CallLoc, "callbr instructions may not have an alignment"); 6801 6802 // Finish off the Attribute and check them 6803 AttributeList PAL = 6804 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6805 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6806 6807 CallBrInst *CBI = 6808 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6809 BundleList); 6810 CBI->setCallingConv(CC); 6811 CBI->setAttributes(PAL); 6812 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6813 Inst = CBI; 6814 return false; 6815 } 6816 6817 //===----------------------------------------------------------------------===// 6818 // Binary Operators. 6819 //===----------------------------------------------------------------------===// 6820 6821 /// parseArithmetic 6822 /// ::= ArithmeticOps TypeAndValue ',' Value 6823 /// 6824 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6825 /// operand is allowed. 6826 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6827 unsigned Opc, bool IsFP) { 6828 LocTy Loc; Value *LHS, *RHS; 6829 if (parseTypeAndValue(LHS, Loc, PFS) || 6830 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 6831 parseValue(LHS->getType(), RHS, PFS)) 6832 return true; 6833 6834 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6835 : LHS->getType()->isIntOrIntVectorTy(); 6836 6837 if (!Valid) 6838 return error(Loc, "invalid operand type for instruction"); 6839 6840 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6841 return false; 6842 } 6843 6844 /// parseLogical 6845 /// ::= ArithmeticOps TypeAndValue ',' Value { 6846 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 6847 unsigned Opc) { 6848 LocTy Loc; Value *LHS, *RHS; 6849 if (parseTypeAndValue(LHS, Loc, PFS) || 6850 parseToken(lltok::comma, "expected ',' in logical operation") || 6851 parseValue(LHS->getType(), RHS, PFS)) 6852 return true; 6853 6854 if (!LHS->getType()->isIntOrIntVectorTy()) 6855 return error(Loc, 6856 "instruction requires integer or integer vector operands"); 6857 6858 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6859 return false; 6860 } 6861 6862 /// parseCompare 6863 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6864 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6865 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 6866 unsigned Opc) { 6867 // parse the integer/fp comparison predicate. 6868 LocTy Loc; 6869 unsigned Pred; 6870 Value *LHS, *RHS; 6871 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 6872 parseToken(lltok::comma, "expected ',' after compare value") || 6873 parseValue(LHS->getType(), RHS, PFS)) 6874 return true; 6875 6876 if (Opc == Instruction::FCmp) { 6877 if (!LHS->getType()->isFPOrFPVectorTy()) 6878 return error(Loc, "fcmp requires floating point operands"); 6879 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6880 } else { 6881 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6882 if (!LHS->getType()->isIntOrIntVectorTy() && 6883 !LHS->getType()->isPtrOrPtrVectorTy()) 6884 return error(Loc, "icmp requires integer operands"); 6885 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6886 } 6887 return false; 6888 } 6889 6890 //===----------------------------------------------------------------------===// 6891 // Other Instructions. 6892 //===----------------------------------------------------------------------===// 6893 6894 /// parseCast 6895 /// ::= CastOpc TypeAndValue 'to' Type 6896 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 6897 unsigned Opc) { 6898 LocTy Loc; 6899 Value *Op; 6900 Type *DestTy = nullptr; 6901 if (parseTypeAndValue(Op, Loc, PFS) || 6902 parseToken(lltok::kw_to, "expected 'to' after cast value") || 6903 parseType(DestTy)) 6904 return true; 6905 6906 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6907 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6908 return error(Loc, "invalid cast opcode for cast from '" + 6909 getTypeString(Op->getType()) + "' to '" + 6910 getTypeString(DestTy) + "'"); 6911 } 6912 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6913 return false; 6914 } 6915 6916 /// parseSelect 6917 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6918 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6919 LocTy Loc; 6920 Value *Op0, *Op1, *Op2; 6921 if (parseTypeAndValue(Op0, Loc, PFS) || 6922 parseToken(lltok::comma, "expected ',' after select condition") || 6923 parseTypeAndValue(Op1, PFS) || 6924 parseToken(lltok::comma, "expected ',' after select value") || 6925 parseTypeAndValue(Op2, PFS)) 6926 return true; 6927 6928 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6929 return error(Loc, Reason); 6930 6931 Inst = SelectInst::Create(Op0, Op1, Op2); 6932 return false; 6933 } 6934 6935 /// parseVAArg 6936 /// ::= 'va_arg' TypeAndValue ',' Type 6937 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 6938 Value *Op; 6939 Type *EltTy = nullptr; 6940 LocTy TypeLoc; 6941 if (parseTypeAndValue(Op, PFS) || 6942 parseToken(lltok::comma, "expected ',' after vaarg operand") || 6943 parseType(EltTy, TypeLoc)) 6944 return true; 6945 6946 if (!EltTy->isFirstClassType()) 6947 return error(TypeLoc, "va_arg requires operand with first class type"); 6948 6949 Inst = new VAArgInst(Op, EltTy); 6950 return false; 6951 } 6952 6953 /// parseExtractElement 6954 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6955 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6956 LocTy Loc; 6957 Value *Op0, *Op1; 6958 if (parseTypeAndValue(Op0, Loc, PFS) || 6959 parseToken(lltok::comma, "expected ',' after extract value") || 6960 parseTypeAndValue(Op1, PFS)) 6961 return true; 6962 6963 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6964 return error(Loc, "invalid extractelement operands"); 6965 6966 Inst = ExtractElementInst::Create(Op0, Op1); 6967 return false; 6968 } 6969 6970 /// parseInsertElement 6971 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6972 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6973 LocTy Loc; 6974 Value *Op0, *Op1, *Op2; 6975 if (parseTypeAndValue(Op0, Loc, PFS) || 6976 parseToken(lltok::comma, "expected ',' after insertelement value") || 6977 parseTypeAndValue(Op1, PFS) || 6978 parseToken(lltok::comma, "expected ',' after insertelement value") || 6979 parseTypeAndValue(Op2, PFS)) 6980 return true; 6981 6982 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6983 return error(Loc, "invalid insertelement operands"); 6984 6985 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6986 return false; 6987 } 6988 6989 /// parseShuffleVector 6990 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6991 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6992 LocTy Loc; 6993 Value *Op0, *Op1, *Op2; 6994 if (parseTypeAndValue(Op0, Loc, PFS) || 6995 parseToken(lltok::comma, "expected ',' after shuffle mask") || 6996 parseTypeAndValue(Op1, PFS) || 6997 parseToken(lltok::comma, "expected ',' after shuffle value") || 6998 parseTypeAndValue(Op2, PFS)) 6999 return true; 7000 7001 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 7002 return error(Loc, "invalid shufflevector operands"); 7003 7004 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 7005 return false; 7006 } 7007 7008 /// parsePHI 7009 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 7010 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 7011 Type *Ty = nullptr; LocTy TypeLoc; 7012 Value *Op0, *Op1; 7013 7014 if (parseType(Ty, TypeLoc) || 7015 parseToken(lltok::lsquare, "expected '[' in phi value list") || 7016 parseValue(Ty, Op0, PFS) || 7017 parseToken(lltok::comma, "expected ',' after insertelement value") || 7018 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7019 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7020 return true; 7021 7022 bool AteExtraComma = false; 7023 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 7024 7025 while (true) { 7026 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 7027 7028 if (!EatIfPresent(lltok::comma)) 7029 break; 7030 7031 if (Lex.getKind() == lltok::MetadataVar) { 7032 AteExtraComma = true; 7033 break; 7034 } 7035 7036 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 7037 parseValue(Ty, Op0, PFS) || 7038 parseToken(lltok::comma, "expected ',' after insertelement value") || 7039 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7040 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7041 return true; 7042 } 7043 7044 if (!Ty->isFirstClassType()) 7045 return error(TypeLoc, "phi node must have first class type"); 7046 7047 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 7048 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 7049 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 7050 Inst = PN; 7051 return AteExtraComma ? InstExtraComma : InstNormal; 7052 } 7053 7054 /// parseLandingPad 7055 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 7056 /// Clause 7057 /// ::= 'catch' TypeAndValue 7058 /// ::= 'filter' 7059 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 7060 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 7061 Type *Ty = nullptr; LocTy TyLoc; 7062 7063 if (parseType(Ty, TyLoc)) 7064 return true; 7065 7066 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 7067 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 7068 7069 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 7070 LandingPadInst::ClauseType CT; 7071 if (EatIfPresent(lltok::kw_catch)) 7072 CT = LandingPadInst::Catch; 7073 else if (EatIfPresent(lltok::kw_filter)) 7074 CT = LandingPadInst::Filter; 7075 else 7076 return tokError("expected 'catch' or 'filter' clause type"); 7077 7078 Value *V; 7079 LocTy VLoc; 7080 if (parseTypeAndValue(V, VLoc, PFS)) 7081 return true; 7082 7083 // A 'catch' type expects a non-array constant. A filter clause expects an 7084 // array constant. 7085 if (CT == LandingPadInst::Catch) { 7086 if (isa<ArrayType>(V->getType())) 7087 error(VLoc, "'catch' clause has an invalid type"); 7088 } else { 7089 if (!isa<ArrayType>(V->getType())) 7090 error(VLoc, "'filter' clause has an invalid type"); 7091 } 7092 7093 Constant *CV = dyn_cast<Constant>(V); 7094 if (!CV) 7095 return error(VLoc, "clause argument must be a constant"); 7096 LP->addClause(CV); 7097 } 7098 7099 Inst = LP.release(); 7100 return false; 7101 } 7102 7103 /// parseFreeze 7104 /// ::= 'freeze' Type Value 7105 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 7106 LocTy Loc; 7107 Value *Op; 7108 if (parseTypeAndValue(Op, Loc, PFS)) 7109 return true; 7110 7111 Inst = new FreezeInst(Op); 7112 return false; 7113 } 7114 7115 /// parseCall 7116 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 7117 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7118 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 7119 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7120 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 7121 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7122 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 7123 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7124 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 7125 CallInst::TailCallKind TCK) { 7126 AttrBuilder RetAttrs, FnAttrs; 7127 std::vector<unsigned> FwdRefAttrGrps; 7128 LocTy BuiltinLoc; 7129 unsigned CallAddrSpace; 7130 unsigned CC; 7131 Type *RetType = nullptr; 7132 LocTy RetTypeLoc; 7133 ValID CalleeID; 7134 SmallVector<ParamInfo, 16> ArgList; 7135 SmallVector<OperandBundleDef, 2> BundleList; 7136 LocTy CallLoc = Lex.getLoc(); 7137 7138 if (TCK != CallInst::TCK_None && 7139 parseToken(lltok::kw_call, 7140 "expected 'tail call', 'musttail call', or 'notail call'")) 7141 return true; 7142 7143 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7144 7145 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7146 parseOptionalProgramAddrSpace(CallAddrSpace) || 7147 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7148 parseValID(CalleeID) || 7149 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 7150 PFS.getFunction().isVarArg()) || 7151 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 7152 parseOptionalOperandBundles(BundleList, PFS)) 7153 return true; 7154 7155 // If RetType is a non-function pointer type, then this is the short syntax 7156 // for the call, which means that RetType is just the return type. Infer the 7157 // rest of the function argument types from the arguments that are present. 7158 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 7159 if (!Ty) { 7160 // Pull out the types of all of the arguments... 7161 std::vector<Type*> ParamTypes; 7162 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 7163 ParamTypes.push_back(ArgList[i].V->getType()); 7164 7165 if (!FunctionType::isValidReturnType(RetType)) 7166 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7167 7168 Ty = FunctionType::get(RetType, ParamTypes, false); 7169 } 7170 7171 CalleeID.FTy = Ty; 7172 7173 // Look up the callee. 7174 Value *Callee; 7175 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 7176 &PFS, /*IsCall=*/true)) 7177 return true; 7178 7179 // Set up the Attribute for the function. 7180 SmallVector<AttributeSet, 8> Attrs; 7181 7182 SmallVector<Value*, 8> Args; 7183 7184 // Loop through FunctionType's arguments and ensure they are specified 7185 // correctly. Also, gather any parameter attributes. 7186 FunctionType::param_iterator I = Ty->param_begin(); 7187 FunctionType::param_iterator E = Ty->param_end(); 7188 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 7189 Type *ExpectedTy = nullptr; 7190 if (I != E) { 7191 ExpectedTy = *I++; 7192 } else if (!Ty->isVarArg()) { 7193 return error(ArgList[i].Loc, "too many arguments specified"); 7194 } 7195 7196 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 7197 return error(ArgList[i].Loc, "argument is not of expected type '" + 7198 getTypeString(ExpectedTy) + "'"); 7199 Args.push_back(ArgList[i].V); 7200 Attrs.push_back(ArgList[i].Attrs); 7201 } 7202 7203 if (I != E) 7204 return error(CallLoc, "not enough parameters specified for call"); 7205 7206 if (FnAttrs.hasAlignmentAttr()) 7207 return error(CallLoc, "call instructions may not have an alignment"); 7208 7209 // Finish off the Attribute and check them 7210 AttributeList PAL = 7211 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7212 AttributeSet::get(Context, RetAttrs), Attrs); 7213 7214 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 7215 CI->setTailCallKind(TCK); 7216 CI->setCallingConv(CC); 7217 if (FMF.any()) { 7218 if (!isa<FPMathOperator>(CI)) { 7219 CI->deleteValue(); 7220 return error(CallLoc, "fast-math-flags specified for call without " 7221 "floating-point scalar or vector return type"); 7222 } 7223 CI->setFastMathFlags(FMF); 7224 } 7225 CI->setAttributes(PAL); 7226 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 7227 Inst = CI; 7228 return false; 7229 } 7230 7231 //===----------------------------------------------------------------------===// 7232 // Memory Instructions. 7233 //===----------------------------------------------------------------------===// 7234 7235 /// parseAlloc 7236 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 7237 /// (',' 'align' i32)? (',', 'addrspace(n))? 7238 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 7239 Value *Size = nullptr; 7240 LocTy SizeLoc, TyLoc, ASLoc; 7241 MaybeAlign Alignment; 7242 unsigned AddrSpace = 0; 7243 Type *Ty = nullptr; 7244 7245 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 7246 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 7247 7248 if (parseType(Ty, TyLoc)) 7249 return true; 7250 7251 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7252 return error(TyLoc, "invalid type for alloca"); 7253 7254 bool AteExtraComma = false; 7255 if (EatIfPresent(lltok::comma)) { 7256 if (Lex.getKind() == lltok::kw_align) { 7257 if (parseOptionalAlignment(Alignment)) 7258 return true; 7259 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7260 return true; 7261 } else if (Lex.getKind() == lltok::kw_addrspace) { 7262 ASLoc = Lex.getLoc(); 7263 if (parseOptionalAddrSpace(AddrSpace)) 7264 return true; 7265 } else if (Lex.getKind() == lltok::MetadataVar) { 7266 AteExtraComma = true; 7267 } else { 7268 if (parseTypeAndValue(Size, SizeLoc, PFS)) 7269 return true; 7270 if (EatIfPresent(lltok::comma)) { 7271 if (Lex.getKind() == lltok::kw_align) { 7272 if (parseOptionalAlignment(Alignment)) 7273 return true; 7274 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7275 return true; 7276 } else if (Lex.getKind() == lltok::kw_addrspace) { 7277 ASLoc = Lex.getLoc(); 7278 if (parseOptionalAddrSpace(AddrSpace)) 7279 return true; 7280 } else if (Lex.getKind() == lltok::MetadataVar) { 7281 AteExtraComma = true; 7282 } 7283 } 7284 } 7285 } 7286 7287 if (Size && !Size->getType()->isIntegerTy()) 7288 return error(SizeLoc, "element count must have integer type"); 7289 7290 SmallPtrSet<Type *, 4> Visited; 7291 if (!Alignment && !Ty->isSized(&Visited)) 7292 return error(TyLoc, "Cannot allocate unsized type"); 7293 if (!Alignment) 7294 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7295 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7296 AI->setUsedWithInAlloca(IsInAlloca); 7297 AI->setSwiftError(IsSwiftError); 7298 Inst = AI; 7299 return AteExtraComma ? InstExtraComma : InstNormal; 7300 } 7301 7302 /// parseLoad 7303 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7304 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7305 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7306 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7307 Value *Val; LocTy Loc; 7308 MaybeAlign Alignment; 7309 bool AteExtraComma = false; 7310 bool isAtomic = false; 7311 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7312 SyncScope::ID SSID = SyncScope::System; 7313 7314 if (Lex.getKind() == lltok::kw_atomic) { 7315 isAtomic = true; 7316 Lex.Lex(); 7317 } 7318 7319 bool isVolatile = false; 7320 if (Lex.getKind() == lltok::kw_volatile) { 7321 isVolatile = true; 7322 Lex.Lex(); 7323 } 7324 7325 Type *Ty; 7326 LocTy ExplicitTypeLoc = Lex.getLoc(); 7327 if (parseType(Ty) || 7328 parseToken(lltok::comma, "expected comma after load's type") || 7329 parseTypeAndValue(Val, Loc, PFS) || 7330 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7331 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7332 return true; 7333 7334 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7335 return error(Loc, "load operand must be a pointer to a first class type"); 7336 if (isAtomic && !Alignment) 7337 return error(Loc, "atomic load must have explicit non-zero alignment"); 7338 if (Ordering == AtomicOrdering::Release || 7339 Ordering == AtomicOrdering::AcquireRelease) 7340 return error(Loc, "atomic load cannot use Release ordering"); 7341 7342 if (Ty != cast<PointerType>(Val->getType())->getElementType()) 7343 return error(ExplicitTypeLoc, 7344 "explicit pointee type doesn't match operand's pointee type"); 7345 SmallPtrSet<Type *, 4> Visited; 7346 if (!Alignment && !Ty->isSized(&Visited)) 7347 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7348 if (!Alignment) 7349 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7350 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7351 return AteExtraComma ? InstExtraComma : InstNormal; 7352 } 7353 7354 /// parseStore 7355 7356 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7357 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7358 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7359 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 7360 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7361 MaybeAlign Alignment; 7362 bool AteExtraComma = false; 7363 bool isAtomic = false; 7364 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7365 SyncScope::ID SSID = SyncScope::System; 7366 7367 if (Lex.getKind() == lltok::kw_atomic) { 7368 isAtomic = true; 7369 Lex.Lex(); 7370 } 7371 7372 bool isVolatile = false; 7373 if (Lex.getKind() == lltok::kw_volatile) { 7374 isVolatile = true; 7375 Lex.Lex(); 7376 } 7377 7378 if (parseTypeAndValue(Val, Loc, PFS) || 7379 parseToken(lltok::comma, "expected ',' after store operand") || 7380 parseTypeAndValue(Ptr, PtrLoc, PFS) || 7381 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7382 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7383 return true; 7384 7385 if (!Ptr->getType()->isPointerTy()) 7386 return error(PtrLoc, "store operand must be a pointer"); 7387 if (!Val->getType()->isFirstClassType()) 7388 return error(Loc, "store operand must be a first class value"); 7389 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7390 return error(Loc, "stored value and pointer type do not match"); 7391 if (isAtomic && !Alignment) 7392 return error(Loc, "atomic store must have explicit non-zero alignment"); 7393 if (Ordering == AtomicOrdering::Acquire || 7394 Ordering == AtomicOrdering::AcquireRelease) 7395 return error(Loc, "atomic store cannot use Acquire ordering"); 7396 SmallPtrSet<Type *, 4> Visited; 7397 if (!Alignment && !Val->getType()->isSized(&Visited)) 7398 return error(Loc, "storing unsized types is not allowed"); 7399 if (!Alignment) 7400 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7401 7402 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7403 return AteExtraComma ? InstExtraComma : InstNormal; 7404 } 7405 7406 /// parseCmpXchg 7407 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7408 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering 7409 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7410 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7411 bool AteExtraComma = false; 7412 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7413 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7414 SyncScope::ID SSID = SyncScope::System; 7415 bool isVolatile = false; 7416 bool isWeak = false; 7417 7418 if (EatIfPresent(lltok::kw_weak)) 7419 isWeak = true; 7420 7421 if (EatIfPresent(lltok::kw_volatile)) 7422 isVolatile = true; 7423 7424 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7425 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 7426 parseTypeAndValue(Cmp, CmpLoc, PFS) || 7427 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7428 parseTypeAndValue(New, NewLoc, PFS) || 7429 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7430 parseOrdering(FailureOrdering)) 7431 return true; 7432 7433 if (SuccessOrdering == AtomicOrdering::Unordered || 7434 FailureOrdering == AtomicOrdering::Unordered) 7435 return tokError("cmpxchg cannot be unordered"); 7436 if (isStrongerThan(FailureOrdering, SuccessOrdering)) 7437 return tokError("cmpxchg failure argument shall be no stronger than the " 7438 "success argument"); 7439 if (FailureOrdering == AtomicOrdering::Release || 7440 FailureOrdering == AtomicOrdering::AcquireRelease) 7441 return tokError( 7442 "cmpxchg failure ordering cannot include release semantics"); 7443 if (!Ptr->getType()->isPointerTy()) 7444 return error(PtrLoc, "cmpxchg operand must be a pointer"); 7445 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 7446 return error(CmpLoc, "compare value and pointer type do not match"); 7447 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 7448 return error(NewLoc, "new value and pointer type do not match"); 7449 if (!New->getType()->isFirstClassType()) 7450 return error(NewLoc, "cmpxchg operand must be a first class value"); 7451 7452 Align Alignment( 7453 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7454 Cmp->getType())); 7455 7456 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7457 Ptr, Cmp, New, Alignment, SuccessOrdering, FailureOrdering, SSID); 7458 CXI->setVolatile(isVolatile); 7459 CXI->setWeak(isWeak); 7460 Inst = CXI; 7461 return AteExtraComma ? InstExtraComma : InstNormal; 7462 } 7463 7464 /// parseAtomicRMW 7465 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7466 /// 'singlethread'? AtomicOrdering 7467 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7468 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7469 bool AteExtraComma = false; 7470 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7471 SyncScope::ID SSID = SyncScope::System; 7472 bool isVolatile = false; 7473 bool IsFP = false; 7474 AtomicRMWInst::BinOp Operation; 7475 7476 if (EatIfPresent(lltok::kw_volatile)) 7477 isVolatile = true; 7478 7479 switch (Lex.getKind()) { 7480 default: 7481 return tokError("expected binary operation in atomicrmw"); 7482 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7483 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7484 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7485 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7486 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7487 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7488 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7489 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7490 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7491 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7492 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7493 case lltok::kw_fadd: 7494 Operation = AtomicRMWInst::FAdd; 7495 IsFP = true; 7496 break; 7497 case lltok::kw_fsub: 7498 Operation = AtomicRMWInst::FSub; 7499 IsFP = true; 7500 break; 7501 } 7502 Lex.Lex(); // Eat the operation. 7503 7504 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7505 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 7506 parseTypeAndValue(Val, ValLoc, PFS) || 7507 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7508 return true; 7509 7510 if (Ordering == AtomicOrdering::Unordered) 7511 return tokError("atomicrmw cannot be unordered"); 7512 if (!Ptr->getType()->isPointerTy()) 7513 return error(PtrLoc, "atomicrmw operand must be a pointer"); 7514 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7515 return error(ValLoc, "atomicrmw value and pointer type do not match"); 7516 7517 if (Operation == AtomicRMWInst::Xchg) { 7518 if (!Val->getType()->isIntegerTy() && 7519 !Val->getType()->isFloatingPointTy()) { 7520 return error(ValLoc, 7521 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 7522 " operand must be an integer or floating point type"); 7523 } 7524 } else if (IsFP) { 7525 if (!Val->getType()->isFloatingPointTy()) { 7526 return error(ValLoc, "atomicrmw " + 7527 AtomicRMWInst::getOperationName(Operation) + 7528 " operand must be a floating point type"); 7529 } 7530 } else { 7531 if (!Val->getType()->isIntegerTy()) { 7532 return error(ValLoc, "atomicrmw " + 7533 AtomicRMWInst::getOperationName(Operation) + 7534 " operand must be an integer"); 7535 } 7536 } 7537 7538 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7539 if (Size < 8 || (Size & (Size - 1))) 7540 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7541 " integer"); 7542 Align Alignment( 7543 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7544 Val->getType())); 7545 AtomicRMWInst *RMWI = 7546 new AtomicRMWInst(Operation, Ptr, Val, Alignment, Ordering, SSID); 7547 RMWI->setVolatile(isVolatile); 7548 Inst = RMWI; 7549 return AteExtraComma ? InstExtraComma : InstNormal; 7550 } 7551 7552 /// parseFence 7553 /// ::= 'fence' 'singlethread'? AtomicOrdering 7554 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 7555 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7556 SyncScope::ID SSID = SyncScope::System; 7557 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7558 return true; 7559 7560 if (Ordering == AtomicOrdering::Unordered) 7561 return tokError("fence cannot be unordered"); 7562 if (Ordering == AtomicOrdering::Monotonic) 7563 return tokError("fence cannot be monotonic"); 7564 7565 Inst = new FenceInst(Context, Ordering, SSID); 7566 return InstNormal; 7567 } 7568 7569 /// parseGetElementPtr 7570 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7571 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7572 Value *Ptr = nullptr; 7573 Value *Val = nullptr; 7574 LocTy Loc, EltLoc; 7575 7576 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7577 7578 Type *Ty = nullptr; 7579 LocTy ExplicitTypeLoc = Lex.getLoc(); 7580 if (parseType(Ty) || 7581 parseToken(lltok::comma, "expected comma after getelementptr's type") || 7582 parseTypeAndValue(Ptr, Loc, PFS)) 7583 return true; 7584 7585 Type *BaseType = Ptr->getType(); 7586 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7587 if (!BasePointerType) 7588 return error(Loc, "base of getelementptr must be a pointer"); 7589 7590 if (Ty != BasePointerType->getElementType()) 7591 return error(ExplicitTypeLoc, 7592 "explicit pointee type doesn't match operand's pointee type"); 7593 7594 SmallVector<Value*, 16> Indices; 7595 bool AteExtraComma = false; 7596 // GEP returns a vector of pointers if at least one of parameters is a vector. 7597 // All vector parameters should have the same vector width. 7598 ElementCount GEPWidth = BaseType->isVectorTy() 7599 ? cast<VectorType>(BaseType)->getElementCount() 7600 : ElementCount::getFixed(0); 7601 7602 while (EatIfPresent(lltok::comma)) { 7603 if (Lex.getKind() == lltok::MetadataVar) { 7604 AteExtraComma = true; 7605 break; 7606 } 7607 if (parseTypeAndValue(Val, EltLoc, PFS)) 7608 return true; 7609 if (!Val->getType()->isIntOrIntVectorTy()) 7610 return error(EltLoc, "getelementptr index must be an integer"); 7611 7612 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7613 ElementCount ValNumEl = ValVTy->getElementCount(); 7614 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 7615 return error( 7616 EltLoc, 7617 "getelementptr vector index has a wrong number of elements"); 7618 GEPWidth = ValNumEl; 7619 } 7620 Indices.push_back(Val); 7621 } 7622 7623 SmallPtrSet<Type*, 4> Visited; 7624 if (!Indices.empty() && !Ty->isSized(&Visited)) 7625 return error(Loc, "base element of getelementptr must be sized"); 7626 7627 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7628 return error(Loc, "invalid getelementptr indices"); 7629 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7630 if (InBounds) 7631 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7632 return AteExtraComma ? InstExtraComma : InstNormal; 7633 } 7634 7635 /// parseExtractValue 7636 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7637 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7638 Value *Val; LocTy Loc; 7639 SmallVector<unsigned, 4> Indices; 7640 bool AteExtraComma; 7641 if (parseTypeAndValue(Val, Loc, PFS) || 7642 parseIndexList(Indices, AteExtraComma)) 7643 return true; 7644 7645 if (!Val->getType()->isAggregateType()) 7646 return error(Loc, "extractvalue operand must be aggregate type"); 7647 7648 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7649 return error(Loc, "invalid indices for extractvalue"); 7650 Inst = ExtractValueInst::Create(Val, Indices); 7651 return AteExtraComma ? InstExtraComma : InstNormal; 7652 } 7653 7654 /// parseInsertValue 7655 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7656 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7657 Value *Val0, *Val1; LocTy Loc0, Loc1; 7658 SmallVector<unsigned, 4> Indices; 7659 bool AteExtraComma; 7660 if (parseTypeAndValue(Val0, Loc0, PFS) || 7661 parseToken(lltok::comma, "expected comma after insertvalue operand") || 7662 parseTypeAndValue(Val1, Loc1, PFS) || 7663 parseIndexList(Indices, AteExtraComma)) 7664 return true; 7665 7666 if (!Val0->getType()->isAggregateType()) 7667 return error(Loc0, "insertvalue operand must be aggregate type"); 7668 7669 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7670 if (!IndexedType) 7671 return error(Loc0, "invalid indices for insertvalue"); 7672 if (IndexedType != Val1->getType()) 7673 return error(Loc1, "insertvalue operand and field disagree in type: '" + 7674 getTypeString(Val1->getType()) + "' instead of '" + 7675 getTypeString(IndexedType) + "'"); 7676 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7677 return AteExtraComma ? InstExtraComma : InstNormal; 7678 } 7679 7680 //===----------------------------------------------------------------------===// 7681 // Embedded metadata. 7682 //===----------------------------------------------------------------------===// 7683 7684 /// parseMDNodeVector 7685 /// ::= { Element (',' Element)* } 7686 /// Element 7687 /// ::= 'null' | TypeAndValue 7688 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7689 if (parseToken(lltok::lbrace, "expected '{' here")) 7690 return true; 7691 7692 // Check for an empty list. 7693 if (EatIfPresent(lltok::rbrace)) 7694 return false; 7695 7696 do { 7697 // Null is a special case since it is typeless. 7698 if (EatIfPresent(lltok::kw_null)) { 7699 Elts.push_back(nullptr); 7700 continue; 7701 } 7702 7703 Metadata *MD; 7704 if (parseMetadata(MD, nullptr)) 7705 return true; 7706 Elts.push_back(MD); 7707 } while (EatIfPresent(lltok::comma)); 7708 7709 return parseToken(lltok::rbrace, "expected end of metadata node"); 7710 } 7711 7712 //===----------------------------------------------------------------------===// 7713 // Use-list order directives. 7714 //===----------------------------------------------------------------------===// 7715 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7716 SMLoc Loc) { 7717 if (V->use_empty()) 7718 return error(Loc, "value has no uses"); 7719 7720 unsigned NumUses = 0; 7721 SmallDenseMap<const Use *, unsigned, 16> Order; 7722 for (const Use &U : V->uses()) { 7723 if (++NumUses > Indexes.size()) 7724 break; 7725 Order[&U] = Indexes[NumUses - 1]; 7726 } 7727 if (NumUses < 2) 7728 return error(Loc, "value only has one use"); 7729 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7730 return error(Loc, 7731 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7732 7733 V->sortUseList([&](const Use &L, const Use &R) { 7734 return Order.lookup(&L) < Order.lookup(&R); 7735 }); 7736 return false; 7737 } 7738 7739 /// parseUseListOrderIndexes 7740 /// ::= '{' uint32 (',' uint32)+ '}' 7741 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7742 SMLoc Loc = Lex.getLoc(); 7743 if (parseToken(lltok::lbrace, "expected '{' here")) 7744 return true; 7745 if (Lex.getKind() == lltok::rbrace) 7746 return Lex.Error("expected non-empty list of uselistorder indexes"); 7747 7748 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7749 // indexes should be distinct numbers in the range [0, size-1], and should 7750 // not be in order. 7751 unsigned Offset = 0; 7752 unsigned Max = 0; 7753 bool IsOrdered = true; 7754 assert(Indexes.empty() && "Expected empty order vector"); 7755 do { 7756 unsigned Index; 7757 if (parseUInt32(Index)) 7758 return true; 7759 7760 // Update consistency checks. 7761 Offset += Index - Indexes.size(); 7762 Max = std::max(Max, Index); 7763 IsOrdered &= Index == Indexes.size(); 7764 7765 Indexes.push_back(Index); 7766 } while (EatIfPresent(lltok::comma)); 7767 7768 if (parseToken(lltok::rbrace, "expected '}' here")) 7769 return true; 7770 7771 if (Indexes.size() < 2) 7772 return error(Loc, "expected >= 2 uselistorder indexes"); 7773 if (Offset != 0 || Max >= Indexes.size()) 7774 return error(Loc, 7775 "expected distinct uselistorder indexes in range [0, size)"); 7776 if (IsOrdered) 7777 return error(Loc, "expected uselistorder indexes to change the order"); 7778 7779 return false; 7780 } 7781 7782 /// parseUseListOrder 7783 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7784 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 7785 SMLoc Loc = Lex.getLoc(); 7786 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7787 return true; 7788 7789 Value *V; 7790 SmallVector<unsigned, 16> Indexes; 7791 if (parseTypeAndValue(V, PFS) || 7792 parseToken(lltok::comma, "expected comma in uselistorder directive") || 7793 parseUseListOrderIndexes(Indexes)) 7794 return true; 7795 7796 return sortUseListOrder(V, Indexes, Loc); 7797 } 7798 7799 /// parseUseListOrderBB 7800 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7801 bool LLParser::parseUseListOrderBB() { 7802 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7803 SMLoc Loc = Lex.getLoc(); 7804 Lex.Lex(); 7805 7806 ValID Fn, Label; 7807 SmallVector<unsigned, 16> Indexes; 7808 if (parseValID(Fn) || 7809 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7810 parseValID(Label) || 7811 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7812 parseUseListOrderIndexes(Indexes)) 7813 return true; 7814 7815 // Check the function. 7816 GlobalValue *GV; 7817 if (Fn.Kind == ValID::t_GlobalName) 7818 GV = M->getNamedValue(Fn.StrVal); 7819 else if (Fn.Kind == ValID::t_GlobalID) 7820 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7821 else 7822 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7823 if (!GV) 7824 return error(Fn.Loc, 7825 "invalid function forward reference in uselistorder_bb"); 7826 auto *F = dyn_cast<Function>(GV); 7827 if (!F) 7828 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7829 if (F->isDeclaration()) 7830 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7831 7832 // Check the basic block. 7833 if (Label.Kind == ValID::t_LocalID) 7834 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7835 if (Label.Kind != ValID::t_LocalName) 7836 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 7837 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7838 if (!V) 7839 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 7840 if (!isa<BasicBlock>(V)) 7841 return error(Label.Loc, "expected basic block in uselistorder_bb"); 7842 7843 return sortUseListOrder(V, Indexes, Loc); 7844 } 7845 7846 /// ModuleEntry 7847 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7848 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7849 bool LLParser::parseModuleEntry(unsigned ID) { 7850 assert(Lex.getKind() == lltok::kw_module); 7851 Lex.Lex(); 7852 7853 std::string Path; 7854 if (parseToken(lltok::colon, "expected ':' here") || 7855 parseToken(lltok::lparen, "expected '(' here") || 7856 parseToken(lltok::kw_path, "expected 'path' here") || 7857 parseToken(lltok::colon, "expected ':' here") || 7858 parseStringConstant(Path) || 7859 parseToken(lltok::comma, "expected ',' here") || 7860 parseToken(lltok::kw_hash, "expected 'hash' here") || 7861 parseToken(lltok::colon, "expected ':' here") || 7862 parseToken(lltok::lparen, "expected '(' here")) 7863 return true; 7864 7865 ModuleHash Hash; 7866 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 7867 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 7868 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 7869 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 7870 parseUInt32(Hash[4])) 7871 return true; 7872 7873 if (parseToken(lltok::rparen, "expected ')' here") || 7874 parseToken(lltok::rparen, "expected ')' here")) 7875 return true; 7876 7877 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7878 ModuleIdMap[ID] = ModuleEntry->first(); 7879 7880 return false; 7881 } 7882 7883 /// TypeIdEntry 7884 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7885 bool LLParser::parseTypeIdEntry(unsigned ID) { 7886 assert(Lex.getKind() == lltok::kw_typeid); 7887 Lex.Lex(); 7888 7889 std::string Name; 7890 if (parseToken(lltok::colon, "expected ':' here") || 7891 parseToken(lltok::lparen, "expected '(' here") || 7892 parseToken(lltok::kw_name, "expected 'name' here") || 7893 parseToken(lltok::colon, "expected ':' here") || 7894 parseStringConstant(Name)) 7895 return true; 7896 7897 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7898 if (parseToken(lltok::comma, "expected ',' here") || 7899 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 7900 return true; 7901 7902 // Check if this ID was forward referenced, and if so, update the 7903 // corresponding GUIDs. 7904 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7905 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7906 for (auto TIDRef : FwdRefTIDs->second) { 7907 assert(!*TIDRef.first && 7908 "Forward referenced type id GUID expected to be 0"); 7909 *TIDRef.first = GlobalValue::getGUID(Name); 7910 } 7911 ForwardRefTypeIds.erase(FwdRefTIDs); 7912 } 7913 7914 return false; 7915 } 7916 7917 /// TypeIdSummary 7918 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7919 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 7920 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 7921 parseToken(lltok::colon, "expected ':' here") || 7922 parseToken(lltok::lparen, "expected '(' here") || 7923 parseTypeTestResolution(TIS.TTRes)) 7924 return true; 7925 7926 if (EatIfPresent(lltok::comma)) { 7927 // Expect optional wpdResolutions field 7928 if (parseOptionalWpdResolutions(TIS.WPDRes)) 7929 return true; 7930 } 7931 7932 if (parseToken(lltok::rparen, "expected ')' here")) 7933 return true; 7934 7935 return false; 7936 } 7937 7938 static ValueInfo EmptyVI = 7939 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7940 7941 /// TypeIdCompatibleVtableEntry 7942 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7943 /// TypeIdCompatibleVtableInfo 7944 /// ')' 7945 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 7946 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7947 Lex.Lex(); 7948 7949 std::string Name; 7950 if (parseToken(lltok::colon, "expected ':' here") || 7951 parseToken(lltok::lparen, "expected '(' here") || 7952 parseToken(lltok::kw_name, "expected 'name' here") || 7953 parseToken(lltok::colon, "expected ':' here") || 7954 parseStringConstant(Name)) 7955 return true; 7956 7957 TypeIdCompatibleVtableInfo &TI = 7958 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7959 if (parseToken(lltok::comma, "expected ',' here") || 7960 parseToken(lltok::kw_summary, "expected 'summary' here") || 7961 parseToken(lltok::colon, "expected ':' here") || 7962 parseToken(lltok::lparen, "expected '(' here")) 7963 return true; 7964 7965 IdToIndexMapType IdToIndexMap; 7966 // parse each call edge 7967 do { 7968 uint64_t Offset; 7969 if (parseToken(lltok::lparen, "expected '(' here") || 7970 parseToken(lltok::kw_offset, "expected 'offset' here") || 7971 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7972 parseToken(lltok::comma, "expected ',' here")) 7973 return true; 7974 7975 LocTy Loc = Lex.getLoc(); 7976 unsigned GVId; 7977 ValueInfo VI; 7978 if (parseGVReference(VI, GVId)) 7979 return true; 7980 7981 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7982 // forward reference. We will save the location of the ValueInfo needing an 7983 // update, but can only do so once the std::vector is finalized. 7984 if (VI == EmptyVI) 7985 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7986 TI.push_back({Offset, VI}); 7987 7988 if (parseToken(lltok::rparen, "expected ')' in call")) 7989 return true; 7990 } while (EatIfPresent(lltok::comma)); 7991 7992 // Now that the TI vector is finalized, it is safe to save the locations 7993 // of any forward GV references that need updating later. 7994 for (auto I : IdToIndexMap) { 7995 auto &Infos = ForwardRefValueInfos[I.first]; 7996 for (auto P : I.second) { 7997 assert(TI[P.first].VTableVI == EmptyVI && 7998 "Forward referenced ValueInfo expected to be empty"); 7999 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 8000 } 8001 } 8002 8003 if (parseToken(lltok::rparen, "expected ')' here") || 8004 parseToken(lltok::rparen, "expected ')' here")) 8005 return true; 8006 8007 // Check if this ID was forward referenced, and if so, update the 8008 // corresponding GUIDs. 8009 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8010 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8011 for (auto TIDRef : FwdRefTIDs->second) { 8012 assert(!*TIDRef.first && 8013 "Forward referenced type id GUID expected to be 0"); 8014 *TIDRef.first = GlobalValue::getGUID(Name); 8015 } 8016 ForwardRefTypeIds.erase(FwdRefTIDs); 8017 } 8018 8019 return false; 8020 } 8021 8022 /// TypeTestResolution 8023 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 8024 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 8025 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 8026 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 8027 /// [',' 'inlinesBits' ':' UInt64]? ')' 8028 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 8029 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 8030 parseToken(lltok::colon, "expected ':' here") || 8031 parseToken(lltok::lparen, "expected '(' here") || 8032 parseToken(lltok::kw_kind, "expected 'kind' here") || 8033 parseToken(lltok::colon, "expected ':' here")) 8034 return true; 8035 8036 switch (Lex.getKind()) { 8037 case lltok::kw_unknown: 8038 TTRes.TheKind = TypeTestResolution::Unknown; 8039 break; 8040 case lltok::kw_unsat: 8041 TTRes.TheKind = TypeTestResolution::Unsat; 8042 break; 8043 case lltok::kw_byteArray: 8044 TTRes.TheKind = TypeTestResolution::ByteArray; 8045 break; 8046 case lltok::kw_inline: 8047 TTRes.TheKind = TypeTestResolution::Inline; 8048 break; 8049 case lltok::kw_single: 8050 TTRes.TheKind = TypeTestResolution::Single; 8051 break; 8052 case lltok::kw_allOnes: 8053 TTRes.TheKind = TypeTestResolution::AllOnes; 8054 break; 8055 default: 8056 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 8057 } 8058 Lex.Lex(); 8059 8060 if (parseToken(lltok::comma, "expected ',' here") || 8061 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 8062 parseToken(lltok::colon, "expected ':' here") || 8063 parseUInt32(TTRes.SizeM1BitWidth)) 8064 return true; 8065 8066 // parse optional fields 8067 while (EatIfPresent(lltok::comma)) { 8068 switch (Lex.getKind()) { 8069 case lltok::kw_alignLog2: 8070 Lex.Lex(); 8071 if (parseToken(lltok::colon, "expected ':'") || 8072 parseUInt64(TTRes.AlignLog2)) 8073 return true; 8074 break; 8075 case lltok::kw_sizeM1: 8076 Lex.Lex(); 8077 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 8078 return true; 8079 break; 8080 case lltok::kw_bitMask: { 8081 unsigned Val; 8082 Lex.Lex(); 8083 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 8084 return true; 8085 assert(Val <= 0xff); 8086 TTRes.BitMask = (uint8_t)Val; 8087 break; 8088 } 8089 case lltok::kw_inlineBits: 8090 Lex.Lex(); 8091 if (parseToken(lltok::colon, "expected ':'") || 8092 parseUInt64(TTRes.InlineBits)) 8093 return true; 8094 break; 8095 default: 8096 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 8097 } 8098 } 8099 8100 if (parseToken(lltok::rparen, "expected ')' here")) 8101 return true; 8102 8103 return false; 8104 } 8105 8106 /// OptionalWpdResolutions 8107 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 8108 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 8109 bool LLParser::parseOptionalWpdResolutions( 8110 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 8111 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 8112 parseToken(lltok::colon, "expected ':' here") || 8113 parseToken(lltok::lparen, "expected '(' here")) 8114 return true; 8115 8116 do { 8117 uint64_t Offset; 8118 WholeProgramDevirtResolution WPDRes; 8119 if (parseToken(lltok::lparen, "expected '(' here") || 8120 parseToken(lltok::kw_offset, "expected 'offset' here") || 8121 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8122 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 8123 parseToken(lltok::rparen, "expected ')' here")) 8124 return true; 8125 WPDResMap[Offset] = WPDRes; 8126 } while (EatIfPresent(lltok::comma)); 8127 8128 if (parseToken(lltok::rparen, "expected ')' here")) 8129 return true; 8130 8131 return false; 8132 } 8133 8134 /// WpdRes 8135 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 8136 /// [',' OptionalResByArg]? ')' 8137 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 8138 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 8139 /// [',' OptionalResByArg]? ')' 8140 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 8141 /// [',' OptionalResByArg]? ')' 8142 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 8143 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 8144 parseToken(lltok::colon, "expected ':' here") || 8145 parseToken(lltok::lparen, "expected '(' here") || 8146 parseToken(lltok::kw_kind, "expected 'kind' here") || 8147 parseToken(lltok::colon, "expected ':' here")) 8148 return true; 8149 8150 switch (Lex.getKind()) { 8151 case lltok::kw_indir: 8152 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 8153 break; 8154 case lltok::kw_singleImpl: 8155 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 8156 break; 8157 case lltok::kw_branchFunnel: 8158 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 8159 break; 8160 default: 8161 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 8162 } 8163 Lex.Lex(); 8164 8165 // parse optional fields 8166 while (EatIfPresent(lltok::comma)) { 8167 switch (Lex.getKind()) { 8168 case lltok::kw_singleImplName: 8169 Lex.Lex(); 8170 if (parseToken(lltok::colon, "expected ':' here") || 8171 parseStringConstant(WPDRes.SingleImplName)) 8172 return true; 8173 break; 8174 case lltok::kw_resByArg: 8175 if (parseOptionalResByArg(WPDRes.ResByArg)) 8176 return true; 8177 break; 8178 default: 8179 return error(Lex.getLoc(), 8180 "expected optional WholeProgramDevirtResolution field"); 8181 } 8182 } 8183 8184 if (parseToken(lltok::rparen, "expected ')' here")) 8185 return true; 8186 8187 return false; 8188 } 8189 8190 /// OptionalResByArg 8191 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 8192 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 8193 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 8194 /// 'virtualConstProp' ) 8195 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 8196 /// [',' 'bit' ':' UInt32]? ')' 8197 bool LLParser::parseOptionalResByArg( 8198 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 8199 &ResByArg) { 8200 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 8201 parseToken(lltok::colon, "expected ':' here") || 8202 parseToken(lltok::lparen, "expected '(' here")) 8203 return true; 8204 8205 do { 8206 std::vector<uint64_t> Args; 8207 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 8208 parseToken(lltok::kw_byArg, "expected 'byArg here") || 8209 parseToken(lltok::colon, "expected ':' here") || 8210 parseToken(lltok::lparen, "expected '(' here") || 8211 parseToken(lltok::kw_kind, "expected 'kind' here") || 8212 parseToken(lltok::colon, "expected ':' here")) 8213 return true; 8214 8215 WholeProgramDevirtResolution::ByArg ByArg; 8216 switch (Lex.getKind()) { 8217 case lltok::kw_indir: 8218 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 8219 break; 8220 case lltok::kw_uniformRetVal: 8221 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 8222 break; 8223 case lltok::kw_uniqueRetVal: 8224 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 8225 break; 8226 case lltok::kw_virtualConstProp: 8227 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 8228 break; 8229 default: 8230 return error(Lex.getLoc(), 8231 "unexpected WholeProgramDevirtResolution::ByArg kind"); 8232 } 8233 Lex.Lex(); 8234 8235 // parse optional fields 8236 while (EatIfPresent(lltok::comma)) { 8237 switch (Lex.getKind()) { 8238 case lltok::kw_info: 8239 Lex.Lex(); 8240 if (parseToken(lltok::colon, "expected ':' here") || 8241 parseUInt64(ByArg.Info)) 8242 return true; 8243 break; 8244 case lltok::kw_byte: 8245 Lex.Lex(); 8246 if (parseToken(lltok::colon, "expected ':' here") || 8247 parseUInt32(ByArg.Byte)) 8248 return true; 8249 break; 8250 case lltok::kw_bit: 8251 Lex.Lex(); 8252 if (parseToken(lltok::colon, "expected ':' here") || 8253 parseUInt32(ByArg.Bit)) 8254 return true; 8255 break; 8256 default: 8257 return error(Lex.getLoc(), 8258 "expected optional whole program devirt field"); 8259 } 8260 } 8261 8262 if (parseToken(lltok::rparen, "expected ')' here")) 8263 return true; 8264 8265 ResByArg[Args] = ByArg; 8266 } while (EatIfPresent(lltok::comma)); 8267 8268 if (parseToken(lltok::rparen, "expected ')' here")) 8269 return true; 8270 8271 return false; 8272 } 8273 8274 /// OptionalResByArg 8275 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8276 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 8277 if (parseToken(lltok::kw_args, "expected 'args' here") || 8278 parseToken(lltok::colon, "expected ':' here") || 8279 parseToken(lltok::lparen, "expected '(' here")) 8280 return true; 8281 8282 do { 8283 uint64_t Val; 8284 if (parseUInt64(Val)) 8285 return true; 8286 Args.push_back(Val); 8287 } while (EatIfPresent(lltok::comma)); 8288 8289 if (parseToken(lltok::rparen, "expected ')' here")) 8290 return true; 8291 8292 return false; 8293 } 8294 8295 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8296 8297 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8298 bool ReadOnly = Fwd->isReadOnly(); 8299 bool WriteOnly = Fwd->isWriteOnly(); 8300 assert(!(ReadOnly && WriteOnly)); 8301 *Fwd = Resolved; 8302 if (ReadOnly) 8303 Fwd->setReadOnly(); 8304 if (WriteOnly) 8305 Fwd->setWriteOnly(); 8306 } 8307 8308 /// Stores the given Name/GUID and associated summary into the Index. 8309 /// Also updates any forward references to the associated entry ID. 8310 void LLParser::addGlobalValueToIndex( 8311 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8312 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8313 // First create the ValueInfo utilizing the Name or GUID. 8314 ValueInfo VI; 8315 if (GUID != 0) { 8316 assert(Name.empty()); 8317 VI = Index->getOrInsertValueInfo(GUID); 8318 } else { 8319 assert(!Name.empty()); 8320 if (M) { 8321 auto *GV = M->getNamedValue(Name); 8322 assert(GV); 8323 VI = Index->getOrInsertValueInfo(GV); 8324 } else { 8325 assert( 8326 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8327 "Need a source_filename to compute GUID for local"); 8328 GUID = GlobalValue::getGUID( 8329 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8330 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8331 } 8332 } 8333 8334 // Resolve forward references from calls/refs 8335 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8336 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8337 for (auto VIRef : FwdRefVIs->second) { 8338 assert(VIRef.first->getRef() == FwdVIRef && 8339 "Forward referenced ValueInfo expected to be empty"); 8340 resolveFwdRef(VIRef.first, VI); 8341 } 8342 ForwardRefValueInfos.erase(FwdRefVIs); 8343 } 8344 8345 // Resolve forward references from aliases 8346 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8347 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8348 for (auto AliaseeRef : FwdRefAliasees->second) { 8349 assert(!AliaseeRef.first->hasAliasee() && 8350 "Forward referencing alias already has aliasee"); 8351 assert(Summary && "Aliasee must be a definition"); 8352 AliaseeRef.first->setAliasee(VI, Summary.get()); 8353 } 8354 ForwardRefAliasees.erase(FwdRefAliasees); 8355 } 8356 8357 // Add the summary if one was provided. 8358 if (Summary) 8359 Index->addGlobalValueSummary(VI, std::move(Summary)); 8360 8361 // Save the associated ValueInfo for use in later references by ID. 8362 if (ID == NumberedValueInfos.size()) 8363 NumberedValueInfos.push_back(VI); 8364 else { 8365 // Handle non-continuous numbers (to make test simplification easier). 8366 if (ID > NumberedValueInfos.size()) 8367 NumberedValueInfos.resize(ID + 1); 8368 NumberedValueInfos[ID] = VI; 8369 } 8370 } 8371 8372 /// parseSummaryIndexFlags 8373 /// ::= 'flags' ':' UInt64 8374 bool LLParser::parseSummaryIndexFlags() { 8375 assert(Lex.getKind() == lltok::kw_flags); 8376 Lex.Lex(); 8377 8378 if (parseToken(lltok::colon, "expected ':' here")) 8379 return true; 8380 uint64_t Flags; 8381 if (parseUInt64(Flags)) 8382 return true; 8383 if (Index) 8384 Index->setFlags(Flags); 8385 return false; 8386 } 8387 8388 /// parseBlockCount 8389 /// ::= 'blockcount' ':' UInt64 8390 bool LLParser::parseBlockCount() { 8391 assert(Lex.getKind() == lltok::kw_blockcount); 8392 Lex.Lex(); 8393 8394 if (parseToken(lltok::colon, "expected ':' here")) 8395 return true; 8396 uint64_t BlockCount; 8397 if (parseUInt64(BlockCount)) 8398 return true; 8399 if (Index) 8400 Index->setBlockCount(BlockCount); 8401 return false; 8402 } 8403 8404 /// parseGVEntry 8405 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8406 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8407 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8408 bool LLParser::parseGVEntry(unsigned ID) { 8409 assert(Lex.getKind() == lltok::kw_gv); 8410 Lex.Lex(); 8411 8412 if (parseToken(lltok::colon, "expected ':' here") || 8413 parseToken(lltok::lparen, "expected '(' here")) 8414 return true; 8415 8416 std::string Name; 8417 GlobalValue::GUID GUID = 0; 8418 switch (Lex.getKind()) { 8419 case lltok::kw_name: 8420 Lex.Lex(); 8421 if (parseToken(lltok::colon, "expected ':' here") || 8422 parseStringConstant(Name)) 8423 return true; 8424 // Can't create GUID/ValueInfo until we have the linkage. 8425 break; 8426 case lltok::kw_guid: 8427 Lex.Lex(); 8428 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 8429 return true; 8430 break; 8431 default: 8432 return error(Lex.getLoc(), "expected name or guid tag"); 8433 } 8434 8435 if (!EatIfPresent(lltok::comma)) { 8436 // No summaries. Wrap up. 8437 if (parseToken(lltok::rparen, "expected ')' here")) 8438 return true; 8439 // This was created for a call to an external or indirect target. 8440 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8441 // created for indirect calls with VP. A Name with no GUID came from 8442 // an external definition. We pass ExternalLinkage since that is only 8443 // used when the GUID must be computed from Name, and in that case 8444 // the symbol must have external linkage. 8445 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8446 nullptr); 8447 return false; 8448 } 8449 8450 // Have a list of summaries 8451 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 8452 parseToken(lltok::colon, "expected ':' here") || 8453 parseToken(lltok::lparen, "expected '(' here")) 8454 return true; 8455 do { 8456 switch (Lex.getKind()) { 8457 case lltok::kw_function: 8458 if (parseFunctionSummary(Name, GUID, ID)) 8459 return true; 8460 break; 8461 case lltok::kw_variable: 8462 if (parseVariableSummary(Name, GUID, ID)) 8463 return true; 8464 break; 8465 case lltok::kw_alias: 8466 if (parseAliasSummary(Name, GUID, ID)) 8467 return true; 8468 break; 8469 default: 8470 return error(Lex.getLoc(), "expected summary type"); 8471 } 8472 } while (EatIfPresent(lltok::comma)); 8473 8474 if (parseToken(lltok::rparen, "expected ')' here") || 8475 parseToken(lltok::rparen, "expected ')' here")) 8476 return true; 8477 8478 return false; 8479 } 8480 8481 /// FunctionSummary 8482 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8483 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8484 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8485 /// [',' OptionalRefs]? ')' 8486 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8487 unsigned ID) { 8488 assert(Lex.getKind() == lltok::kw_function); 8489 Lex.Lex(); 8490 8491 StringRef ModulePath; 8492 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8493 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8494 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8495 unsigned InstCount; 8496 std::vector<FunctionSummary::EdgeTy> Calls; 8497 FunctionSummary::TypeIdInfo TypeIdInfo; 8498 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8499 std::vector<ValueInfo> Refs; 8500 // Default is all-zeros (conservative values). 8501 FunctionSummary::FFlags FFlags = {}; 8502 if (parseToken(lltok::colon, "expected ':' here") || 8503 parseToken(lltok::lparen, "expected '(' here") || 8504 parseModuleReference(ModulePath) || 8505 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8506 parseToken(lltok::comma, "expected ',' here") || 8507 parseToken(lltok::kw_insts, "expected 'insts' here") || 8508 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 8509 return true; 8510 8511 // parse optional fields 8512 while (EatIfPresent(lltok::comma)) { 8513 switch (Lex.getKind()) { 8514 case lltok::kw_funcFlags: 8515 if (parseOptionalFFlags(FFlags)) 8516 return true; 8517 break; 8518 case lltok::kw_calls: 8519 if (parseOptionalCalls(Calls)) 8520 return true; 8521 break; 8522 case lltok::kw_typeIdInfo: 8523 if (parseOptionalTypeIdInfo(TypeIdInfo)) 8524 return true; 8525 break; 8526 case lltok::kw_refs: 8527 if (parseOptionalRefs(Refs)) 8528 return true; 8529 break; 8530 case lltok::kw_params: 8531 if (parseOptionalParamAccesses(ParamAccesses)) 8532 return true; 8533 break; 8534 default: 8535 return error(Lex.getLoc(), "expected optional function summary field"); 8536 } 8537 } 8538 8539 if (parseToken(lltok::rparen, "expected ')' here")) 8540 return true; 8541 8542 auto FS = std::make_unique<FunctionSummary>( 8543 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8544 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8545 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8546 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8547 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8548 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8549 std::move(ParamAccesses)); 8550 8551 FS->setModulePath(ModulePath); 8552 8553 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8554 ID, std::move(FS)); 8555 8556 return false; 8557 } 8558 8559 /// VariableSummary 8560 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8561 /// [',' OptionalRefs]? ')' 8562 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8563 unsigned ID) { 8564 assert(Lex.getKind() == lltok::kw_variable); 8565 Lex.Lex(); 8566 8567 StringRef ModulePath; 8568 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8569 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8570 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8571 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8572 /* WriteOnly */ false, 8573 /* Constant */ false, 8574 GlobalObject::VCallVisibilityPublic); 8575 std::vector<ValueInfo> Refs; 8576 VTableFuncList VTableFuncs; 8577 if (parseToken(lltok::colon, "expected ':' here") || 8578 parseToken(lltok::lparen, "expected '(' here") || 8579 parseModuleReference(ModulePath) || 8580 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8581 parseToken(lltok::comma, "expected ',' here") || 8582 parseGVarFlags(GVarFlags)) 8583 return true; 8584 8585 // parse optional fields 8586 while (EatIfPresent(lltok::comma)) { 8587 switch (Lex.getKind()) { 8588 case lltok::kw_vTableFuncs: 8589 if (parseOptionalVTableFuncs(VTableFuncs)) 8590 return true; 8591 break; 8592 case lltok::kw_refs: 8593 if (parseOptionalRefs(Refs)) 8594 return true; 8595 break; 8596 default: 8597 return error(Lex.getLoc(), "expected optional variable summary field"); 8598 } 8599 } 8600 8601 if (parseToken(lltok::rparen, "expected ')' here")) 8602 return true; 8603 8604 auto GS = 8605 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8606 8607 GS->setModulePath(ModulePath); 8608 GS->setVTableFuncs(std::move(VTableFuncs)); 8609 8610 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8611 ID, std::move(GS)); 8612 8613 return false; 8614 } 8615 8616 /// AliasSummary 8617 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8618 /// 'aliasee' ':' GVReference ')' 8619 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8620 unsigned ID) { 8621 assert(Lex.getKind() == lltok::kw_alias); 8622 LocTy Loc = Lex.getLoc(); 8623 Lex.Lex(); 8624 8625 StringRef ModulePath; 8626 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8627 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8628 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8629 if (parseToken(lltok::colon, "expected ':' here") || 8630 parseToken(lltok::lparen, "expected '(' here") || 8631 parseModuleReference(ModulePath) || 8632 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8633 parseToken(lltok::comma, "expected ',' here") || 8634 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8635 parseToken(lltok::colon, "expected ':' here")) 8636 return true; 8637 8638 ValueInfo AliaseeVI; 8639 unsigned GVId; 8640 if (parseGVReference(AliaseeVI, GVId)) 8641 return true; 8642 8643 if (parseToken(lltok::rparen, "expected ')' here")) 8644 return true; 8645 8646 auto AS = std::make_unique<AliasSummary>(GVFlags); 8647 8648 AS->setModulePath(ModulePath); 8649 8650 // Record forward reference if the aliasee is not parsed yet. 8651 if (AliaseeVI.getRef() == FwdVIRef) { 8652 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 8653 } else { 8654 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8655 assert(Summary && "Aliasee must be a definition"); 8656 AS->setAliasee(AliaseeVI, Summary); 8657 } 8658 8659 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8660 ID, std::move(AS)); 8661 8662 return false; 8663 } 8664 8665 /// Flag 8666 /// ::= [0|1] 8667 bool LLParser::parseFlag(unsigned &Val) { 8668 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8669 return tokError("expected integer"); 8670 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8671 Lex.Lex(); 8672 return false; 8673 } 8674 8675 /// OptionalFFlags 8676 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8677 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8678 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8679 /// [',' 'noInline' ':' Flag]? ')' 8680 /// [',' 'alwaysInline' ':' Flag]? ')' 8681 8682 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8683 assert(Lex.getKind() == lltok::kw_funcFlags); 8684 Lex.Lex(); 8685 8686 if (parseToken(lltok::colon, "expected ':' in funcFlags") | 8687 parseToken(lltok::lparen, "expected '(' in funcFlags")) 8688 return true; 8689 8690 do { 8691 unsigned Val = 0; 8692 switch (Lex.getKind()) { 8693 case lltok::kw_readNone: 8694 Lex.Lex(); 8695 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8696 return true; 8697 FFlags.ReadNone = Val; 8698 break; 8699 case lltok::kw_readOnly: 8700 Lex.Lex(); 8701 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8702 return true; 8703 FFlags.ReadOnly = Val; 8704 break; 8705 case lltok::kw_noRecurse: 8706 Lex.Lex(); 8707 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8708 return true; 8709 FFlags.NoRecurse = Val; 8710 break; 8711 case lltok::kw_returnDoesNotAlias: 8712 Lex.Lex(); 8713 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8714 return true; 8715 FFlags.ReturnDoesNotAlias = Val; 8716 break; 8717 case lltok::kw_noInline: 8718 Lex.Lex(); 8719 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8720 return true; 8721 FFlags.NoInline = Val; 8722 break; 8723 case lltok::kw_alwaysInline: 8724 Lex.Lex(); 8725 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8726 return true; 8727 FFlags.AlwaysInline = Val; 8728 break; 8729 default: 8730 return error(Lex.getLoc(), "expected function flag type"); 8731 } 8732 } while (EatIfPresent(lltok::comma)); 8733 8734 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 8735 return true; 8736 8737 return false; 8738 } 8739 8740 /// OptionalCalls 8741 /// := 'calls' ':' '(' Call [',' Call]* ')' 8742 /// Call ::= '(' 'callee' ':' GVReference 8743 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8744 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8745 assert(Lex.getKind() == lltok::kw_calls); 8746 Lex.Lex(); 8747 8748 if (parseToken(lltok::colon, "expected ':' in calls") | 8749 parseToken(lltok::lparen, "expected '(' in calls")) 8750 return true; 8751 8752 IdToIndexMapType IdToIndexMap; 8753 // parse each call edge 8754 do { 8755 ValueInfo VI; 8756 if (parseToken(lltok::lparen, "expected '(' in call") || 8757 parseToken(lltok::kw_callee, "expected 'callee' in call") || 8758 parseToken(lltok::colon, "expected ':'")) 8759 return true; 8760 8761 LocTy Loc = Lex.getLoc(); 8762 unsigned GVId; 8763 if (parseGVReference(VI, GVId)) 8764 return true; 8765 8766 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8767 unsigned RelBF = 0; 8768 if (EatIfPresent(lltok::comma)) { 8769 // Expect either hotness or relbf 8770 if (EatIfPresent(lltok::kw_hotness)) { 8771 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 8772 return true; 8773 } else { 8774 if (parseToken(lltok::kw_relbf, "expected relbf") || 8775 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 8776 return true; 8777 } 8778 } 8779 // Keep track of the Call array index needing a forward reference. 8780 // We will save the location of the ValueInfo needing an update, but 8781 // can only do so once the std::vector is finalized. 8782 if (VI.getRef() == FwdVIRef) 8783 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8784 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8785 8786 if (parseToken(lltok::rparen, "expected ')' in call")) 8787 return true; 8788 } while (EatIfPresent(lltok::comma)); 8789 8790 // Now that the Calls vector is finalized, it is safe to save the locations 8791 // of any forward GV references that need updating later. 8792 for (auto I : IdToIndexMap) { 8793 auto &Infos = ForwardRefValueInfos[I.first]; 8794 for (auto P : I.second) { 8795 assert(Calls[P.first].first.getRef() == FwdVIRef && 8796 "Forward referenced ValueInfo expected to be empty"); 8797 Infos.emplace_back(&Calls[P.first].first, P.second); 8798 } 8799 } 8800 8801 if (parseToken(lltok::rparen, "expected ')' in calls")) 8802 return true; 8803 8804 return false; 8805 } 8806 8807 /// Hotness 8808 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8809 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 8810 switch (Lex.getKind()) { 8811 case lltok::kw_unknown: 8812 Hotness = CalleeInfo::HotnessType::Unknown; 8813 break; 8814 case lltok::kw_cold: 8815 Hotness = CalleeInfo::HotnessType::Cold; 8816 break; 8817 case lltok::kw_none: 8818 Hotness = CalleeInfo::HotnessType::None; 8819 break; 8820 case lltok::kw_hot: 8821 Hotness = CalleeInfo::HotnessType::Hot; 8822 break; 8823 case lltok::kw_critical: 8824 Hotness = CalleeInfo::HotnessType::Critical; 8825 break; 8826 default: 8827 return error(Lex.getLoc(), "invalid call edge hotness"); 8828 } 8829 Lex.Lex(); 8830 return false; 8831 } 8832 8833 /// OptionalVTableFuncs 8834 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8835 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8836 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8837 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8838 Lex.Lex(); 8839 8840 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") | 8841 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8842 return true; 8843 8844 IdToIndexMapType IdToIndexMap; 8845 // parse each virtual function pair 8846 do { 8847 ValueInfo VI; 8848 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 8849 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8850 parseToken(lltok::colon, "expected ':'")) 8851 return true; 8852 8853 LocTy Loc = Lex.getLoc(); 8854 unsigned GVId; 8855 if (parseGVReference(VI, GVId)) 8856 return true; 8857 8858 uint64_t Offset; 8859 if (parseToken(lltok::comma, "expected comma") || 8860 parseToken(lltok::kw_offset, "expected offset") || 8861 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 8862 return true; 8863 8864 // Keep track of the VTableFuncs array index needing a forward reference. 8865 // We will save the location of the ValueInfo needing an update, but 8866 // can only do so once the std::vector is finalized. 8867 if (VI == EmptyVI) 8868 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8869 VTableFuncs.push_back({VI, Offset}); 8870 8871 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 8872 return true; 8873 } while (EatIfPresent(lltok::comma)); 8874 8875 // Now that the VTableFuncs vector is finalized, it is safe to save the 8876 // locations of any forward GV references that need updating later. 8877 for (auto I : IdToIndexMap) { 8878 auto &Infos = ForwardRefValueInfos[I.first]; 8879 for (auto P : I.second) { 8880 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8881 "Forward referenced ValueInfo expected to be empty"); 8882 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 8883 } 8884 } 8885 8886 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8887 return true; 8888 8889 return false; 8890 } 8891 8892 /// ParamNo := 'param' ':' UInt64 8893 bool LLParser::parseParamNo(uint64_t &ParamNo) { 8894 if (parseToken(lltok::kw_param, "expected 'param' here") || 8895 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 8896 return true; 8897 return false; 8898 } 8899 8900 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8901 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 8902 APSInt Lower; 8903 APSInt Upper; 8904 auto ParseAPSInt = [&](APSInt &Val) { 8905 if (Lex.getKind() != lltok::APSInt) 8906 return tokError("expected integer"); 8907 Val = Lex.getAPSIntVal(); 8908 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8909 Val.setIsSigned(true); 8910 Lex.Lex(); 8911 return false; 8912 }; 8913 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 8914 parseToken(lltok::colon, "expected ':' here") || 8915 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8916 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8917 parseToken(lltok::rsquare, "expected ']' here")) 8918 return true; 8919 8920 ++Upper; 8921 Range = 8922 (Lower == Upper && !Lower.isMaxValue()) 8923 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8924 : ConstantRange(Lower, Upper); 8925 8926 return false; 8927 } 8928 8929 /// ParamAccessCall 8930 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8931 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 8932 IdLocListType &IdLocList) { 8933 if (parseToken(lltok::lparen, "expected '(' here") || 8934 parseToken(lltok::kw_callee, "expected 'callee' here") || 8935 parseToken(lltok::colon, "expected ':' here")) 8936 return true; 8937 8938 unsigned GVId; 8939 ValueInfo VI; 8940 LocTy Loc = Lex.getLoc(); 8941 if (parseGVReference(VI, GVId)) 8942 return true; 8943 8944 Call.Callee = VI; 8945 IdLocList.emplace_back(GVId, Loc); 8946 8947 if (parseToken(lltok::comma, "expected ',' here") || 8948 parseParamNo(Call.ParamNo) || 8949 parseToken(lltok::comma, "expected ',' here") || 8950 parseParamAccessOffset(Call.Offsets)) 8951 return true; 8952 8953 if (parseToken(lltok::rparen, "expected ')' here")) 8954 return true; 8955 8956 return false; 8957 } 8958 8959 /// ParamAccess 8960 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8961 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8962 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 8963 IdLocListType &IdLocList) { 8964 if (parseToken(lltok::lparen, "expected '(' here") || 8965 parseParamNo(Param.ParamNo) || 8966 parseToken(lltok::comma, "expected ',' here") || 8967 parseParamAccessOffset(Param.Use)) 8968 return true; 8969 8970 if (EatIfPresent(lltok::comma)) { 8971 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 8972 parseToken(lltok::colon, "expected ':' here") || 8973 parseToken(lltok::lparen, "expected '(' here")) 8974 return true; 8975 do { 8976 FunctionSummary::ParamAccess::Call Call; 8977 if (parseParamAccessCall(Call, IdLocList)) 8978 return true; 8979 Param.Calls.push_back(Call); 8980 } while (EatIfPresent(lltok::comma)); 8981 8982 if (parseToken(lltok::rparen, "expected ')' here")) 8983 return true; 8984 } 8985 8986 if (parseToken(lltok::rparen, "expected ')' here")) 8987 return true; 8988 8989 return false; 8990 } 8991 8992 /// OptionalParamAccesses 8993 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8994 bool LLParser::parseOptionalParamAccesses( 8995 std::vector<FunctionSummary::ParamAccess> &Params) { 8996 assert(Lex.getKind() == lltok::kw_params); 8997 Lex.Lex(); 8998 8999 if (parseToken(lltok::colon, "expected ':' here") || 9000 parseToken(lltok::lparen, "expected '(' here")) 9001 return true; 9002 9003 IdLocListType VContexts; 9004 size_t CallsNum = 0; 9005 do { 9006 FunctionSummary::ParamAccess ParamAccess; 9007 if (parseParamAccess(ParamAccess, VContexts)) 9008 return true; 9009 CallsNum += ParamAccess.Calls.size(); 9010 assert(VContexts.size() == CallsNum); 9011 Params.emplace_back(std::move(ParamAccess)); 9012 } while (EatIfPresent(lltok::comma)); 9013 9014 if (parseToken(lltok::rparen, "expected ')' here")) 9015 return true; 9016 9017 // Now that the Params is finalized, it is safe to save the locations 9018 // of any forward GV references that need updating later. 9019 IdLocListType::const_iterator ItContext = VContexts.begin(); 9020 for (auto &PA : Params) { 9021 for (auto &C : PA.Calls) { 9022 if (C.Callee.getRef() == FwdVIRef) 9023 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 9024 ItContext->second); 9025 ++ItContext; 9026 } 9027 } 9028 assert(ItContext == VContexts.end()); 9029 9030 return false; 9031 } 9032 9033 /// OptionalRefs 9034 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 9035 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) { 9036 assert(Lex.getKind() == lltok::kw_refs); 9037 Lex.Lex(); 9038 9039 if (parseToken(lltok::colon, "expected ':' in refs") || 9040 parseToken(lltok::lparen, "expected '(' in refs")) 9041 return true; 9042 9043 struct ValueContext { 9044 ValueInfo VI; 9045 unsigned GVId; 9046 LocTy Loc; 9047 }; 9048 std::vector<ValueContext> VContexts; 9049 // parse each ref edge 9050 do { 9051 ValueContext VC; 9052 VC.Loc = Lex.getLoc(); 9053 if (parseGVReference(VC.VI, VC.GVId)) 9054 return true; 9055 VContexts.push_back(VC); 9056 } while (EatIfPresent(lltok::comma)); 9057 9058 // Sort value contexts so that ones with writeonly 9059 // and readonly ValueInfo are at the end of VContexts vector. 9060 // See FunctionSummary::specialRefCounts() 9061 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 9062 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 9063 }); 9064 9065 IdToIndexMapType IdToIndexMap; 9066 for (auto &VC : VContexts) { 9067 // Keep track of the Refs array index needing a forward reference. 9068 // We will save the location of the ValueInfo needing an update, but 9069 // can only do so once the std::vector is finalized. 9070 if (VC.VI.getRef() == FwdVIRef) 9071 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 9072 Refs.push_back(VC.VI); 9073 } 9074 9075 // Now that the Refs vector is finalized, it is safe to save the locations 9076 // of any forward GV references that need updating later. 9077 for (auto I : IdToIndexMap) { 9078 auto &Infos = ForwardRefValueInfos[I.first]; 9079 for (auto P : I.second) { 9080 assert(Refs[P.first].getRef() == FwdVIRef && 9081 "Forward referenced ValueInfo expected to be empty"); 9082 Infos.emplace_back(&Refs[P.first], P.second); 9083 } 9084 } 9085 9086 if (parseToken(lltok::rparen, "expected ')' in refs")) 9087 return true; 9088 9089 return false; 9090 } 9091 9092 /// OptionalTypeIdInfo 9093 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 9094 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 9095 /// [',' TypeCheckedLoadConstVCalls]? ')' 9096 bool LLParser::parseOptionalTypeIdInfo( 9097 FunctionSummary::TypeIdInfo &TypeIdInfo) { 9098 assert(Lex.getKind() == lltok::kw_typeIdInfo); 9099 Lex.Lex(); 9100 9101 if (parseToken(lltok::colon, "expected ':' here") || 9102 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9103 return true; 9104 9105 do { 9106 switch (Lex.getKind()) { 9107 case lltok::kw_typeTests: 9108 if (parseTypeTests(TypeIdInfo.TypeTests)) 9109 return true; 9110 break; 9111 case lltok::kw_typeTestAssumeVCalls: 9112 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 9113 TypeIdInfo.TypeTestAssumeVCalls)) 9114 return true; 9115 break; 9116 case lltok::kw_typeCheckedLoadVCalls: 9117 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 9118 TypeIdInfo.TypeCheckedLoadVCalls)) 9119 return true; 9120 break; 9121 case lltok::kw_typeTestAssumeConstVCalls: 9122 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 9123 TypeIdInfo.TypeTestAssumeConstVCalls)) 9124 return true; 9125 break; 9126 case lltok::kw_typeCheckedLoadConstVCalls: 9127 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 9128 TypeIdInfo.TypeCheckedLoadConstVCalls)) 9129 return true; 9130 break; 9131 default: 9132 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 9133 } 9134 } while (EatIfPresent(lltok::comma)); 9135 9136 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9137 return true; 9138 9139 return false; 9140 } 9141 9142 /// TypeTests 9143 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 9144 /// [',' (SummaryID | UInt64)]* ')' 9145 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 9146 assert(Lex.getKind() == lltok::kw_typeTests); 9147 Lex.Lex(); 9148 9149 if (parseToken(lltok::colon, "expected ':' here") || 9150 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9151 return true; 9152 9153 IdToIndexMapType IdToIndexMap; 9154 do { 9155 GlobalValue::GUID GUID = 0; 9156 if (Lex.getKind() == lltok::SummaryID) { 9157 unsigned ID = Lex.getUIntVal(); 9158 LocTy Loc = Lex.getLoc(); 9159 // Keep track of the TypeTests array index needing a forward reference. 9160 // We will save the location of the GUID needing an update, but 9161 // can only do so once the std::vector is finalized. 9162 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 9163 Lex.Lex(); 9164 } else if (parseUInt64(GUID)) 9165 return true; 9166 TypeTests.push_back(GUID); 9167 } while (EatIfPresent(lltok::comma)); 9168 9169 // Now that the TypeTests vector is finalized, it is safe to save the 9170 // locations of any forward GV references that need updating later. 9171 for (auto I : IdToIndexMap) { 9172 auto &Ids = ForwardRefTypeIds[I.first]; 9173 for (auto P : I.second) { 9174 assert(TypeTests[P.first] == 0 && 9175 "Forward referenced type id GUID expected to be 0"); 9176 Ids.emplace_back(&TypeTests[P.first], P.second); 9177 } 9178 } 9179 9180 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9181 return true; 9182 9183 return false; 9184 } 9185 9186 /// VFuncIdList 9187 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 9188 bool LLParser::parseVFuncIdList( 9189 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 9190 assert(Lex.getKind() == Kind); 9191 Lex.Lex(); 9192 9193 if (parseToken(lltok::colon, "expected ':' here") || 9194 parseToken(lltok::lparen, "expected '(' here")) 9195 return true; 9196 9197 IdToIndexMapType IdToIndexMap; 9198 do { 9199 FunctionSummary::VFuncId VFuncId; 9200 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 9201 return true; 9202 VFuncIdList.push_back(VFuncId); 9203 } while (EatIfPresent(lltok::comma)); 9204 9205 if (parseToken(lltok::rparen, "expected ')' here")) 9206 return true; 9207 9208 // Now that the VFuncIdList vector is finalized, it is safe to save the 9209 // locations of any forward GV references that need updating later. 9210 for (auto I : IdToIndexMap) { 9211 auto &Ids = ForwardRefTypeIds[I.first]; 9212 for (auto P : I.second) { 9213 assert(VFuncIdList[P.first].GUID == 0 && 9214 "Forward referenced type id GUID expected to be 0"); 9215 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 9216 } 9217 } 9218 9219 return false; 9220 } 9221 9222 /// ConstVCallList 9223 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 9224 bool LLParser::parseConstVCallList( 9225 lltok::Kind Kind, 9226 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 9227 assert(Lex.getKind() == Kind); 9228 Lex.Lex(); 9229 9230 if (parseToken(lltok::colon, "expected ':' here") || 9231 parseToken(lltok::lparen, "expected '(' here")) 9232 return true; 9233 9234 IdToIndexMapType IdToIndexMap; 9235 do { 9236 FunctionSummary::ConstVCall ConstVCall; 9237 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 9238 return true; 9239 ConstVCallList.push_back(ConstVCall); 9240 } while (EatIfPresent(lltok::comma)); 9241 9242 if (parseToken(lltok::rparen, "expected ')' here")) 9243 return true; 9244 9245 // Now that the ConstVCallList vector is finalized, it is safe to save the 9246 // locations of any forward GV references that need updating later. 9247 for (auto I : IdToIndexMap) { 9248 auto &Ids = ForwardRefTypeIds[I.first]; 9249 for (auto P : I.second) { 9250 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 9251 "Forward referenced type id GUID expected to be 0"); 9252 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 9253 } 9254 } 9255 9256 return false; 9257 } 9258 9259 /// ConstVCall 9260 /// ::= '(' VFuncId ',' Args ')' 9261 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 9262 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9263 if (parseToken(lltok::lparen, "expected '(' here") || 9264 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 9265 return true; 9266 9267 if (EatIfPresent(lltok::comma)) 9268 if (parseArgs(ConstVCall.Args)) 9269 return true; 9270 9271 if (parseToken(lltok::rparen, "expected ')' here")) 9272 return true; 9273 9274 return false; 9275 } 9276 9277 /// VFuncId 9278 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9279 /// 'offset' ':' UInt64 ')' 9280 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 9281 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9282 assert(Lex.getKind() == lltok::kw_vFuncId); 9283 Lex.Lex(); 9284 9285 if (parseToken(lltok::colon, "expected ':' here") || 9286 parseToken(lltok::lparen, "expected '(' here")) 9287 return true; 9288 9289 if (Lex.getKind() == lltok::SummaryID) { 9290 VFuncId.GUID = 0; 9291 unsigned ID = Lex.getUIntVal(); 9292 LocTy Loc = Lex.getLoc(); 9293 // Keep track of the array index needing a forward reference. 9294 // We will save the location of the GUID needing an update, but 9295 // can only do so once the caller's std::vector is finalized. 9296 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9297 Lex.Lex(); 9298 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 9299 parseToken(lltok::colon, "expected ':' here") || 9300 parseUInt64(VFuncId.GUID)) 9301 return true; 9302 9303 if (parseToken(lltok::comma, "expected ',' here") || 9304 parseToken(lltok::kw_offset, "expected 'offset' here") || 9305 parseToken(lltok::colon, "expected ':' here") || 9306 parseUInt64(VFuncId.Offset) || 9307 parseToken(lltok::rparen, "expected ')' here")) 9308 return true; 9309 9310 return false; 9311 } 9312 9313 /// GVFlags 9314 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9315 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ',' 9316 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')' 9317 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9318 assert(Lex.getKind() == lltok::kw_flags); 9319 Lex.Lex(); 9320 9321 if (parseToken(lltok::colon, "expected ':' here") || 9322 parseToken(lltok::lparen, "expected '(' here")) 9323 return true; 9324 9325 do { 9326 unsigned Flag = 0; 9327 switch (Lex.getKind()) { 9328 case lltok::kw_linkage: 9329 Lex.Lex(); 9330 if (parseToken(lltok::colon, "expected ':'")) 9331 return true; 9332 bool HasLinkage; 9333 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9334 assert(HasLinkage && "Linkage not optional in summary entry"); 9335 Lex.Lex(); 9336 break; 9337 case lltok::kw_notEligibleToImport: 9338 Lex.Lex(); 9339 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9340 return true; 9341 GVFlags.NotEligibleToImport = Flag; 9342 break; 9343 case lltok::kw_live: 9344 Lex.Lex(); 9345 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9346 return true; 9347 GVFlags.Live = Flag; 9348 break; 9349 case lltok::kw_dsoLocal: 9350 Lex.Lex(); 9351 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9352 return true; 9353 GVFlags.DSOLocal = Flag; 9354 break; 9355 case lltok::kw_canAutoHide: 9356 Lex.Lex(); 9357 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9358 return true; 9359 GVFlags.CanAutoHide = Flag; 9360 break; 9361 default: 9362 return error(Lex.getLoc(), "expected gv flag type"); 9363 } 9364 } while (EatIfPresent(lltok::comma)); 9365 9366 if (parseToken(lltok::rparen, "expected ')' here")) 9367 return true; 9368 9369 return false; 9370 } 9371 9372 /// GVarFlags 9373 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9374 /// ',' 'writeonly' ':' Flag 9375 /// ',' 'constant' ':' Flag ')' 9376 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9377 assert(Lex.getKind() == lltok::kw_varFlags); 9378 Lex.Lex(); 9379 9380 if (parseToken(lltok::colon, "expected ':' here") || 9381 parseToken(lltok::lparen, "expected '(' here")) 9382 return true; 9383 9384 auto ParseRest = [this](unsigned int &Val) { 9385 Lex.Lex(); 9386 if (parseToken(lltok::colon, "expected ':'")) 9387 return true; 9388 return parseFlag(Val); 9389 }; 9390 9391 do { 9392 unsigned Flag = 0; 9393 switch (Lex.getKind()) { 9394 case lltok::kw_readonly: 9395 if (ParseRest(Flag)) 9396 return true; 9397 GVarFlags.MaybeReadOnly = Flag; 9398 break; 9399 case lltok::kw_writeonly: 9400 if (ParseRest(Flag)) 9401 return true; 9402 GVarFlags.MaybeWriteOnly = Flag; 9403 break; 9404 case lltok::kw_constant: 9405 if (ParseRest(Flag)) 9406 return true; 9407 GVarFlags.Constant = Flag; 9408 break; 9409 case lltok::kw_vcall_visibility: 9410 if (ParseRest(Flag)) 9411 return true; 9412 GVarFlags.VCallVisibility = Flag; 9413 break; 9414 default: 9415 return error(Lex.getLoc(), "expected gvar flag type"); 9416 } 9417 } while (EatIfPresent(lltok::comma)); 9418 return parseToken(lltok::rparen, "expected ')' here"); 9419 } 9420 9421 /// ModuleReference 9422 /// ::= 'module' ':' UInt 9423 bool LLParser::parseModuleReference(StringRef &ModulePath) { 9424 // parse module id. 9425 if (parseToken(lltok::kw_module, "expected 'module' here") || 9426 parseToken(lltok::colon, "expected ':' here") || 9427 parseToken(lltok::SummaryID, "expected module ID")) 9428 return true; 9429 9430 unsigned ModuleID = Lex.getUIntVal(); 9431 auto I = ModuleIdMap.find(ModuleID); 9432 // We should have already parsed all module IDs 9433 assert(I != ModuleIdMap.end()); 9434 ModulePath = I->second; 9435 return false; 9436 } 9437 9438 /// GVReference 9439 /// ::= SummaryID 9440 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 9441 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9442 if (!ReadOnly) 9443 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9444 if (parseToken(lltok::SummaryID, "expected GV ID")) 9445 return true; 9446 9447 GVId = Lex.getUIntVal(); 9448 // Check if we already have a VI for this GV 9449 if (GVId < NumberedValueInfos.size()) { 9450 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9451 VI = NumberedValueInfos[GVId]; 9452 } else 9453 // We will create a forward reference to the stored location. 9454 VI = ValueInfo(false, FwdVIRef); 9455 9456 if (ReadOnly) 9457 VI.setReadOnly(); 9458 if (WriteOnly) 9459 VI.setWriteOnly(); 9460 return false; 9461 } 9462