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