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