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