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