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