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