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