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