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