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