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 = 3654 BaseType->isVectorTy() 3655 ? cast<FixedVectorType>(BaseType)->getNumElements() 3656 : 0; 3657 3658 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3659 for (Constant *Val : Indices) { 3660 Type *ValTy = Val->getType(); 3661 if (!ValTy->isIntOrIntVectorTy()) 3662 return Error(ID.Loc, "getelementptr index must be an integer"); 3663 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 3664 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 3665 if (GEPWidth && (ValNumEl != GEPWidth)) 3666 return Error( 3667 ID.Loc, 3668 "getelementptr vector index has a wrong number of elements"); 3669 // GEPWidth may have been unknown because the base is a scalar, 3670 // but it is known now. 3671 GEPWidth = ValNumEl; 3672 } 3673 } 3674 3675 SmallPtrSet<Type*, 4> Visited; 3676 if (!Indices.empty() && !Ty->isSized(&Visited)) 3677 return Error(ID.Loc, "base element of getelementptr must be sized"); 3678 3679 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3680 return Error(ID.Loc, "invalid getelementptr indices"); 3681 3682 if (InRangeOp) { 3683 if (*InRangeOp == 0) 3684 return Error(ID.Loc, 3685 "inrange keyword may not appear on pointer operand"); 3686 --*InRangeOp; 3687 } 3688 3689 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3690 InBounds, InRangeOp); 3691 } else if (Opc == Instruction::Select) { 3692 if (Elts.size() != 3) 3693 return Error(ID.Loc, "expected three operands to select"); 3694 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3695 Elts[2])) 3696 return Error(ID.Loc, Reason); 3697 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3698 } else if (Opc == Instruction::ShuffleVector) { 3699 if (Elts.size() != 3) 3700 return Error(ID.Loc, "expected three operands to shufflevector"); 3701 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3702 return Error(ID.Loc, "invalid operands to shufflevector"); 3703 SmallVector<int, 16> Mask; 3704 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 3705 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 3706 } else if (Opc == Instruction::ExtractElement) { 3707 if (Elts.size() != 2) 3708 return Error(ID.Loc, "expected two operands to extractelement"); 3709 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3710 return Error(ID.Loc, "invalid extractelement operands"); 3711 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3712 } else { 3713 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3714 if (Elts.size() != 3) 3715 return Error(ID.Loc, "expected three operands to insertelement"); 3716 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3717 return Error(ID.Loc, "invalid insertelement operands"); 3718 ID.ConstantVal = 3719 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3720 } 3721 3722 ID.Kind = ValID::t_Constant; 3723 return false; 3724 } 3725 } 3726 3727 Lex.Lex(); 3728 return false; 3729 } 3730 3731 /// ParseGlobalValue - Parse a global value with the specified type. 3732 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 3733 C = nullptr; 3734 ValID ID; 3735 Value *V = nullptr; 3736 bool Parsed = ParseValID(ID) || 3737 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false); 3738 if (V && !(C = dyn_cast<Constant>(V))) 3739 return Error(ID.Loc, "global values must be constants"); 3740 return Parsed; 3741 } 3742 3743 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 3744 Type *Ty = nullptr; 3745 return ParseType(Ty) || 3746 ParseGlobalValue(Ty, V); 3747 } 3748 3749 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3750 C = nullptr; 3751 3752 LocTy KwLoc = Lex.getLoc(); 3753 if (!EatIfPresent(lltok::kw_comdat)) 3754 return false; 3755 3756 if (EatIfPresent(lltok::lparen)) { 3757 if (Lex.getKind() != lltok::ComdatVar) 3758 return TokError("expected comdat variable"); 3759 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3760 Lex.Lex(); 3761 if (ParseToken(lltok::rparen, "expected ')' after comdat var")) 3762 return true; 3763 } else { 3764 if (GlobalName.empty()) 3765 return TokError("comdat cannot be unnamed"); 3766 C = getComdat(std::string(GlobalName), KwLoc); 3767 } 3768 3769 return false; 3770 } 3771 3772 /// ParseGlobalValueVector 3773 /// ::= /*empty*/ 3774 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3775 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3776 Optional<unsigned> *InRangeOp) { 3777 // Empty list. 3778 if (Lex.getKind() == lltok::rbrace || 3779 Lex.getKind() == lltok::rsquare || 3780 Lex.getKind() == lltok::greater || 3781 Lex.getKind() == lltok::rparen) 3782 return false; 3783 3784 do { 3785 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3786 *InRangeOp = Elts.size(); 3787 3788 Constant *C; 3789 if (ParseGlobalTypeAndValue(C)) return true; 3790 Elts.push_back(C); 3791 } while (EatIfPresent(lltok::comma)); 3792 3793 return false; 3794 } 3795 3796 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) { 3797 SmallVector<Metadata *, 16> Elts; 3798 if (ParseMDNodeVector(Elts)) 3799 return true; 3800 3801 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3802 return false; 3803 } 3804 3805 /// MDNode: 3806 /// ::= !{ ... } 3807 /// ::= !7 3808 /// ::= !DILocation(...) 3809 bool LLParser::ParseMDNode(MDNode *&N) { 3810 if (Lex.getKind() == lltok::MetadataVar) 3811 return ParseSpecializedMDNode(N); 3812 3813 return ParseToken(lltok::exclaim, "expected '!' here") || 3814 ParseMDNodeTail(N); 3815 } 3816 3817 bool LLParser::ParseMDNodeTail(MDNode *&N) { 3818 // !{ ... } 3819 if (Lex.getKind() == lltok::lbrace) 3820 return ParseMDTuple(N); 3821 3822 // !42 3823 return ParseMDNodeID(N); 3824 } 3825 3826 namespace { 3827 3828 /// Structure to represent an optional metadata field. 3829 template <class FieldTy> struct MDFieldImpl { 3830 typedef MDFieldImpl ImplTy; 3831 FieldTy Val; 3832 bool Seen; 3833 3834 void assign(FieldTy Val) { 3835 Seen = true; 3836 this->Val = std::move(Val); 3837 } 3838 3839 explicit MDFieldImpl(FieldTy Default) 3840 : Val(std::move(Default)), Seen(false) {} 3841 }; 3842 3843 /// Structure to represent an optional metadata field that 3844 /// can be of either type (A or B) and encapsulates the 3845 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3846 /// to reimplement the specifics for representing each Field. 3847 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3848 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3849 FieldTypeA A; 3850 FieldTypeB B; 3851 bool Seen; 3852 3853 enum { 3854 IsInvalid = 0, 3855 IsTypeA = 1, 3856 IsTypeB = 2 3857 } WhatIs; 3858 3859 void assign(FieldTypeA A) { 3860 Seen = true; 3861 this->A = std::move(A); 3862 WhatIs = IsTypeA; 3863 } 3864 3865 void assign(FieldTypeB B) { 3866 Seen = true; 3867 this->B = std::move(B); 3868 WhatIs = IsTypeB; 3869 } 3870 3871 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3872 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3873 WhatIs(IsInvalid) {} 3874 }; 3875 3876 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3877 uint64_t Max; 3878 3879 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 3880 : ImplTy(Default), Max(Max) {} 3881 }; 3882 3883 struct LineField : public MDUnsignedField { 3884 LineField() : MDUnsignedField(0, UINT32_MAX) {} 3885 }; 3886 3887 struct ColumnField : public MDUnsignedField { 3888 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 3889 }; 3890 3891 struct DwarfTagField : public MDUnsignedField { 3892 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 3893 DwarfTagField(dwarf::Tag DefaultTag) 3894 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 3895 }; 3896 3897 struct DwarfMacinfoTypeField : public MDUnsignedField { 3898 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 3899 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 3900 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 3901 }; 3902 3903 struct DwarfAttEncodingField : public MDUnsignedField { 3904 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 3905 }; 3906 3907 struct DwarfVirtualityField : public MDUnsignedField { 3908 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 3909 }; 3910 3911 struct DwarfLangField : public MDUnsignedField { 3912 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 3913 }; 3914 3915 struct DwarfCCField : public MDUnsignedField { 3916 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 3917 }; 3918 3919 struct EmissionKindField : public MDUnsignedField { 3920 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 3921 }; 3922 3923 struct NameTableKindField : public MDUnsignedField { 3924 NameTableKindField() 3925 : MDUnsignedField( 3926 0, (unsigned) 3927 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 3928 }; 3929 3930 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 3931 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 3932 }; 3933 3934 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 3935 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 3936 }; 3937 3938 struct MDAPSIntField : public MDFieldImpl<APSInt> { 3939 MDAPSIntField() : ImplTy(APSInt()) {} 3940 }; 3941 3942 struct MDSignedField : public MDFieldImpl<int64_t> { 3943 int64_t Min; 3944 int64_t Max; 3945 3946 MDSignedField(int64_t Default = 0) 3947 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 3948 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 3949 : ImplTy(Default), Min(Min), Max(Max) {} 3950 }; 3951 3952 struct MDBoolField : public MDFieldImpl<bool> { 3953 MDBoolField(bool Default = false) : ImplTy(Default) {} 3954 }; 3955 3956 struct MDField : public MDFieldImpl<Metadata *> { 3957 bool AllowNull; 3958 3959 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 3960 }; 3961 3962 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> { 3963 MDConstant() : ImplTy(nullptr) {} 3964 }; 3965 3966 struct MDStringField : public MDFieldImpl<MDString *> { 3967 bool AllowEmpty; 3968 MDStringField(bool AllowEmpty = true) 3969 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 3970 }; 3971 3972 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 3973 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 3974 }; 3975 3976 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 3977 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 3978 }; 3979 3980 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 3981 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 3982 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 3983 3984 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 3985 bool AllowNull = true) 3986 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 3987 3988 bool isMDSignedField() const { return WhatIs == IsTypeA; } 3989 bool isMDField() const { return WhatIs == IsTypeB; } 3990 int64_t getMDSignedValue() const { 3991 assert(isMDSignedField() && "Wrong field type"); 3992 return A.Val; 3993 } 3994 Metadata *getMDFieldValue() const { 3995 assert(isMDField() && "Wrong field type"); 3996 return B.Val; 3997 } 3998 }; 3999 4000 struct MDSignedOrUnsignedField 4001 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> { 4002 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {} 4003 4004 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4005 bool isMDUnsignedField() const { return WhatIs == IsTypeB; } 4006 int64_t getMDSignedValue() const { 4007 assert(isMDSignedField() && "Wrong field type"); 4008 return A.Val; 4009 } 4010 uint64_t getMDUnsignedValue() const { 4011 assert(isMDUnsignedField() && "Wrong field type"); 4012 return B.Val; 4013 } 4014 }; 4015 4016 } // end anonymous namespace 4017 4018 namespace llvm { 4019 4020 template <> 4021 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 4022 if (Lex.getKind() != lltok::APSInt) 4023 return TokError("expected integer"); 4024 4025 Result.assign(Lex.getAPSIntVal()); 4026 Lex.Lex(); 4027 return false; 4028 } 4029 4030 template <> 4031 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4032 MDUnsignedField &Result) { 4033 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4034 return TokError("expected unsigned integer"); 4035 4036 auto &U = Lex.getAPSIntVal(); 4037 if (U.ugt(Result.Max)) 4038 return TokError("value for '" + Name + "' too large, limit is " + 4039 Twine(Result.Max)); 4040 Result.assign(U.getZExtValue()); 4041 assert(Result.Val <= Result.Max && "Expected value in range"); 4042 Lex.Lex(); 4043 return false; 4044 } 4045 4046 template <> 4047 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) { 4048 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4049 } 4050 template <> 4051 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 4052 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4053 } 4054 4055 template <> 4056 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 4057 if (Lex.getKind() == lltok::APSInt) 4058 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4059 4060 if (Lex.getKind() != lltok::DwarfTag) 4061 return TokError("expected DWARF tag"); 4062 4063 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 4064 if (Tag == dwarf::DW_TAG_invalid) 4065 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 4066 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 4067 4068 Result.assign(Tag); 4069 Lex.Lex(); 4070 return false; 4071 } 4072 4073 template <> 4074 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4075 DwarfMacinfoTypeField &Result) { 4076 if (Lex.getKind() == lltok::APSInt) 4077 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4078 4079 if (Lex.getKind() != lltok::DwarfMacinfo) 4080 return TokError("expected DWARF macinfo type"); 4081 4082 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4083 if (Macinfo == dwarf::DW_MACINFO_invalid) 4084 return TokError( 4085 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'"); 4086 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4087 4088 Result.assign(Macinfo); 4089 Lex.Lex(); 4090 return false; 4091 } 4092 4093 template <> 4094 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4095 DwarfVirtualityField &Result) { 4096 if (Lex.getKind() == lltok::APSInt) 4097 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4098 4099 if (Lex.getKind() != lltok::DwarfVirtuality) 4100 return TokError("expected DWARF virtuality code"); 4101 4102 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4103 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4104 return TokError("invalid DWARF virtuality code" + Twine(" '") + 4105 Lex.getStrVal() + "'"); 4106 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4107 Result.assign(Virtuality); 4108 Lex.Lex(); 4109 return false; 4110 } 4111 4112 template <> 4113 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4114 if (Lex.getKind() == lltok::APSInt) 4115 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4116 4117 if (Lex.getKind() != lltok::DwarfLang) 4118 return TokError("expected DWARF language"); 4119 4120 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4121 if (!Lang) 4122 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4123 "'"); 4124 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4125 Result.assign(Lang); 4126 Lex.Lex(); 4127 return false; 4128 } 4129 4130 template <> 4131 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4132 if (Lex.getKind() == lltok::APSInt) 4133 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4134 4135 if (Lex.getKind() != lltok::DwarfCC) 4136 return TokError("expected DWARF calling convention"); 4137 4138 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4139 if (!CC) 4140 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() + 4141 "'"); 4142 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4143 Result.assign(CC); 4144 Lex.Lex(); 4145 return false; 4146 } 4147 4148 template <> 4149 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) { 4150 if (Lex.getKind() == lltok::APSInt) 4151 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4152 4153 if (Lex.getKind() != lltok::EmissionKind) 4154 return TokError("expected emission kind"); 4155 4156 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4157 if (!Kind) 4158 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4159 "'"); 4160 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4161 Result.assign(*Kind); 4162 Lex.Lex(); 4163 return false; 4164 } 4165 4166 template <> 4167 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4168 NameTableKindField &Result) { 4169 if (Lex.getKind() == lltok::APSInt) 4170 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4171 4172 if (Lex.getKind() != lltok::NameTableKind) 4173 return TokError("expected nameTable kind"); 4174 4175 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4176 if (!Kind) 4177 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4178 "'"); 4179 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4180 Result.assign((unsigned)*Kind); 4181 Lex.Lex(); 4182 return false; 4183 } 4184 4185 template <> 4186 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4187 DwarfAttEncodingField &Result) { 4188 if (Lex.getKind() == lltok::APSInt) 4189 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4190 4191 if (Lex.getKind() != lltok::DwarfAttEncoding) 4192 return TokError("expected DWARF type attribute encoding"); 4193 4194 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4195 if (!Encoding) 4196 return TokError("invalid DWARF type attribute encoding" + Twine(" '") + 4197 Lex.getStrVal() + "'"); 4198 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4199 Result.assign(Encoding); 4200 Lex.Lex(); 4201 return false; 4202 } 4203 4204 /// DIFlagField 4205 /// ::= uint32 4206 /// ::= DIFlagVector 4207 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4208 template <> 4209 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4210 4211 // Parser for a single flag. 4212 auto parseFlag = [&](DINode::DIFlags &Val) { 4213 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4214 uint32_t TempVal = static_cast<uint32_t>(Val); 4215 bool Res = ParseUInt32(TempVal); 4216 Val = static_cast<DINode::DIFlags>(TempVal); 4217 return Res; 4218 } 4219 4220 if (Lex.getKind() != lltok::DIFlag) 4221 return TokError("expected debug info flag"); 4222 4223 Val = DINode::getFlag(Lex.getStrVal()); 4224 if (!Val) 4225 return TokError(Twine("invalid debug info flag flag '") + 4226 Lex.getStrVal() + "'"); 4227 Lex.Lex(); 4228 return false; 4229 }; 4230 4231 // Parse the flags and combine them together. 4232 DINode::DIFlags Combined = DINode::FlagZero; 4233 do { 4234 DINode::DIFlags Val; 4235 if (parseFlag(Val)) 4236 return true; 4237 Combined |= Val; 4238 } while (EatIfPresent(lltok::bar)); 4239 4240 Result.assign(Combined); 4241 return false; 4242 } 4243 4244 /// DISPFlagField 4245 /// ::= uint32 4246 /// ::= DISPFlagVector 4247 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4248 template <> 4249 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4250 4251 // Parser for a single flag. 4252 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4253 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4254 uint32_t TempVal = static_cast<uint32_t>(Val); 4255 bool Res = ParseUInt32(TempVal); 4256 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4257 return Res; 4258 } 4259 4260 if (Lex.getKind() != lltok::DISPFlag) 4261 return TokError("expected debug info flag"); 4262 4263 Val = DISubprogram::getFlag(Lex.getStrVal()); 4264 if (!Val) 4265 return TokError(Twine("invalid subprogram debug info flag '") + 4266 Lex.getStrVal() + "'"); 4267 Lex.Lex(); 4268 return false; 4269 }; 4270 4271 // Parse the flags and combine them together. 4272 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4273 do { 4274 DISubprogram::DISPFlags Val; 4275 if (parseFlag(Val)) 4276 return true; 4277 Combined |= Val; 4278 } while (EatIfPresent(lltok::bar)); 4279 4280 Result.assign(Combined); 4281 return false; 4282 } 4283 4284 template <> 4285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4286 MDSignedField &Result) { 4287 if (Lex.getKind() != lltok::APSInt) 4288 return TokError("expected signed integer"); 4289 4290 auto &S = Lex.getAPSIntVal(); 4291 if (S < Result.Min) 4292 return TokError("value for '" + Name + "' too small, limit is " + 4293 Twine(Result.Min)); 4294 if (S > Result.Max) 4295 return TokError("value for '" + Name + "' too large, limit is " + 4296 Twine(Result.Max)); 4297 Result.assign(S.getExtValue()); 4298 assert(Result.Val >= Result.Min && "Expected value in range"); 4299 assert(Result.Val <= Result.Max && "Expected value in range"); 4300 Lex.Lex(); 4301 return false; 4302 } 4303 4304 template <> 4305 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4306 switch (Lex.getKind()) { 4307 default: 4308 return TokError("expected 'true' or 'false'"); 4309 case lltok::kw_true: 4310 Result.assign(true); 4311 break; 4312 case lltok::kw_false: 4313 Result.assign(false); 4314 break; 4315 } 4316 Lex.Lex(); 4317 return false; 4318 } 4319 4320 template <> 4321 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4322 if (Lex.getKind() == lltok::kw_null) { 4323 if (!Result.AllowNull) 4324 return TokError("'" + Name + "' cannot be null"); 4325 Lex.Lex(); 4326 Result.assign(nullptr); 4327 return false; 4328 } 4329 4330 Metadata *MD; 4331 if (ParseMetadata(MD, nullptr)) 4332 return true; 4333 4334 Result.assign(MD); 4335 return false; 4336 } 4337 4338 template <> 4339 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4340 MDSignedOrMDField &Result) { 4341 // Try to parse a signed int. 4342 if (Lex.getKind() == lltok::APSInt) { 4343 MDSignedField Res = Result.A; 4344 if (!ParseMDField(Loc, Name, Res)) { 4345 Result.assign(Res); 4346 return false; 4347 } 4348 return true; 4349 } 4350 4351 // Otherwise, try to parse as an MDField. 4352 MDField Res = Result.B; 4353 if (!ParseMDField(Loc, Name, Res)) { 4354 Result.assign(Res); 4355 return false; 4356 } 4357 4358 return true; 4359 } 4360 4361 template <> 4362 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4363 LocTy ValueLoc = Lex.getLoc(); 4364 std::string S; 4365 if (ParseStringConstant(S)) 4366 return true; 4367 4368 if (!Result.AllowEmpty && S.empty()) 4369 return Error(ValueLoc, "'" + Name + "' cannot be empty"); 4370 4371 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4372 return false; 4373 } 4374 4375 template <> 4376 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4377 SmallVector<Metadata *, 4> MDs; 4378 if (ParseMDNodeVector(MDs)) 4379 return true; 4380 4381 Result.assign(std::move(MDs)); 4382 return false; 4383 } 4384 4385 template <> 4386 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4387 ChecksumKindField &Result) { 4388 Optional<DIFile::ChecksumKind> CSKind = 4389 DIFile::getChecksumKind(Lex.getStrVal()); 4390 4391 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4392 return TokError( 4393 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'"); 4394 4395 Result.assign(*CSKind); 4396 Lex.Lex(); 4397 return false; 4398 } 4399 4400 } // end namespace llvm 4401 4402 template <class ParserTy> 4403 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) { 4404 do { 4405 if (Lex.getKind() != lltok::LabelStr) 4406 return TokError("expected field label here"); 4407 4408 if (parseField()) 4409 return true; 4410 } while (EatIfPresent(lltok::comma)); 4411 4412 return false; 4413 } 4414 4415 template <class ParserTy> 4416 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) { 4417 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4418 Lex.Lex(); 4419 4420 if (ParseToken(lltok::lparen, "expected '(' here")) 4421 return true; 4422 if (Lex.getKind() != lltok::rparen) 4423 if (ParseMDFieldsImplBody(parseField)) 4424 return true; 4425 4426 ClosingLoc = Lex.getLoc(); 4427 return ParseToken(lltok::rparen, "expected ')' here"); 4428 } 4429 4430 template <class FieldTy> 4431 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) { 4432 if (Result.Seen) 4433 return TokError("field '" + Name + "' cannot be specified more than once"); 4434 4435 LocTy Loc = Lex.getLoc(); 4436 Lex.Lex(); 4437 return ParseMDField(Loc, Name, Result); 4438 } 4439 4440 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4441 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4442 4443 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4444 if (Lex.getStrVal() == #CLASS) \ 4445 return Parse##CLASS(N, IsDistinct); 4446 #include "llvm/IR/Metadata.def" 4447 4448 return TokError("expected metadata type"); 4449 } 4450 4451 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4452 #define NOP_FIELD(NAME, TYPE, INIT) 4453 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4454 if (!NAME.Seen) \ 4455 return Error(ClosingLoc, "missing required field '" #NAME "'"); 4456 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4457 if (Lex.getStrVal() == #NAME) \ 4458 return ParseMDField(#NAME, NAME); 4459 #define PARSE_MD_FIELDS() \ 4460 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4461 do { \ 4462 LocTy ClosingLoc; \ 4463 if (ParseMDFieldsImpl([&]() -> bool { \ 4464 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4465 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \ 4466 }, ClosingLoc)) \ 4467 return true; \ 4468 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4469 } while (false) 4470 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4471 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4472 4473 /// ParseDILocationFields: 4474 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4475 /// isImplicitCode: true) 4476 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) { 4477 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4478 OPTIONAL(line, LineField, ); \ 4479 OPTIONAL(column, ColumnField, ); \ 4480 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4481 OPTIONAL(inlinedAt, MDField, ); \ 4482 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4483 PARSE_MD_FIELDS(); 4484 #undef VISIT_MD_FIELDS 4485 4486 Result = 4487 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4488 inlinedAt.Val, isImplicitCode.Val)); 4489 return false; 4490 } 4491 4492 /// ParseGenericDINode: 4493 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4494 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) { 4495 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4496 REQUIRED(tag, DwarfTagField, ); \ 4497 OPTIONAL(header, MDStringField, ); \ 4498 OPTIONAL(operands, MDFieldList, ); 4499 PARSE_MD_FIELDS(); 4500 #undef VISIT_MD_FIELDS 4501 4502 Result = GET_OR_DISTINCT(GenericDINode, 4503 (Context, tag.Val, header.Val, operands.Val)); 4504 return false; 4505 } 4506 4507 /// ParseDISubrange: 4508 /// ::= !DISubrange(count: 30, lowerBound: 2) 4509 /// ::= !DISubrange(count: !node, lowerBound: 2) 4510 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 4511 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) { 4512 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4513 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4514 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4515 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4516 OPTIONAL(stride, MDSignedOrMDField, ); 4517 PARSE_MD_FIELDS(); 4518 #undef VISIT_MD_FIELDS 4519 4520 Metadata *Count = nullptr; 4521 Metadata *LowerBound = nullptr; 4522 Metadata *UpperBound = nullptr; 4523 Metadata *Stride = nullptr; 4524 if (count.isMDSignedField()) 4525 Count = ConstantAsMetadata::get(ConstantInt::getSigned( 4526 Type::getInt64Ty(Context), count.getMDSignedValue())); 4527 else if (count.isMDField()) 4528 Count = count.getMDFieldValue(); 4529 4530 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4531 if (Bound.isMDSignedField()) 4532 return ConstantAsMetadata::get(ConstantInt::getSigned( 4533 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 4534 if (Bound.isMDField()) 4535 return Bound.getMDFieldValue(); 4536 return nullptr; 4537 }; 4538 4539 LowerBound = convToMetadata(lowerBound); 4540 UpperBound = convToMetadata(upperBound); 4541 Stride = convToMetadata(stride); 4542 4543 Result = GET_OR_DISTINCT(DISubrange, 4544 (Context, Count, LowerBound, UpperBound, Stride)); 4545 4546 return false; 4547 } 4548 4549 /// ParseDIEnumerator: 4550 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4551 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4552 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4553 REQUIRED(name, MDStringField, ); \ 4554 REQUIRED(value, MDAPSIntField, ); \ 4555 OPTIONAL(isUnsigned, MDBoolField, (false)); 4556 PARSE_MD_FIELDS(); 4557 #undef VISIT_MD_FIELDS 4558 4559 if (isUnsigned.Val && value.Val.isNegative()) 4560 return TokError("unsigned enumerator with negative value"); 4561 4562 APSInt Value(value.Val); 4563 // Add a leading zero so that unsigned values with the msb set are not 4564 // mistaken for negative values when used for signed enumerators. 4565 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 4566 Value = Value.zext(Value.getBitWidth() + 1); 4567 4568 Result = 4569 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4570 4571 return false; 4572 } 4573 4574 /// ParseDIBasicType: 4575 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4576 /// encoding: DW_ATE_encoding, flags: 0) 4577 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) { 4578 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4579 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4580 OPTIONAL(name, MDStringField, ); \ 4581 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4582 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4583 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4584 OPTIONAL(flags, DIFlagField, ); 4585 PARSE_MD_FIELDS(); 4586 #undef VISIT_MD_FIELDS 4587 4588 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4589 align.Val, encoding.Val, flags.Val)); 4590 return false; 4591 } 4592 4593 /// ParseDIDerivedType: 4594 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4595 /// line: 7, scope: !1, baseType: !2, size: 32, 4596 /// align: 32, offset: 0, flags: 0, extraData: !3, 4597 /// dwarfAddressSpace: 3) 4598 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4599 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4600 REQUIRED(tag, DwarfTagField, ); \ 4601 OPTIONAL(name, MDStringField, ); \ 4602 OPTIONAL(file, MDField, ); \ 4603 OPTIONAL(line, LineField, ); \ 4604 OPTIONAL(scope, MDField, ); \ 4605 REQUIRED(baseType, MDField, ); \ 4606 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4607 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4608 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4609 OPTIONAL(flags, DIFlagField, ); \ 4610 OPTIONAL(extraData, MDField, ); \ 4611 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 4612 PARSE_MD_FIELDS(); 4613 #undef VISIT_MD_FIELDS 4614 4615 Optional<unsigned> DWARFAddressSpace; 4616 if (dwarfAddressSpace.Val != UINT32_MAX) 4617 DWARFAddressSpace = dwarfAddressSpace.Val; 4618 4619 Result = GET_OR_DISTINCT(DIDerivedType, 4620 (Context, tag.Val, name.Val, file.Val, line.Val, 4621 scope.Val, baseType.Val, size.Val, align.Val, 4622 offset.Val, DWARFAddressSpace, flags.Val, 4623 extraData.Val)); 4624 return false; 4625 } 4626 4627 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) { 4628 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4629 REQUIRED(tag, DwarfTagField, ); \ 4630 OPTIONAL(name, MDStringField, ); \ 4631 OPTIONAL(file, MDField, ); \ 4632 OPTIONAL(line, LineField, ); \ 4633 OPTIONAL(scope, MDField, ); \ 4634 OPTIONAL(baseType, MDField, ); \ 4635 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4636 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4637 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4638 OPTIONAL(flags, DIFlagField, ); \ 4639 OPTIONAL(elements, MDField, ); \ 4640 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4641 OPTIONAL(vtableHolder, MDField, ); \ 4642 OPTIONAL(templateParams, MDField, ); \ 4643 OPTIONAL(identifier, MDStringField, ); \ 4644 OPTIONAL(discriminator, MDField, ); \ 4645 OPTIONAL(dataLocation, MDField, ); 4646 PARSE_MD_FIELDS(); 4647 #undef VISIT_MD_FIELDS 4648 4649 // If this has an identifier try to build an ODR type. 4650 if (identifier.Val) 4651 if (auto *CT = DICompositeType::buildODRType( 4652 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4653 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4654 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 4655 discriminator.Val, dataLocation.Val)) { 4656 Result = CT; 4657 return false; 4658 } 4659 4660 // Create a new node, and save it in the context if it belongs in the type 4661 // map. 4662 Result = GET_OR_DISTINCT( 4663 DICompositeType, 4664 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4665 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4666 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4667 discriminator.Val, dataLocation.Val)); 4668 return false; 4669 } 4670 4671 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4672 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4673 OPTIONAL(flags, DIFlagField, ); \ 4674 OPTIONAL(cc, DwarfCCField, ); \ 4675 REQUIRED(types, MDField, ); 4676 PARSE_MD_FIELDS(); 4677 #undef VISIT_MD_FIELDS 4678 4679 Result = GET_OR_DISTINCT(DISubroutineType, 4680 (Context, flags.Val, cc.Val, types.Val)); 4681 return false; 4682 } 4683 4684 /// ParseDIFileType: 4685 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4686 /// checksumkind: CSK_MD5, 4687 /// checksum: "000102030405060708090a0b0c0d0e0f", 4688 /// source: "source file contents") 4689 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) { 4690 // The default constructed value for checksumkind is required, but will never 4691 // be used, as the parser checks if the field was actually Seen before using 4692 // the Val. 4693 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4694 REQUIRED(filename, MDStringField, ); \ 4695 REQUIRED(directory, MDStringField, ); \ 4696 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4697 OPTIONAL(checksum, MDStringField, ); \ 4698 OPTIONAL(source, MDStringField, ); 4699 PARSE_MD_FIELDS(); 4700 #undef VISIT_MD_FIELDS 4701 4702 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4703 if (checksumkind.Seen && checksum.Seen) 4704 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4705 else if (checksumkind.Seen || checksum.Seen) 4706 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4707 4708 Optional<MDString *> OptSource; 4709 if (source.Seen) 4710 OptSource = source.Val; 4711 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4712 OptChecksum, OptSource)); 4713 return false; 4714 } 4715 4716 /// ParseDICompileUnit: 4717 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4718 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4719 /// splitDebugFilename: "abc.debug", 4720 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4721 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4722 /// sysroot: "/", sdk: "MacOSX.sdk") 4723 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4724 if (!IsDistinct) 4725 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4726 4727 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4728 REQUIRED(language, DwarfLangField, ); \ 4729 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4730 OPTIONAL(producer, MDStringField, ); \ 4731 OPTIONAL(isOptimized, MDBoolField, ); \ 4732 OPTIONAL(flags, MDStringField, ); \ 4733 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4734 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4735 OPTIONAL(emissionKind, EmissionKindField, ); \ 4736 OPTIONAL(enums, MDField, ); \ 4737 OPTIONAL(retainedTypes, MDField, ); \ 4738 OPTIONAL(globals, MDField, ); \ 4739 OPTIONAL(imports, MDField, ); \ 4740 OPTIONAL(macros, MDField, ); \ 4741 OPTIONAL(dwoId, MDUnsignedField, ); \ 4742 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4743 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4744 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4745 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 4746 OPTIONAL(sysroot, MDStringField, ); \ 4747 OPTIONAL(sdk, MDStringField, ); 4748 PARSE_MD_FIELDS(); 4749 #undef VISIT_MD_FIELDS 4750 4751 Result = DICompileUnit::getDistinct( 4752 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4753 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4754 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4755 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4756 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 4757 return false; 4758 } 4759 4760 /// ParseDISubprogram: 4761 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4762 /// file: !1, line: 7, type: !2, isLocal: false, 4763 /// isDefinition: true, scopeLine: 8, containingType: !3, 4764 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4765 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4766 /// spFlags: 10, isOptimized: false, templateParams: !4, 4767 /// declaration: !5, retainedNodes: !6, thrownTypes: !7) 4768 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) { 4769 auto Loc = Lex.getLoc(); 4770 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4771 OPTIONAL(scope, MDField, ); \ 4772 OPTIONAL(name, MDStringField, ); \ 4773 OPTIONAL(linkageName, MDStringField, ); \ 4774 OPTIONAL(file, MDField, ); \ 4775 OPTIONAL(line, LineField, ); \ 4776 OPTIONAL(type, MDField, ); \ 4777 OPTIONAL(isLocal, MDBoolField, ); \ 4778 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4779 OPTIONAL(scopeLine, LineField, ); \ 4780 OPTIONAL(containingType, MDField, ); \ 4781 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4782 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4783 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4784 OPTIONAL(flags, DIFlagField, ); \ 4785 OPTIONAL(spFlags, DISPFlagField, ); \ 4786 OPTIONAL(isOptimized, MDBoolField, ); \ 4787 OPTIONAL(unit, MDField, ); \ 4788 OPTIONAL(templateParams, MDField, ); \ 4789 OPTIONAL(declaration, MDField, ); \ 4790 OPTIONAL(retainedNodes, MDField, ); \ 4791 OPTIONAL(thrownTypes, MDField, ); 4792 PARSE_MD_FIELDS(); 4793 #undef VISIT_MD_FIELDS 4794 4795 // An explicit spFlags field takes precedence over individual fields in 4796 // older IR versions. 4797 DISubprogram::DISPFlags SPFlags = 4798 spFlags.Seen ? spFlags.Val 4799 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4800 isOptimized.Val, virtuality.Val); 4801 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4802 return Lex.Error( 4803 Loc, 4804 "missing 'distinct', required for !DISubprogram that is a Definition"); 4805 Result = GET_OR_DISTINCT( 4806 DISubprogram, 4807 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4808 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 4809 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 4810 declaration.Val, retainedNodes.Val, thrownTypes.Val)); 4811 return false; 4812 } 4813 4814 /// ParseDILexicalBlock: 4815 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 4816 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 4817 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4818 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4819 OPTIONAL(file, MDField, ); \ 4820 OPTIONAL(line, LineField, ); \ 4821 OPTIONAL(column, ColumnField, ); 4822 PARSE_MD_FIELDS(); 4823 #undef VISIT_MD_FIELDS 4824 4825 Result = GET_OR_DISTINCT( 4826 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 4827 return false; 4828 } 4829 4830 /// ParseDILexicalBlockFile: 4831 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 4832 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 4833 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4834 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4835 OPTIONAL(file, MDField, ); \ 4836 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4837 PARSE_MD_FIELDS(); 4838 #undef VISIT_MD_FIELDS 4839 4840 Result = GET_OR_DISTINCT(DILexicalBlockFile, 4841 (Context, scope.Val, file.Val, discriminator.Val)); 4842 return false; 4843 } 4844 4845 /// ParseDICommonBlock: 4846 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 4847 bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) { 4848 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4849 REQUIRED(scope, MDField, ); \ 4850 OPTIONAL(declaration, MDField, ); \ 4851 OPTIONAL(name, MDStringField, ); \ 4852 OPTIONAL(file, MDField, ); \ 4853 OPTIONAL(line, LineField, ); 4854 PARSE_MD_FIELDS(); 4855 #undef VISIT_MD_FIELDS 4856 4857 Result = GET_OR_DISTINCT(DICommonBlock, 4858 (Context, scope.Val, declaration.Val, name.Val, 4859 file.Val, line.Val)); 4860 return false; 4861 } 4862 4863 /// ParseDINamespace: 4864 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 4865 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) { 4866 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4867 REQUIRED(scope, MDField, ); \ 4868 OPTIONAL(name, MDStringField, ); \ 4869 OPTIONAL(exportSymbols, MDBoolField, ); 4870 PARSE_MD_FIELDS(); 4871 #undef VISIT_MD_FIELDS 4872 4873 Result = GET_OR_DISTINCT(DINamespace, 4874 (Context, scope.Val, name.Val, exportSymbols.Val)); 4875 return false; 4876 } 4877 4878 /// ParseDIMacro: 4879 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue") 4880 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) { 4881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4882 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4883 OPTIONAL(line, LineField, ); \ 4884 REQUIRED(name, MDStringField, ); \ 4885 OPTIONAL(value, MDStringField, ); 4886 PARSE_MD_FIELDS(); 4887 #undef VISIT_MD_FIELDS 4888 4889 Result = GET_OR_DISTINCT(DIMacro, 4890 (Context, type.Val, line.Val, name.Val, value.Val)); 4891 return false; 4892 } 4893 4894 /// ParseDIMacroFile: 4895 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 4896 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) { 4897 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4898 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4899 OPTIONAL(line, LineField, ); \ 4900 REQUIRED(file, MDField, ); \ 4901 OPTIONAL(nodes, MDField, ); 4902 PARSE_MD_FIELDS(); 4903 #undef VISIT_MD_FIELDS 4904 4905 Result = GET_OR_DISTINCT(DIMacroFile, 4906 (Context, type.Val, line.Val, file.Val, nodes.Val)); 4907 return false; 4908 } 4909 4910 /// ParseDIModule: 4911 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 4912 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 4913 /// file: !1, line: 4) 4914 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) { 4915 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4916 REQUIRED(scope, MDField, ); \ 4917 REQUIRED(name, MDStringField, ); \ 4918 OPTIONAL(configMacros, MDStringField, ); \ 4919 OPTIONAL(includePath, MDStringField, ); \ 4920 OPTIONAL(apinotes, MDStringField, ); \ 4921 OPTIONAL(file, MDField, ); \ 4922 OPTIONAL(line, LineField, ); 4923 PARSE_MD_FIELDS(); 4924 #undef VISIT_MD_FIELDS 4925 4926 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 4927 configMacros.Val, includePath.Val, 4928 apinotes.Val, line.Val)); 4929 return false; 4930 } 4931 4932 /// ParseDITemplateTypeParameter: 4933 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 4934 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 4935 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4936 OPTIONAL(name, MDStringField, ); \ 4937 REQUIRED(type, MDField, ); \ 4938 OPTIONAL(defaulted, MDBoolField, ); 4939 PARSE_MD_FIELDS(); 4940 #undef VISIT_MD_FIELDS 4941 4942 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 4943 (Context, name.Val, type.Val, defaulted.Val)); 4944 return false; 4945 } 4946 4947 /// ParseDITemplateValueParameter: 4948 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 4949 /// name: "V", type: !1, defaulted: false, 4950 /// value: i32 7) 4951 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 4952 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4953 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4954 OPTIONAL(name, MDStringField, ); \ 4955 OPTIONAL(type, MDField, ); \ 4956 OPTIONAL(defaulted, MDBoolField, ); \ 4957 REQUIRED(value, MDField, ); 4958 4959 PARSE_MD_FIELDS(); 4960 #undef VISIT_MD_FIELDS 4961 4962 Result = GET_OR_DISTINCT( 4963 DITemplateValueParameter, 4964 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 4965 return false; 4966 } 4967 4968 /// ParseDIGlobalVariable: 4969 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 4970 /// file: !1, line: 7, type: !2, isLocal: false, 4971 /// isDefinition: true, templateParams: !3, 4972 /// declaration: !4, align: 8) 4973 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 4974 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4975 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 4976 OPTIONAL(scope, MDField, ); \ 4977 OPTIONAL(linkageName, MDStringField, ); \ 4978 OPTIONAL(file, MDField, ); \ 4979 OPTIONAL(line, LineField, ); \ 4980 OPTIONAL(type, MDField, ); \ 4981 OPTIONAL(isLocal, MDBoolField, ); \ 4982 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4983 OPTIONAL(templateParams, MDField, ); \ 4984 OPTIONAL(declaration, MDField, ); \ 4985 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4986 PARSE_MD_FIELDS(); 4987 #undef VISIT_MD_FIELDS 4988 4989 Result = 4990 GET_OR_DISTINCT(DIGlobalVariable, 4991 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 4992 line.Val, type.Val, isLocal.Val, isDefinition.Val, 4993 declaration.Val, templateParams.Val, align.Val)); 4994 return false; 4995 } 4996 4997 /// ParseDILocalVariable: 4998 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 4999 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5000 /// align: 8) 5001 /// ::= !DILocalVariable(scope: !0, name: "foo", 5002 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5003 /// align: 8) 5004 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) { 5005 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5006 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5007 OPTIONAL(name, MDStringField, ); \ 5008 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 5009 OPTIONAL(file, MDField, ); \ 5010 OPTIONAL(line, LineField, ); \ 5011 OPTIONAL(type, MDField, ); \ 5012 OPTIONAL(flags, DIFlagField, ); \ 5013 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 5014 PARSE_MD_FIELDS(); 5015 #undef VISIT_MD_FIELDS 5016 5017 Result = GET_OR_DISTINCT(DILocalVariable, 5018 (Context, scope.Val, name.Val, file.Val, line.Val, 5019 type.Val, arg.Val, flags.Val, align.Val)); 5020 return false; 5021 } 5022 5023 /// ParseDILabel: 5024 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 5025 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) { 5026 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5027 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5028 REQUIRED(name, MDStringField, ); \ 5029 REQUIRED(file, MDField, ); \ 5030 REQUIRED(line, LineField, ); 5031 PARSE_MD_FIELDS(); 5032 #undef VISIT_MD_FIELDS 5033 5034 Result = GET_OR_DISTINCT(DILabel, 5035 (Context, scope.Val, name.Val, file.Val, line.Val)); 5036 return false; 5037 } 5038 5039 /// ParseDIExpression: 5040 /// ::= !DIExpression(0, 7, -1) 5041 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) { 5042 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5043 Lex.Lex(); 5044 5045 if (ParseToken(lltok::lparen, "expected '(' here")) 5046 return true; 5047 5048 SmallVector<uint64_t, 8> Elements; 5049 if (Lex.getKind() != lltok::rparen) 5050 do { 5051 if (Lex.getKind() == lltok::DwarfOp) { 5052 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5053 Lex.Lex(); 5054 Elements.push_back(Op); 5055 continue; 5056 } 5057 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5058 } 5059 5060 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5061 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5062 Lex.Lex(); 5063 Elements.push_back(Op); 5064 continue; 5065 } 5066 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'"); 5067 } 5068 5069 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5070 return TokError("expected unsigned integer"); 5071 5072 auto &U = Lex.getAPSIntVal(); 5073 if (U.ugt(UINT64_MAX)) 5074 return TokError("element too large, limit is " + Twine(UINT64_MAX)); 5075 Elements.push_back(U.getZExtValue()); 5076 Lex.Lex(); 5077 } while (EatIfPresent(lltok::comma)); 5078 5079 if (ParseToken(lltok::rparen, "expected ')' here")) 5080 return true; 5081 5082 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5083 return false; 5084 } 5085 5086 /// ParseDIGlobalVariableExpression: 5087 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5088 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result, 5089 bool IsDistinct) { 5090 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5091 REQUIRED(var, MDField, ); \ 5092 REQUIRED(expr, MDField, ); 5093 PARSE_MD_FIELDS(); 5094 #undef VISIT_MD_FIELDS 5095 5096 Result = 5097 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5098 return false; 5099 } 5100 5101 /// ParseDIObjCProperty: 5102 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5103 /// getter: "getFoo", attributes: 7, type: !2) 5104 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5105 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5106 OPTIONAL(name, MDStringField, ); \ 5107 OPTIONAL(file, MDField, ); \ 5108 OPTIONAL(line, LineField, ); \ 5109 OPTIONAL(setter, MDStringField, ); \ 5110 OPTIONAL(getter, MDStringField, ); \ 5111 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5112 OPTIONAL(type, MDField, ); 5113 PARSE_MD_FIELDS(); 5114 #undef VISIT_MD_FIELDS 5115 5116 Result = GET_OR_DISTINCT(DIObjCProperty, 5117 (Context, name.Val, file.Val, line.Val, setter.Val, 5118 getter.Val, attributes.Val, type.Val)); 5119 return false; 5120 } 5121 5122 /// ParseDIImportedEntity: 5123 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5124 /// line: 7, name: "foo") 5125 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5126 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5127 REQUIRED(tag, DwarfTagField, ); \ 5128 REQUIRED(scope, MDField, ); \ 5129 OPTIONAL(entity, MDField, ); \ 5130 OPTIONAL(file, MDField, ); \ 5131 OPTIONAL(line, LineField, ); \ 5132 OPTIONAL(name, MDStringField, ); 5133 PARSE_MD_FIELDS(); 5134 #undef VISIT_MD_FIELDS 5135 5136 Result = GET_OR_DISTINCT( 5137 DIImportedEntity, 5138 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val)); 5139 return false; 5140 } 5141 5142 #undef PARSE_MD_FIELD 5143 #undef NOP_FIELD 5144 #undef REQUIRE_FIELD 5145 #undef DECLARE_FIELD 5146 5147 /// ParseMetadataAsValue 5148 /// ::= metadata i32 %local 5149 /// ::= metadata i32 @global 5150 /// ::= metadata i32 7 5151 /// ::= metadata !0 5152 /// ::= metadata !{...} 5153 /// ::= metadata !"string" 5154 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5155 // Note: the type 'metadata' has already been parsed. 5156 Metadata *MD; 5157 if (ParseMetadata(MD, &PFS)) 5158 return true; 5159 5160 V = MetadataAsValue::get(Context, MD); 5161 return false; 5162 } 5163 5164 /// ParseValueAsMetadata 5165 /// ::= i32 %local 5166 /// ::= i32 @global 5167 /// ::= i32 7 5168 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5169 PerFunctionState *PFS) { 5170 Type *Ty; 5171 LocTy Loc; 5172 if (ParseType(Ty, TypeMsg, Loc)) 5173 return true; 5174 if (Ty->isMetadataTy()) 5175 return Error(Loc, "invalid metadata-value-metadata roundtrip"); 5176 5177 Value *V; 5178 if (ParseValue(Ty, V, PFS)) 5179 return true; 5180 5181 MD = ValueAsMetadata::get(V); 5182 return false; 5183 } 5184 5185 /// ParseMetadata 5186 /// ::= i32 %local 5187 /// ::= i32 @global 5188 /// ::= i32 7 5189 /// ::= !42 5190 /// ::= !{...} 5191 /// ::= !"string" 5192 /// ::= !DILocation(...) 5193 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5194 if (Lex.getKind() == lltok::MetadataVar) { 5195 MDNode *N; 5196 if (ParseSpecializedMDNode(N)) 5197 return true; 5198 MD = N; 5199 return false; 5200 } 5201 5202 // ValueAsMetadata: 5203 // <type> <value> 5204 if (Lex.getKind() != lltok::exclaim) 5205 return ParseValueAsMetadata(MD, "expected metadata operand", PFS); 5206 5207 // '!'. 5208 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5209 Lex.Lex(); 5210 5211 // MDString: 5212 // ::= '!' STRINGCONSTANT 5213 if (Lex.getKind() == lltok::StringConstant) { 5214 MDString *S; 5215 if (ParseMDString(S)) 5216 return true; 5217 MD = S; 5218 return false; 5219 } 5220 5221 // MDNode: 5222 // !{ ... } 5223 // !7 5224 MDNode *N; 5225 if (ParseMDNodeTail(N)) 5226 return true; 5227 MD = N; 5228 return false; 5229 } 5230 5231 //===----------------------------------------------------------------------===// 5232 // Function Parsing. 5233 //===----------------------------------------------------------------------===// 5234 5235 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5236 PerFunctionState *PFS, bool IsCall) { 5237 if (Ty->isFunctionTy()) 5238 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 5239 5240 switch (ID.Kind) { 5241 case ValID::t_LocalID: 5242 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 5243 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5244 return V == nullptr; 5245 case ValID::t_LocalName: 5246 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 5247 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall); 5248 return V == nullptr; 5249 case ValID::t_InlineAsm: { 5250 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5251 return Error(ID.Loc, "invalid type for inline asm constraint string"); 5252 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, 5253 (ID.UIntVal >> 1) & 1, 5254 (InlineAsm::AsmDialect(ID.UIntVal >> 2))); 5255 return false; 5256 } 5257 case ValID::t_GlobalName: 5258 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall); 5259 return V == nullptr; 5260 case ValID::t_GlobalID: 5261 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5262 return V == nullptr; 5263 case ValID::t_APSInt: 5264 if (!Ty->isIntegerTy()) 5265 return Error(ID.Loc, "integer constant must have integer type"); 5266 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5267 V = ConstantInt::get(Context, ID.APSIntVal); 5268 return false; 5269 case ValID::t_APFloat: 5270 if (!Ty->isFloatingPointTy() || 5271 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5272 return Error(ID.Loc, "floating point constant invalid for type"); 5273 5274 // The lexer has no type info, so builds all half, bfloat, float, and double 5275 // FP constants as double. Fix this here. Long double does not need this. 5276 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5277 bool Ignored; 5278 if (Ty->isHalfTy()) 5279 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5280 &Ignored); 5281 else if (Ty->isBFloatTy()) 5282 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 5283 &Ignored); 5284 else if (Ty->isFloatTy()) 5285 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5286 &Ignored); 5287 } 5288 V = ConstantFP::get(Context, ID.APFloatVal); 5289 5290 if (V->getType() != Ty) 5291 return Error(ID.Loc, "floating point constant does not have type '" + 5292 getTypeString(Ty) + "'"); 5293 5294 return false; 5295 case ValID::t_Null: 5296 if (!Ty->isPointerTy()) 5297 return Error(ID.Loc, "null must be a pointer type"); 5298 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5299 return false; 5300 case ValID::t_Undef: 5301 // FIXME: LabelTy should not be a first-class type. 5302 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5303 return Error(ID.Loc, "invalid type for undef constant"); 5304 V = UndefValue::get(Ty); 5305 return false; 5306 case ValID::t_EmptyArray: 5307 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5308 return Error(ID.Loc, "invalid empty array initializer"); 5309 V = UndefValue::get(Ty); 5310 return false; 5311 case ValID::t_Zero: 5312 // FIXME: LabelTy should not be a first-class type. 5313 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5314 return Error(ID.Loc, "invalid type for null constant"); 5315 V = Constant::getNullValue(Ty); 5316 return false; 5317 case ValID::t_None: 5318 if (!Ty->isTokenTy()) 5319 return Error(ID.Loc, "invalid type for none constant"); 5320 V = Constant::getNullValue(Ty); 5321 return false; 5322 case ValID::t_Constant: 5323 if (ID.ConstantVal->getType() != Ty) 5324 return Error(ID.Loc, "constant expression type mismatch"); 5325 5326 V = ID.ConstantVal; 5327 return false; 5328 case ValID::t_ConstantStruct: 5329 case ValID::t_PackedConstantStruct: 5330 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5331 if (ST->getNumElements() != ID.UIntVal) 5332 return Error(ID.Loc, 5333 "initializer with struct type has wrong # elements"); 5334 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5335 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 5336 5337 // Verify that the elements are compatible with the structtype. 5338 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5339 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5340 return Error(ID.Loc, "element " + Twine(i) + 5341 " of struct initializer doesn't match struct element type"); 5342 5343 V = ConstantStruct::get( 5344 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5345 } else 5346 return Error(ID.Loc, "constant expression type mismatch"); 5347 return false; 5348 } 5349 llvm_unreachable("Invalid ValID"); 5350 } 5351 5352 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5353 C = nullptr; 5354 ValID ID; 5355 auto Loc = Lex.getLoc(); 5356 if (ParseValID(ID, /*PFS=*/nullptr)) 5357 return true; 5358 switch (ID.Kind) { 5359 case ValID::t_APSInt: 5360 case ValID::t_APFloat: 5361 case ValID::t_Undef: 5362 case ValID::t_Constant: 5363 case ValID::t_ConstantStruct: 5364 case ValID::t_PackedConstantStruct: { 5365 Value *V; 5366 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false)) 5367 return true; 5368 assert(isa<Constant>(V) && "Expected a constant value"); 5369 C = cast<Constant>(V); 5370 return false; 5371 } 5372 case ValID::t_Null: 5373 C = Constant::getNullValue(Ty); 5374 return false; 5375 default: 5376 return Error(Loc, "expected a constant value"); 5377 } 5378 } 5379 5380 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5381 V = nullptr; 5382 ValID ID; 5383 return ParseValID(ID, PFS) || 5384 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false); 5385 } 5386 5387 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5388 Type *Ty = nullptr; 5389 return ParseType(Ty) || 5390 ParseValue(Ty, V, PFS); 5391 } 5392 5393 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5394 PerFunctionState &PFS) { 5395 Value *V; 5396 Loc = Lex.getLoc(); 5397 if (ParseTypeAndValue(V, PFS)) return true; 5398 if (!isa<BasicBlock>(V)) 5399 return Error(Loc, "expected a basic block"); 5400 BB = cast<BasicBlock>(V); 5401 return false; 5402 } 5403 5404 /// FunctionHeader 5405 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5406 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5407 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5408 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5409 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 5410 // Parse the linkage. 5411 LocTy LinkageLoc = Lex.getLoc(); 5412 unsigned Linkage; 5413 unsigned Visibility; 5414 unsigned DLLStorageClass; 5415 bool DSOLocal; 5416 AttrBuilder RetAttrs; 5417 unsigned CC; 5418 bool HasLinkage; 5419 Type *RetType = nullptr; 5420 LocTy RetTypeLoc = Lex.getLoc(); 5421 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5422 DSOLocal) || 5423 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 5424 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 5425 return true; 5426 5427 // Verify that the linkage is ok. 5428 switch ((GlobalValue::LinkageTypes)Linkage) { 5429 case GlobalValue::ExternalLinkage: 5430 break; // always ok. 5431 case GlobalValue::ExternalWeakLinkage: 5432 if (isDefine) 5433 return Error(LinkageLoc, "invalid linkage for function definition"); 5434 break; 5435 case GlobalValue::PrivateLinkage: 5436 case GlobalValue::InternalLinkage: 5437 case GlobalValue::AvailableExternallyLinkage: 5438 case GlobalValue::LinkOnceAnyLinkage: 5439 case GlobalValue::LinkOnceODRLinkage: 5440 case GlobalValue::WeakAnyLinkage: 5441 case GlobalValue::WeakODRLinkage: 5442 if (!isDefine) 5443 return Error(LinkageLoc, "invalid linkage for function declaration"); 5444 break; 5445 case GlobalValue::AppendingLinkage: 5446 case GlobalValue::CommonLinkage: 5447 return Error(LinkageLoc, "invalid function linkage type"); 5448 } 5449 5450 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5451 return Error(LinkageLoc, 5452 "symbol with local linkage must have default visibility"); 5453 5454 if (!FunctionType::isValidReturnType(RetType)) 5455 return Error(RetTypeLoc, "invalid function return type"); 5456 5457 LocTy NameLoc = Lex.getLoc(); 5458 5459 std::string FunctionName; 5460 if (Lex.getKind() == lltok::GlobalVar) { 5461 FunctionName = Lex.getStrVal(); 5462 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5463 unsigned NameID = Lex.getUIntVal(); 5464 5465 if (NameID != NumberedVals.size()) 5466 return TokError("function expected to be numbered '%" + 5467 Twine(NumberedVals.size()) + "'"); 5468 } else { 5469 return TokError("expected function name"); 5470 } 5471 5472 Lex.Lex(); 5473 5474 if (Lex.getKind() != lltok::lparen) 5475 return TokError("expected '(' in function argument list"); 5476 5477 SmallVector<ArgInfo, 8> ArgList; 5478 bool isVarArg; 5479 AttrBuilder FuncAttrs; 5480 std::vector<unsigned> FwdRefAttrGrps; 5481 LocTy BuiltinLoc; 5482 std::string Section; 5483 std::string Partition; 5484 MaybeAlign Alignment; 5485 std::string GC; 5486 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5487 unsigned AddrSpace = 0; 5488 Constant *Prefix = nullptr; 5489 Constant *Prologue = nullptr; 5490 Constant *PersonalityFn = nullptr; 5491 Comdat *C; 5492 5493 if (ParseArgumentList(ArgList, isVarArg) || 5494 ParseOptionalUnnamedAddr(UnnamedAddr) || 5495 ParseOptionalProgramAddrSpace(AddrSpace) || 5496 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5497 BuiltinLoc) || 5498 (EatIfPresent(lltok::kw_section) && 5499 ParseStringConstant(Section)) || 5500 (EatIfPresent(lltok::kw_partition) && 5501 ParseStringConstant(Partition)) || 5502 parseOptionalComdat(FunctionName, C) || 5503 ParseOptionalAlignment(Alignment) || 5504 (EatIfPresent(lltok::kw_gc) && 5505 ParseStringConstant(GC)) || 5506 (EatIfPresent(lltok::kw_prefix) && 5507 ParseGlobalTypeAndValue(Prefix)) || 5508 (EatIfPresent(lltok::kw_prologue) && 5509 ParseGlobalTypeAndValue(Prologue)) || 5510 (EatIfPresent(lltok::kw_personality) && 5511 ParseGlobalTypeAndValue(PersonalityFn))) 5512 return true; 5513 5514 if (FuncAttrs.contains(Attribute::Builtin)) 5515 return Error(BuiltinLoc, "'builtin' attribute not valid on function"); 5516 5517 // If the alignment was parsed as an attribute, move to the alignment field. 5518 if (FuncAttrs.hasAlignmentAttr()) { 5519 Alignment = FuncAttrs.getAlignment(); 5520 FuncAttrs.removeAttribute(Attribute::Alignment); 5521 } 5522 5523 // Okay, if we got here, the function is syntactically valid. Convert types 5524 // and do semantic checks. 5525 std::vector<Type*> ParamTypeList; 5526 SmallVector<AttributeSet, 8> Attrs; 5527 5528 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5529 ParamTypeList.push_back(ArgList[i].Ty); 5530 Attrs.push_back(ArgList[i].Attrs); 5531 } 5532 5533 AttributeList PAL = 5534 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5535 AttributeSet::get(Context, RetAttrs), Attrs); 5536 5537 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 5538 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 5539 5540 FunctionType *FT = 5541 FunctionType::get(RetType, ParamTypeList, isVarArg); 5542 PointerType *PFT = PointerType::get(FT, AddrSpace); 5543 5544 Fn = nullptr; 5545 if (!FunctionName.empty()) { 5546 // If this was a definition of a forward reference, remove the definition 5547 // from the forward reference table and fill in the forward ref. 5548 auto FRVI = ForwardRefVals.find(FunctionName); 5549 if (FRVI != ForwardRefVals.end()) { 5550 Fn = M->getFunction(FunctionName); 5551 if (!Fn) 5552 return Error(FRVI->second.second, "invalid forward reference to " 5553 "function as global value!"); 5554 if (Fn->getType() != PFT) 5555 return Error(FRVI->second.second, "invalid forward reference to " 5556 "function '" + FunctionName + "' with wrong type: " 5557 "expected '" + getTypeString(PFT) + "' but was '" + 5558 getTypeString(Fn->getType()) + "'"); 5559 ForwardRefVals.erase(FRVI); 5560 } else if ((Fn = M->getFunction(FunctionName))) { 5561 // Reject redefinitions. 5562 return Error(NameLoc, "invalid redefinition of function '" + 5563 FunctionName + "'"); 5564 } else if (M->getNamedValue(FunctionName)) { 5565 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5566 } 5567 5568 } else { 5569 // If this is a definition of a forward referenced function, make sure the 5570 // types agree. 5571 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5572 if (I != ForwardRefValIDs.end()) { 5573 Fn = cast<Function>(I->second.first); 5574 if (Fn->getType() != PFT) 5575 return Error(NameLoc, "type of definition and forward reference of '@" + 5576 Twine(NumberedVals.size()) + "' disagree: " 5577 "expected '" + getTypeString(PFT) + "' but was '" + 5578 getTypeString(Fn->getType()) + "'"); 5579 ForwardRefValIDs.erase(I); 5580 } 5581 } 5582 5583 if (!Fn) 5584 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5585 FunctionName, M); 5586 else // Move the forward-reference to the correct spot in the module. 5587 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 5588 5589 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5590 5591 if (FunctionName.empty()) 5592 NumberedVals.push_back(Fn); 5593 5594 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5595 maybeSetDSOLocal(DSOLocal, *Fn); 5596 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5597 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5598 Fn->setCallingConv(CC); 5599 Fn->setAttributes(PAL); 5600 Fn->setUnnamedAddr(UnnamedAddr); 5601 Fn->setAlignment(MaybeAlign(Alignment)); 5602 Fn->setSection(Section); 5603 Fn->setPartition(Partition); 5604 Fn->setComdat(C); 5605 Fn->setPersonalityFn(PersonalityFn); 5606 if (!GC.empty()) Fn->setGC(GC); 5607 Fn->setPrefixData(Prefix); 5608 Fn->setPrologueData(Prologue); 5609 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5610 5611 // Add all of the arguments we parsed to the function. 5612 Function::arg_iterator ArgIt = Fn->arg_begin(); 5613 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5614 // If the argument has a name, insert it into the argument symbol table. 5615 if (ArgList[i].Name.empty()) continue; 5616 5617 // Set the name, if it conflicted, it will be auto-renamed. 5618 ArgIt->setName(ArgList[i].Name); 5619 5620 if (ArgIt->getName() != ArgList[i].Name) 5621 return Error(ArgList[i].Loc, "redefinition of argument '%" + 5622 ArgList[i].Name + "'"); 5623 } 5624 5625 if (isDefine) 5626 return false; 5627 5628 // Check the declaration has no block address forward references. 5629 ValID ID; 5630 if (FunctionName.empty()) { 5631 ID.Kind = ValID::t_GlobalID; 5632 ID.UIntVal = NumberedVals.size() - 1; 5633 } else { 5634 ID.Kind = ValID::t_GlobalName; 5635 ID.StrVal = FunctionName; 5636 } 5637 auto Blocks = ForwardRefBlockAddresses.find(ID); 5638 if (Blocks != ForwardRefBlockAddresses.end()) 5639 return Error(Blocks->first.Loc, 5640 "cannot take blockaddress inside a declaration"); 5641 return false; 5642 } 5643 5644 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5645 ValID ID; 5646 if (FunctionNumber == -1) { 5647 ID.Kind = ValID::t_GlobalName; 5648 ID.StrVal = std::string(F.getName()); 5649 } else { 5650 ID.Kind = ValID::t_GlobalID; 5651 ID.UIntVal = FunctionNumber; 5652 } 5653 5654 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5655 if (Blocks == P.ForwardRefBlockAddresses.end()) 5656 return false; 5657 5658 for (const auto &I : Blocks->second) { 5659 const ValID &BBID = I.first; 5660 GlobalValue *GV = I.second; 5661 5662 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5663 "Expected local id or name"); 5664 BasicBlock *BB; 5665 if (BBID.Kind == ValID::t_LocalName) 5666 BB = GetBB(BBID.StrVal, BBID.Loc); 5667 else 5668 BB = GetBB(BBID.UIntVal, BBID.Loc); 5669 if (!BB) 5670 return P.Error(BBID.Loc, "referenced value is not a basic block"); 5671 5672 GV->replaceAllUsesWith(BlockAddress::get(&F, BB)); 5673 GV->eraseFromParent(); 5674 } 5675 5676 P.ForwardRefBlockAddresses.erase(Blocks); 5677 return false; 5678 } 5679 5680 /// ParseFunctionBody 5681 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5682 bool LLParser::ParseFunctionBody(Function &Fn) { 5683 if (Lex.getKind() != lltok::lbrace) 5684 return TokError("expected '{' in function body"); 5685 Lex.Lex(); // eat the {. 5686 5687 int FunctionNumber = -1; 5688 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5689 5690 PerFunctionState PFS(*this, Fn, FunctionNumber); 5691 5692 // Resolve block addresses and allow basic blocks to be forward-declared 5693 // within this function. 5694 if (PFS.resolveForwardRefBlockAddresses()) 5695 return true; 5696 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5697 5698 // We need at least one basic block. 5699 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5700 return TokError("function body requires at least one basic block"); 5701 5702 while (Lex.getKind() != lltok::rbrace && 5703 Lex.getKind() != lltok::kw_uselistorder) 5704 if (ParseBasicBlock(PFS)) return true; 5705 5706 while (Lex.getKind() != lltok::rbrace) 5707 if (ParseUseListOrder(&PFS)) 5708 return true; 5709 5710 // Eat the }. 5711 Lex.Lex(); 5712 5713 // Verify function is ok. 5714 return PFS.FinishFunction(); 5715 } 5716 5717 /// ParseBasicBlock 5718 /// ::= (LabelStr|LabelID)? Instruction* 5719 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 5720 // If this basic block starts out with a name, remember it. 5721 std::string Name; 5722 int NameID = -1; 5723 LocTy NameLoc = Lex.getLoc(); 5724 if (Lex.getKind() == lltok::LabelStr) { 5725 Name = Lex.getStrVal(); 5726 Lex.Lex(); 5727 } else if (Lex.getKind() == lltok::LabelID) { 5728 NameID = Lex.getUIntVal(); 5729 Lex.Lex(); 5730 } 5731 5732 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc); 5733 if (!BB) 5734 return true; 5735 5736 std::string NameStr; 5737 5738 // Parse the instructions in this block until we get a terminator. 5739 Instruction *Inst; 5740 do { 5741 // This instruction may have three possibilities for a name: a) none 5742 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5743 LocTy NameLoc = Lex.getLoc(); 5744 int NameID = -1; 5745 NameStr = ""; 5746 5747 if (Lex.getKind() == lltok::LocalVarID) { 5748 NameID = Lex.getUIntVal(); 5749 Lex.Lex(); 5750 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 5751 return true; 5752 } else if (Lex.getKind() == lltok::LocalVar) { 5753 NameStr = Lex.getStrVal(); 5754 Lex.Lex(); 5755 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 5756 return true; 5757 } 5758 5759 switch (ParseInstruction(Inst, BB, PFS)) { 5760 default: llvm_unreachable("Unknown ParseInstruction result!"); 5761 case InstError: return true; 5762 case InstNormal: 5763 BB->getInstList().push_back(Inst); 5764 5765 // With a normal result, we check to see if the instruction is followed by 5766 // a comma and metadata. 5767 if (EatIfPresent(lltok::comma)) 5768 if (ParseInstructionMetadata(*Inst)) 5769 return true; 5770 break; 5771 case InstExtraComma: 5772 BB->getInstList().push_back(Inst); 5773 5774 // If the instruction parser ate an extra comma at the end of it, it 5775 // *must* be followed by metadata. 5776 if (ParseInstructionMetadata(*Inst)) 5777 return true; 5778 break; 5779 } 5780 5781 // Set the name on the instruction. 5782 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 5783 } while (!Inst->isTerminator()); 5784 5785 return false; 5786 } 5787 5788 //===----------------------------------------------------------------------===// 5789 // Instruction Parsing. 5790 //===----------------------------------------------------------------------===// 5791 5792 /// ParseInstruction - Parse one of the many different instructions. 5793 /// 5794 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 5795 PerFunctionState &PFS) { 5796 lltok::Kind Token = Lex.getKind(); 5797 if (Token == lltok::Eof) 5798 return TokError("found end of file when expecting more instructions"); 5799 LocTy Loc = Lex.getLoc(); 5800 unsigned KeywordVal = Lex.getUIntVal(); 5801 Lex.Lex(); // Eat the keyword. 5802 5803 switch (Token) { 5804 default: return Error(Loc, "expected instruction opcode"); 5805 // Terminator Instructions. 5806 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5807 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 5808 case lltok::kw_br: return ParseBr(Inst, PFS); 5809 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 5810 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS); 5811 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 5812 case lltok::kw_resume: return ParseResume(Inst, PFS); 5813 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS); 5814 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS); 5815 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS); 5816 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS); 5817 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS); 5818 case lltok::kw_callbr: return ParseCallBr(Inst, PFS); 5819 // Unary Operators. 5820 case lltok::kw_fneg: { 5821 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5822 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true); 5823 if (Res != 0) 5824 return Res; 5825 if (FMF.any()) 5826 Inst->setFastMathFlags(FMF); 5827 return false; 5828 } 5829 // Binary Operators. 5830 case lltok::kw_add: 5831 case lltok::kw_sub: 5832 case lltok::kw_mul: 5833 case lltok::kw_shl: { 5834 bool NUW = EatIfPresent(lltok::kw_nuw); 5835 bool NSW = EatIfPresent(lltok::kw_nsw); 5836 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5837 5838 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true; 5839 5840 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5841 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5842 return false; 5843 } 5844 case lltok::kw_fadd: 5845 case lltok::kw_fsub: 5846 case lltok::kw_fmul: 5847 case lltok::kw_fdiv: 5848 case lltok::kw_frem: { 5849 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5850 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true); 5851 if (Res != 0) 5852 return Res; 5853 if (FMF.any()) 5854 Inst->setFastMathFlags(FMF); 5855 return 0; 5856 } 5857 5858 case lltok::kw_sdiv: 5859 case lltok::kw_udiv: 5860 case lltok::kw_lshr: 5861 case lltok::kw_ashr: { 5862 bool Exact = EatIfPresent(lltok::kw_exact); 5863 5864 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true; 5865 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5866 return false; 5867 } 5868 5869 case lltok::kw_urem: 5870 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 5871 /*IsFP*/false); 5872 case lltok::kw_and: 5873 case lltok::kw_or: 5874 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 5875 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal); 5876 case lltok::kw_fcmp: { 5877 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5878 int Res = ParseCompare(Inst, PFS, KeywordVal); 5879 if (Res != 0) 5880 return Res; 5881 if (FMF.any()) 5882 Inst->setFastMathFlags(FMF); 5883 return 0; 5884 } 5885 5886 // Casts. 5887 case lltok::kw_trunc: 5888 case lltok::kw_zext: 5889 case lltok::kw_sext: 5890 case lltok::kw_fptrunc: 5891 case lltok::kw_fpext: 5892 case lltok::kw_bitcast: 5893 case lltok::kw_addrspacecast: 5894 case lltok::kw_uitofp: 5895 case lltok::kw_sitofp: 5896 case lltok::kw_fptoui: 5897 case lltok::kw_fptosi: 5898 case lltok::kw_inttoptr: 5899 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 5900 // Other. 5901 case lltok::kw_select: { 5902 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5903 int Res = ParseSelect(Inst, PFS); 5904 if (Res != 0) 5905 return Res; 5906 if (FMF.any()) { 5907 if (!isa<FPMathOperator>(Inst)) 5908 return Error(Loc, "fast-math-flags specified for select without " 5909 "floating-point scalar or vector return type"); 5910 Inst->setFastMathFlags(FMF); 5911 } 5912 return 0; 5913 } 5914 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 5915 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 5916 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 5917 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 5918 case lltok::kw_phi: { 5919 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5920 int Res = ParsePHI(Inst, PFS); 5921 if (Res != 0) 5922 return Res; 5923 if (FMF.any()) { 5924 if (!isa<FPMathOperator>(Inst)) 5925 return Error(Loc, "fast-math-flags specified for phi without " 5926 "floating-point scalar or vector return type"); 5927 Inst->setFastMathFlags(FMF); 5928 } 5929 return 0; 5930 } 5931 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS); 5932 case lltok::kw_freeze: return ParseFreeze(Inst, PFS); 5933 // Call. 5934 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None); 5935 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail); 5936 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail); 5937 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail); 5938 // Memory. 5939 case lltok::kw_alloca: return ParseAlloc(Inst, PFS); 5940 case lltok::kw_load: return ParseLoad(Inst, PFS); 5941 case lltok::kw_store: return ParseStore(Inst, PFS); 5942 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS); 5943 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS); 5944 case lltok::kw_fence: return ParseFence(Inst, PFS); 5945 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 5946 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 5947 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 5948 } 5949 } 5950 5951 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 5952 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 5953 if (Opc == Instruction::FCmp) { 5954 switch (Lex.getKind()) { 5955 default: return TokError("expected fcmp predicate (e.g. 'oeq')"); 5956 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 5957 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 5958 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 5959 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 5960 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 5961 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 5962 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 5963 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 5964 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 5965 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 5966 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 5967 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 5968 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 5969 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 5970 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 5971 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 5972 } 5973 } else { 5974 switch (Lex.getKind()) { 5975 default: return TokError("expected icmp predicate (e.g. 'eq')"); 5976 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 5977 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 5978 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 5979 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 5980 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 5981 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 5982 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 5983 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 5984 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 5985 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 5986 } 5987 } 5988 Lex.Lex(); 5989 return false; 5990 } 5991 5992 //===----------------------------------------------------------------------===// 5993 // Terminator Instructions. 5994 //===----------------------------------------------------------------------===// 5995 5996 /// ParseRet - Parse a return instruction. 5997 /// ::= 'ret' void (',' !dbg, !1)* 5998 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 5999 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 6000 PerFunctionState &PFS) { 6001 SMLoc TypeLoc = Lex.getLoc(); 6002 Type *Ty = nullptr; 6003 if (ParseType(Ty, true /*void allowed*/)) return true; 6004 6005 Type *ResType = PFS.getFunction().getReturnType(); 6006 6007 if (Ty->isVoidTy()) { 6008 if (!ResType->isVoidTy()) 6009 return Error(TypeLoc, "value doesn't match function result type '" + 6010 getTypeString(ResType) + "'"); 6011 6012 Inst = ReturnInst::Create(Context); 6013 return false; 6014 } 6015 6016 Value *RV; 6017 if (ParseValue(Ty, RV, PFS)) return true; 6018 6019 if (ResType != RV->getType()) 6020 return Error(TypeLoc, "value doesn't match function result type '" + 6021 getTypeString(ResType) + "'"); 6022 6023 Inst = ReturnInst::Create(Context, RV); 6024 return false; 6025 } 6026 6027 /// ParseBr 6028 /// ::= 'br' TypeAndValue 6029 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6030 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 6031 LocTy Loc, Loc2; 6032 Value *Op0; 6033 BasicBlock *Op1, *Op2; 6034 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 6035 6036 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6037 Inst = BranchInst::Create(BB); 6038 return false; 6039 } 6040 6041 if (Op0->getType() != Type::getInt1Ty(Context)) 6042 return Error(Loc, "branch condition must have 'i1' type"); 6043 6044 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 6045 ParseTypeAndBasicBlock(Op1, Loc, PFS) || 6046 ParseToken(lltok::comma, "expected ',' after true destination") || 6047 ParseTypeAndBasicBlock(Op2, Loc2, PFS)) 6048 return true; 6049 6050 Inst = BranchInst::Create(Op1, Op2, Op0); 6051 return false; 6052 } 6053 6054 /// ParseSwitch 6055 /// Instruction 6056 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6057 /// JumpTable 6058 /// ::= (TypeAndValue ',' TypeAndValue)* 6059 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6060 LocTy CondLoc, BBLoc; 6061 Value *Cond; 6062 BasicBlock *DefaultBB; 6063 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 6064 ParseToken(lltok::comma, "expected ',' after switch condition") || 6065 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6066 ParseToken(lltok::lsquare, "expected '[' with switch table")) 6067 return true; 6068 6069 if (!Cond->getType()->isIntegerTy()) 6070 return Error(CondLoc, "switch condition must have integer type"); 6071 6072 // Parse the jump table pairs. 6073 SmallPtrSet<Value*, 32> SeenCases; 6074 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6075 while (Lex.getKind() != lltok::rsquare) { 6076 Value *Constant; 6077 BasicBlock *DestBB; 6078 6079 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 6080 ParseToken(lltok::comma, "expected ',' after case value") || 6081 ParseTypeAndBasicBlock(DestBB, PFS)) 6082 return true; 6083 6084 if (!SeenCases.insert(Constant).second) 6085 return Error(CondLoc, "duplicate case value in switch"); 6086 if (!isa<ConstantInt>(Constant)) 6087 return Error(CondLoc, "case value is not a constant integer"); 6088 6089 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6090 } 6091 6092 Lex.Lex(); // Eat the ']'. 6093 6094 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6095 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6096 SI->addCase(Table[i].first, Table[i].second); 6097 Inst = SI; 6098 return false; 6099 } 6100 6101 /// ParseIndirectBr 6102 /// Instruction 6103 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6104 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6105 LocTy AddrLoc; 6106 Value *Address; 6107 if (ParseTypeAndValue(Address, AddrLoc, PFS) || 6108 ParseToken(lltok::comma, "expected ',' after indirectbr address") || 6109 ParseToken(lltok::lsquare, "expected '[' with indirectbr")) 6110 return true; 6111 6112 if (!Address->getType()->isPointerTy()) 6113 return Error(AddrLoc, "indirectbr address must have pointer type"); 6114 6115 // Parse the destination list. 6116 SmallVector<BasicBlock*, 16> DestList; 6117 6118 if (Lex.getKind() != lltok::rsquare) { 6119 BasicBlock *DestBB; 6120 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6121 return true; 6122 DestList.push_back(DestBB); 6123 6124 while (EatIfPresent(lltok::comma)) { 6125 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6126 return true; 6127 DestList.push_back(DestBB); 6128 } 6129 } 6130 6131 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 6132 return true; 6133 6134 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6135 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6136 IBI->addDestination(DestList[i]); 6137 Inst = IBI; 6138 return false; 6139 } 6140 6141 /// ParseInvoke 6142 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6143 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6144 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6145 LocTy CallLoc = Lex.getLoc(); 6146 AttrBuilder RetAttrs, FnAttrs; 6147 std::vector<unsigned> FwdRefAttrGrps; 6148 LocTy NoBuiltinLoc; 6149 unsigned CC; 6150 unsigned InvokeAddrSpace; 6151 Type *RetType = nullptr; 6152 LocTy RetTypeLoc; 6153 ValID CalleeID; 6154 SmallVector<ParamInfo, 16> ArgList; 6155 SmallVector<OperandBundleDef, 2> BundleList; 6156 6157 BasicBlock *NormalBB, *UnwindBB; 6158 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6159 ParseOptionalProgramAddrSpace(InvokeAddrSpace) || 6160 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6161 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) || 6162 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6163 NoBuiltinLoc) || 6164 ParseOptionalOperandBundles(BundleList, PFS) || 6165 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 6166 ParseTypeAndBasicBlock(NormalBB, PFS) || 6167 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6168 ParseTypeAndBasicBlock(UnwindBB, PFS)) 6169 return true; 6170 6171 // If RetType is a non-function pointer type, then this is the short syntax 6172 // for the call, which means that RetType is just the return type. Infer the 6173 // rest of the function argument types from the arguments that are present. 6174 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6175 if (!Ty) { 6176 // Pull out the types of all of the arguments... 6177 std::vector<Type*> ParamTypes; 6178 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6179 ParamTypes.push_back(ArgList[i].V->getType()); 6180 6181 if (!FunctionType::isValidReturnType(RetType)) 6182 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6183 6184 Ty = FunctionType::get(RetType, ParamTypes, false); 6185 } 6186 6187 CalleeID.FTy = Ty; 6188 6189 // Look up the callee. 6190 Value *Callee; 6191 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6192 Callee, &PFS, /*IsCall=*/true)) 6193 return true; 6194 6195 // Set up the Attribute for the function. 6196 SmallVector<Value *, 8> Args; 6197 SmallVector<AttributeSet, 8> ArgAttrs; 6198 6199 // Loop through FunctionType's arguments and ensure they are specified 6200 // correctly. Also, gather any parameter attributes. 6201 FunctionType::param_iterator I = Ty->param_begin(); 6202 FunctionType::param_iterator E = Ty->param_end(); 6203 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6204 Type *ExpectedTy = nullptr; 6205 if (I != E) { 6206 ExpectedTy = *I++; 6207 } else if (!Ty->isVarArg()) { 6208 return Error(ArgList[i].Loc, "too many arguments specified"); 6209 } 6210 6211 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6212 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6213 getTypeString(ExpectedTy) + "'"); 6214 Args.push_back(ArgList[i].V); 6215 ArgAttrs.push_back(ArgList[i].Attrs); 6216 } 6217 6218 if (I != E) 6219 return Error(CallLoc, "not enough parameters specified for call"); 6220 6221 if (FnAttrs.hasAlignmentAttr()) 6222 return Error(CallLoc, "invoke instructions may not have an alignment"); 6223 6224 // Finish off the Attribute and check them 6225 AttributeList PAL = 6226 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6227 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6228 6229 InvokeInst *II = 6230 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6231 II->setCallingConv(CC); 6232 II->setAttributes(PAL); 6233 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6234 Inst = II; 6235 return false; 6236 } 6237 6238 /// ParseResume 6239 /// ::= 'resume' TypeAndValue 6240 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) { 6241 Value *Exn; LocTy ExnLoc; 6242 if (ParseTypeAndValue(Exn, ExnLoc, PFS)) 6243 return true; 6244 6245 ResumeInst *RI = ResumeInst::Create(Exn); 6246 Inst = RI; 6247 return false; 6248 } 6249 6250 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args, 6251 PerFunctionState &PFS) { 6252 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6253 return true; 6254 6255 while (Lex.getKind() != lltok::rsquare) { 6256 // If this isn't the first argument, we need a comma. 6257 if (!Args.empty() && 6258 ParseToken(lltok::comma, "expected ',' in argument list")) 6259 return true; 6260 6261 // Parse the argument. 6262 LocTy ArgLoc; 6263 Type *ArgTy = nullptr; 6264 if (ParseType(ArgTy, ArgLoc)) 6265 return true; 6266 6267 Value *V; 6268 if (ArgTy->isMetadataTy()) { 6269 if (ParseMetadataAsValue(V, PFS)) 6270 return true; 6271 } else { 6272 if (ParseValue(ArgTy, V, PFS)) 6273 return true; 6274 } 6275 Args.push_back(V); 6276 } 6277 6278 Lex.Lex(); // Lex the ']'. 6279 return false; 6280 } 6281 6282 /// ParseCleanupRet 6283 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6284 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6285 Value *CleanupPad = nullptr; 6286 6287 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6288 return true; 6289 6290 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6291 return true; 6292 6293 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6294 return true; 6295 6296 BasicBlock *UnwindBB = nullptr; 6297 if (Lex.getKind() == lltok::kw_to) { 6298 Lex.Lex(); 6299 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6300 return true; 6301 } else { 6302 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) { 6303 return true; 6304 } 6305 } 6306 6307 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6308 return false; 6309 } 6310 6311 /// ParseCatchRet 6312 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6313 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6314 Value *CatchPad = nullptr; 6315 6316 if (ParseToken(lltok::kw_from, "expected 'from' after catchret")) 6317 return true; 6318 6319 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6320 return true; 6321 6322 BasicBlock *BB; 6323 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") || 6324 ParseTypeAndBasicBlock(BB, PFS)) 6325 return true; 6326 6327 Inst = CatchReturnInst::Create(CatchPad, BB); 6328 return false; 6329 } 6330 6331 /// ParseCatchSwitch 6332 /// ::= 'catchswitch' within Parent 6333 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6334 Value *ParentPad; 6335 6336 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6337 return true; 6338 6339 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6340 Lex.getKind() != lltok::LocalVarID) 6341 return TokError("expected scope value for catchswitch"); 6342 6343 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6344 return true; 6345 6346 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6347 return true; 6348 6349 SmallVector<BasicBlock *, 32> Table; 6350 do { 6351 BasicBlock *DestBB; 6352 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6353 return true; 6354 Table.push_back(DestBB); 6355 } while (EatIfPresent(lltok::comma)); 6356 6357 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6358 return true; 6359 6360 if (ParseToken(lltok::kw_unwind, 6361 "expected 'unwind' after catchswitch scope")) 6362 return true; 6363 6364 BasicBlock *UnwindBB = nullptr; 6365 if (EatIfPresent(lltok::kw_to)) { 6366 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6367 return true; 6368 } else { 6369 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) 6370 return true; 6371 } 6372 6373 auto *CatchSwitch = 6374 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6375 for (BasicBlock *DestBB : Table) 6376 CatchSwitch->addHandler(DestBB); 6377 Inst = CatchSwitch; 6378 return false; 6379 } 6380 6381 /// ParseCatchPad 6382 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6383 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6384 Value *CatchSwitch = nullptr; 6385 6386 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad")) 6387 return true; 6388 6389 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6390 return TokError("expected scope value for catchpad"); 6391 6392 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6393 return true; 6394 6395 SmallVector<Value *, 8> Args; 6396 if (ParseExceptionArgs(Args, PFS)) 6397 return true; 6398 6399 Inst = CatchPadInst::Create(CatchSwitch, Args); 6400 return false; 6401 } 6402 6403 /// ParseCleanupPad 6404 /// ::= 'cleanuppad' within Parent ParamList 6405 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6406 Value *ParentPad = nullptr; 6407 6408 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6409 return true; 6410 6411 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6412 Lex.getKind() != lltok::LocalVarID) 6413 return TokError("expected scope value for cleanuppad"); 6414 6415 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6416 return true; 6417 6418 SmallVector<Value *, 8> Args; 6419 if (ParseExceptionArgs(Args, PFS)) 6420 return true; 6421 6422 Inst = CleanupPadInst::Create(ParentPad, Args); 6423 return false; 6424 } 6425 6426 //===----------------------------------------------------------------------===// 6427 // Unary Operators. 6428 //===----------------------------------------------------------------------===// 6429 6430 /// ParseUnaryOp 6431 /// ::= UnaryOp TypeAndValue ',' Value 6432 /// 6433 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6434 /// operand is allowed. 6435 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6436 unsigned Opc, bool IsFP) { 6437 LocTy Loc; Value *LHS; 6438 if (ParseTypeAndValue(LHS, Loc, PFS)) 6439 return true; 6440 6441 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6442 : LHS->getType()->isIntOrIntVectorTy(); 6443 6444 if (!Valid) 6445 return Error(Loc, "invalid operand type for instruction"); 6446 6447 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6448 return false; 6449 } 6450 6451 /// ParseCallBr 6452 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6453 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6454 /// '[' LabelList ']' 6455 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6456 LocTy CallLoc = Lex.getLoc(); 6457 AttrBuilder RetAttrs, FnAttrs; 6458 std::vector<unsigned> FwdRefAttrGrps; 6459 LocTy NoBuiltinLoc; 6460 unsigned CC; 6461 Type *RetType = nullptr; 6462 LocTy RetTypeLoc; 6463 ValID CalleeID; 6464 SmallVector<ParamInfo, 16> ArgList; 6465 SmallVector<OperandBundleDef, 2> BundleList; 6466 6467 BasicBlock *DefaultDest; 6468 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6469 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6470 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) || 6471 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6472 NoBuiltinLoc) || 6473 ParseOptionalOperandBundles(BundleList, PFS) || 6474 ParseToken(lltok::kw_to, "expected 'to' in callbr") || 6475 ParseTypeAndBasicBlock(DefaultDest, PFS) || 6476 ParseToken(lltok::lsquare, "expected '[' in callbr")) 6477 return true; 6478 6479 // Parse the destination list. 6480 SmallVector<BasicBlock *, 16> IndirectDests; 6481 6482 if (Lex.getKind() != lltok::rsquare) { 6483 BasicBlock *DestBB; 6484 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6485 return true; 6486 IndirectDests.push_back(DestBB); 6487 6488 while (EatIfPresent(lltok::comma)) { 6489 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6490 return true; 6491 IndirectDests.push_back(DestBB); 6492 } 6493 } 6494 6495 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 6496 return true; 6497 6498 // If RetType is a non-function pointer type, then this is the short syntax 6499 // for the call, which means that RetType is just the return type. Infer the 6500 // rest of the function argument types from the arguments that are present. 6501 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6502 if (!Ty) { 6503 // Pull out the types of all of the arguments... 6504 std::vector<Type *> ParamTypes; 6505 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6506 ParamTypes.push_back(ArgList[i].V->getType()); 6507 6508 if (!FunctionType::isValidReturnType(RetType)) 6509 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6510 6511 Ty = FunctionType::get(RetType, ParamTypes, false); 6512 } 6513 6514 CalleeID.FTy = Ty; 6515 6516 // Look up the callee. 6517 Value *Callee; 6518 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS, 6519 /*IsCall=*/true)) 6520 return true; 6521 6522 // Set up the Attribute for the function. 6523 SmallVector<Value *, 8> Args; 6524 SmallVector<AttributeSet, 8> ArgAttrs; 6525 6526 // Loop through FunctionType's arguments and ensure they are specified 6527 // correctly. Also, gather any parameter attributes. 6528 FunctionType::param_iterator I = Ty->param_begin(); 6529 FunctionType::param_iterator E = Ty->param_end(); 6530 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6531 Type *ExpectedTy = nullptr; 6532 if (I != E) { 6533 ExpectedTy = *I++; 6534 } else if (!Ty->isVarArg()) { 6535 return Error(ArgList[i].Loc, "too many arguments specified"); 6536 } 6537 6538 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6539 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6540 getTypeString(ExpectedTy) + "'"); 6541 Args.push_back(ArgList[i].V); 6542 ArgAttrs.push_back(ArgList[i].Attrs); 6543 } 6544 6545 if (I != E) 6546 return Error(CallLoc, "not enough parameters specified for call"); 6547 6548 if (FnAttrs.hasAlignmentAttr()) 6549 return Error(CallLoc, "callbr instructions may not have an alignment"); 6550 6551 // Finish off the Attribute and check them 6552 AttributeList PAL = 6553 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6554 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6555 6556 CallBrInst *CBI = 6557 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6558 BundleList); 6559 CBI->setCallingConv(CC); 6560 CBI->setAttributes(PAL); 6561 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6562 Inst = CBI; 6563 return false; 6564 } 6565 6566 //===----------------------------------------------------------------------===// 6567 // Binary Operators. 6568 //===----------------------------------------------------------------------===// 6569 6570 /// ParseArithmetic 6571 /// ::= ArithmeticOps TypeAndValue ',' Value 6572 /// 6573 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6574 /// operand is allowed. 6575 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6576 unsigned Opc, bool IsFP) { 6577 LocTy Loc; Value *LHS, *RHS; 6578 if (ParseTypeAndValue(LHS, Loc, PFS) || 6579 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 6580 ParseValue(LHS->getType(), RHS, PFS)) 6581 return true; 6582 6583 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6584 : LHS->getType()->isIntOrIntVectorTy(); 6585 6586 if (!Valid) 6587 return Error(Loc, "invalid operand type for instruction"); 6588 6589 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6590 return false; 6591 } 6592 6593 /// ParseLogical 6594 /// ::= ArithmeticOps TypeAndValue ',' Value { 6595 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 6596 unsigned Opc) { 6597 LocTy Loc; Value *LHS, *RHS; 6598 if (ParseTypeAndValue(LHS, Loc, PFS) || 6599 ParseToken(lltok::comma, "expected ',' in logical operation") || 6600 ParseValue(LHS->getType(), RHS, PFS)) 6601 return true; 6602 6603 if (!LHS->getType()->isIntOrIntVectorTy()) 6604 return Error(Loc,"instruction requires integer or integer vector operands"); 6605 6606 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6607 return false; 6608 } 6609 6610 /// ParseCompare 6611 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6612 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6613 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 6614 unsigned Opc) { 6615 // Parse the integer/fp comparison predicate. 6616 LocTy Loc; 6617 unsigned Pred; 6618 Value *LHS, *RHS; 6619 if (ParseCmpPredicate(Pred, Opc) || 6620 ParseTypeAndValue(LHS, Loc, PFS) || 6621 ParseToken(lltok::comma, "expected ',' after compare value") || 6622 ParseValue(LHS->getType(), RHS, PFS)) 6623 return true; 6624 6625 if (Opc == Instruction::FCmp) { 6626 if (!LHS->getType()->isFPOrFPVectorTy()) 6627 return Error(Loc, "fcmp requires floating point operands"); 6628 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6629 } else { 6630 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6631 if (!LHS->getType()->isIntOrIntVectorTy() && 6632 !LHS->getType()->isPtrOrPtrVectorTy()) 6633 return Error(Loc, "icmp requires integer operands"); 6634 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6635 } 6636 return false; 6637 } 6638 6639 //===----------------------------------------------------------------------===// 6640 // Other Instructions. 6641 //===----------------------------------------------------------------------===// 6642 6643 6644 /// ParseCast 6645 /// ::= CastOpc TypeAndValue 'to' Type 6646 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 6647 unsigned Opc) { 6648 LocTy Loc; 6649 Value *Op; 6650 Type *DestTy = nullptr; 6651 if (ParseTypeAndValue(Op, Loc, PFS) || 6652 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 6653 ParseType(DestTy)) 6654 return true; 6655 6656 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6657 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6658 return Error(Loc, "invalid cast opcode for cast from '" + 6659 getTypeString(Op->getType()) + "' to '" + 6660 getTypeString(DestTy) + "'"); 6661 } 6662 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6663 return false; 6664 } 6665 6666 /// ParseSelect 6667 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6668 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6669 LocTy Loc; 6670 Value *Op0, *Op1, *Op2; 6671 if (ParseTypeAndValue(Op0, Loc, PFS) || 6672 ParseToken(lltok::comma, "expected ',' after select condition") || 6673 ParseTypeAndValue(Op1, PFS) || 6674 ParseToken(lltok::comma, "expected ',' after select value") || 6675 ParseTypeAndValue(Op2, PFS)) 6676 return true; 6677 6678 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6679 return Error(Loc, Reason); 6680 6681 Inst = SelectInst::Create(Op0, Op1, Op2); 6682 return false; 6683 } 6684 6685 /// ParseVA_Arg 6686 /// ::= 'va_arg' TypeAndValue ',' Type 6687 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 6688 Value *Op; 6689 Type *EltTy = nullptr; 6690 LocTy TypeLoc; 6691 if (ParseTypeAndValue(Op, PFS) || 6692 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 6693 ParseType(EltTy, TypeLoc)) 6694 return true; 6695 6696 if (!EltTy->isFirstClassType()) 6697 return Error(TypeLoc, "va_arg requires operand with first class type"); 6698 6699 Inst = new VAArgInst(Op, EltTy); 6700 return false; 6701 } 6702 6703 /// ParseExtractElement 6704 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6705 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6706 LocTy Loc; 6707 Value *Op0, *Op1; 6708 if (ParseTypeAndValue(Op0, Loc, PFS) || 6709 ParseToken(lltok::comma, "expected ',' after extract value") || 6710 ParseTypeAndValue(Op1, PFS)) 6711 return true; 6712 6713 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6714 return Error(Loc, "invalid extractelement operands"); 6715 6716 Inst = ExtractElementInst::Create(Op0, Op1); 6717 return false; 6718 } 6719 6720 /// ParseInsertElement 6721 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6722 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6723 LocTy Loc; 6724 Value *Op0, *Op1, *Op2; 6725 if (ParseTypeAndValue(Op0, Loc, PFS) || 6726 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6727 ParseTypeAndValue(Op1, PFS) || 6728 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6729 ParseTypeAndValue(Op2, PFS)) 6730 return true; 6731 6732 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6733 return Error(Loc, "invalid insertelement operands"); 6734 6735 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6736 return false; 6737 } 6738 6739 /// ParseShuffleVector 6740 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6741 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6742 LocTy Loc; 6743 Value *Op0, *Op1, *Op2; 6744 if (ParseTypeAndValue(Op0, Loc, PFS) || 6745 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 6746 ParseTypeAndValue(Op1, PFS) || 6747 ParseToken(lltok::comma, "expected ',' after shuffle value") || 6748 ParseTypeAndValue(Op2, PFS)) 6749 return true; 6750 6751 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 6752 return Error(Loc, "invalid shufflevector operands"); 6753 6754 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 6755 return false; 6756 } 6757 6758 /// ParsePHI 6759 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 6760 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 6761 Type *Ty = nullptr; LocTy TypeLoc; 6762 Value *Op0, *Op1; 6763 6764 if (ParseType(Ty, TypeLoc) || 6765 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 6766 ParseValue(Ty, Op0, PFS) || 6767 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6768 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 6769 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 6770 return true; 6771 6772 bool AteExtraComma = false; 6773 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 6774 6775 while (true) { 6776 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 6777 6778 if (!EatIfPresent(lltok::comma)) 6779 break; 6780 6781 if (Lex.getKind() == lltok::MetadataVar) { 6782 AteExtraComma = true; 6783 break; 6784 } 6785 6786 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 6787 ParseValue(Ty, Op0, PFS) || 6788 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6789 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 6790 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 6791 return true; 6792 } 6793 6794 if (!Ty->isFirstClassType()) 6795 return Error(TypeLoc, "phi node must have first class type"); 6796 6797 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 6798 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 6799 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 6800 Inst = PN; 6801 return AteExtraComma ? InstExtraComma : InstNormal; 6802 } 6803 6804 /// ParseLandingPad 6805 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 6806 /// Clause 6807 /// ::= 'catch' TypeAndValue 6808 /// ::= 'filter' 6809 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 6810 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 6811 Type *Ty = nullptr; LocTy TyLoc; 6812 6813 if (ParseType(Ty, TyLoc)) 6814 return true; 6815 6816 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 6817 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 6818 6819 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 6820 LandingPadInst::ClauseType CT; 6821 if (EatIfPresent(lltok::kw_catch)) 6822 CT = LandingPadInst::Catch; 6823 else if (EatIfPresent(lltok::kw_filter)) 6824 CT = LandingPadInst::Filter; 6825 else 6826 return TokError("expected 'catch' or 'filter' clause type"); 6827 6828 Value *V; 6829 LocTy VLoc; 6830 if (ParseTypeAndValue(V, VLoc, PFS)) 6831 return true; 6832 6833 // A 'catch' type expects a non-array constant. A filter clause expects an 6834 // array constant. 6835 if (CT == LandingPadInst::Catch) { 6836 if (isa<ArrayType>(V->getType())) 6837 Error(VLoc, "'catch' clause has an invalid type"); 6838 } else { 6839 if (!isa<ArrayType>(V->getType())) 6840 Error(VLoc, "'filter' clause has an invalid type"); 6841 } 6842 6843 Constant *CV = dyn_cast<Constant>(V); 6844 if (!CV) 6845 return Error(VLoc, "clause argument must be a constant"); 6846 LP->addClause(CV); 6847 } 6848 6849 Inst = LP.release(); 6850 return false; 6851 } 6852 6853 /// ParseFreeze 6854 /// ::= 'freeze' Type Value 6855 bool LLParser::ParseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 6856 LocTy Loc; 6857 Value *Op; 6858 if (ParseTypeAndValue(Op, Loc, PFS)) 6859 return true; 6860 6861 Inst = new FreezeInst(Op); 6862 return false; 6863 } 6864 6865 /// ParseCall 6866 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 6867 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6868 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 6869 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6870 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 6871 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6872 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 6873 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6874 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 6875 CallInst::TailCallKind TCK) { 6876 AttrBuilder RetAttrs, FnAttrs; 6877 std::vector<unsigned> FwdRefAttrGrps; 6878 LocTy BuiltinLoc; 6879 unsigned CallAddrSpace; 6880 unsigned CC; 6881 Type *RetType = nullptr; 6882 LocTy RetTypeLoc; 6883 ValID CalleeID; 6884 SmallVector<ParamInfo, 16> ArgList; 6885 SmallVector<OperandBundleDef, 2> BundleList; 6886 LocTy CallLoc = Lex.getLoc(); 6887 6888 if (TCK != CallInst::TCK_None && 6889 ParseToken(lltok::kw_call, 6890 "expected 'tail call', 'musttail call', or 'notail call'")) 6891 return true; 6892 6893 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6894 6895 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6896 ParseOptionalProgramAddrSpace(CallAddrSpace) || 6897 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6898 ParseValID(CalleeID) || 6899 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 6900 PFS.getFunction().isVarArg()) || 6901 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 6902 ParseOptionalOperandBundles(BundleList, PFS)) 6903 return true; 6904 6905 // If RetType is a non-function pointer type, then this is the short syntax 6906 // for the call, which means that RetType is just the return type. Infer the 6907 // rest of the function argument types from the arguments that are present. 6908 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6909 if (!Ty) { 6910 // Pull out the types of all of the arguments... 6911 std::vector<Type*> ParamTypes; 6912 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6913 ParamTypes.push_back(ArgList[i].V->getType()); 6914 6915 if (!FunctionType::isValidReturnType(RetType)) 6916 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6917 6918 Ty = FunctionType::get(RetType, ParamTypes, false); 6919 } 6920 6921 CalleeID.FTy = Ty; 6922 6923 // Look up the callee. 6924 Value *Callee; 6925 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 6926 &PFS, /*IsCall=*/true)) 6927 return true; 6928 6929 // Set up the Attribute for the function. 6930 SmallVector<AttributeSet, 8> Attrs; 6931 6932 SmallVector<Value*, 8> Args; 6933 6934 // Loop through FunctionType's arguments and ensure they are specified 6935 // correctly. Also, gather any parameter attributes. 6936 FunctionType::param_iterator I = Ty->param_begin(); 6937 FunctionType::param_iterator E = Ty->param_end(); 6938 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6939 Type *ExpectedTy = nullptr; 6940 if (I != E) { 6941 ExpectedTy = *I++; 6942 } else if (!Ty->isVarArg()) { 6943 return Error(ArgList[i].Loc, "too many arguments specified"); 6944 } 6945 6946 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6947 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6948 getTypeString(ExpectedTy) + "'"); 6949 Args.push_back(ArgList[i].V); 6950 Attrs.push_back(ArgList[i].Attrs); 6951 } 6952 6953 if (I != E) 6954 return Error(CallLoc, "not enough parameters specified for call"); 6955 6956 if (FnAttrs.hasAlignmentAttr()) 6957 return Error(CallLoc, "call instructions may not have an alignment"); 6958 6959 // Finish off the Attribute and check them 6960 AttributeList PAL = 6961 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6962 AttributeSet::get(Context, RetAttrs), Attrs); 6963 6964 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 6965 CI->setTailCallKind(TCK); 6966 CI->setCallingConv(CC); 6967 if (FMF.any()) { 6968 if (!isa<FPMathOperator>(CI)) { 6969 CI->deleteValue(); 6970 return Error(CallLoc, "fast-math-flags specified for call without " 6971 "floating-point scalar or vector return type"); 6972 } 6973 CI->setFastMathFlags(FMF); 6974 } 6975 CI->setAttributes(PAL); 6976 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 6977 Inst = CI; 6978 return false; 6979 } 6980 6981 //===----------------------------------------------------------------------===// 6982 // Memory Instructions. 6983 //===----------------------------------------------------------------------===// 6984 6985 /// ParseAlloc 6986 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 6987 /// (',' 'align' i32)? (',', 'addrspace(n))? 6988 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 6989 Value *Size = nullptr; 6990 LocTy SizeLoc, TyLoc, ASLoc; 6991 MaybeAlign Alignment; 6992 unsigned AddrSpace = 0; 6993 Type *Ty = nullptr; 6994 6995 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 6996 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 6997 6998 if (ParseType(Ty, TyLoc)) return true; 6999 7000 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7001 return Error(TyLoc, "invalid type for alloca"); 7002 7003 bool AteExtraComma = false; 7004 if (EatIfPresent(lltok::comma)) { 7005 if (Lex.getKind() == lltok::kw_align) { 7006 if (ParseOptionalAlignment(Alignment)) 7007 return true; 7008 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7009 return true; 7010 } else if (Lex.getKind() == lltok::kw_addrspace) { 7011 ASLoc = Lex.getLoc(); 7012 if (ParseOptionalAddrSpace(AddrSpace)) 7013 return true; 7014 } else if (Lex.getKind() == lltok::MetadataVar) { 7015 AteExtraComma = true; 7016 } else { 7017 if (ParseTypeAndValue(Size, SizeLoc, PFS)) 7018 return true; 7019 if (EatIfPresent(lltok::comma)) { 7020 if (Lex.getKind() == lltok::kw_align) { 7021 if (ParseOptionalAlignment(Alignment)) 7022 return true; 7023 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7024 return true; 7025 } else if (Lex.getKind() == lltok::kw_addrspace) { 7026 ASLoc = Lex.getLoc(); 7027 if (ParseOptionalAddrSpace(AddrSpace)) 7028 return true; 7029 } else if (Lex.getKind() == lltok::MetadataVar) { 7030 AteExtraComma = true; 7031 } 7032 } 7033 } 7034 } 7035 7036 if (Size && !Size->getType()->isIntegerTy()) 7037 return Error(SizeLoc, "element count must have integer type"); 7038 7039 SmallPtrSet<Type *, 4> Visited; 7040 if (!Alignment && !Ty->isSized(&Visited)) 7041 return Error(TyLoc, "Cannot allocate unsized type"); 7042 if (!Alignment) 7043 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7044 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7045 AI->setUsedWithInAlloca(IsInAlloca); 7046 AI->setSwiftError(IsSwiftError); 7047 Inst = AI; 7048 return AteExtraComma ? InstExtraComma : InstNormal; 7049 } 7050 7051 /// ParseLoad 7052 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7053 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7054 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7055 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7056 Value *Val; LocTy Loc; 7057 MaybeAlign Alignment; 7058 bool AteExtraComma = false; 7059 bool isAtomic = false; 7060 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7061 SyncScope::ID SSID = SyncScope::System; 7062 7063 if (Lex.getKind() == lltok::kw_atomic) { 7064 isAtomic = true; 7065 Lex.Lex(); 7066 } 7067 7068 bool isVolatile = false; 7069 if (Lex.getKind() == lltok::kw_volatile) { 7070 isVolatile = true; 7071 Lex.Lex(); 7072 } 7073 7074 Type *Ty; 7075 LocTy ExplicitTypeLoc = Lex.getLoc(); 7076 if (ParseType(Ty) || 7077 ParseToken(lltok::comma, "expected comma after load's type") || 7078 ParseTypeAndValue(Val, Loc, PFS) || 7079 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 7080 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 7081 return true; 7082 7083 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7084 return Error(Loc, "load operand must be a pointer to a first class type"); 7085 if (isAtomic && !Alignment) 7086 return Error(Loc, "atomic load must have explicit non-zero alignment"); 7087 if (Ordering == AtomicOrdering::Release || 7088 Ordering == AtomicOrdering::AcquireRelease) 7089 return Error(Loc, "atomic load cannot use Release ordering"); 7090 7091 if (Ty != cast<PointerType>(Val->getType())->getElementType()) 7092 return Error(ExplicitTypeLoc, 7093 "explicit pointee type doesn't match operand's pointee type"); 7094 SmallPtrSet<Type *, 4> Visited; 7095 if (!Alignment && !Ty->isSized(&Visited)) 7096 return Error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7097 if (!Alignment) 7098 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7099 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7100 return AteExtraComma ? InstExtraComma : InstNormal; 7101 } 7102 7103 /// ParseStore 7104 7105 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7106 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7107 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7108 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 7109 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7110 MaybeAlign Alignment; 7111 bool AteExtraComma = false; 7112 bool isAtomic = false; 7113 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7114 SyncScope::ID SSID = SyncScope::System; 7115 7116 if (Lex.getKind() == lltok::kw_atomic) { 7117 isAtomic = true; 7118 Lex.Lex(); 7119 } 7120 7121 bool isVolatile = false; 7122 if (Lex.getKind() == lltok::kw_volatile) { 7123 isVolatile = true; 7124 Lex.Lex(); 7125 } 7126 7127 if (ParseTypeAndValue(Val, Loc, PFS) || 7128 ParseToken(lltok::comma, "expected ',' after store operand") || 7129 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7130 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 7131 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 7132 return true; 7133 7134 if (!Ptr->getType()->isPointerTy()) 7135 return Error(PtrLoc, "store operand must be a pointer"); 7136 if (!Val->getType()->isFirstClassType()) 7137 return Error(Loc, "store operand must be a first class value"); 7138 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7139 return Error(Loc, "stored value and pointer type do not match"); 7140 if (isAtomic && !Alignment) 7141 return Error(Loc, "atomic store must have explicit non-zero alignment"); 7142 if (Ordering == AtomicOrdering::Acquire || 7143 Ordering == AtomicOrdering::AcquireRelease) 7144 return Error(Loc, "atomic store cannot use Acquire ordering"); 7145 SmallPtrSet<Type *, 4> Visited; 7146 if (!Alignment && !Val->getType()->isSized(&Visited)) 7147 return Error(Loc, "storing unsized types is not allowed"); 7148 if (!Alignment) 7149 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7150 7151 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7152 return AteExtraComma ? InstExtraComma : InstNormal; 7153 } 7154 7155 /// ParseCmpXchg 7156 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7157 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering 7158 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7159 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7160 bool AteExtraComma = false; 7161 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7162 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7163 SyncScope::ID SSID = SyncScope::System; 7164 bool isVolatile = false; 7165 bool isWeak = false; 7166 7167 if (EatIfPresent(lltok::kw_weak)) 7168 isWeak = true; 7169 7170 if (EatIfPresent(lltok::kw_volatile)) 7171 isVolatile = true; 7172 7173 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7174 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 7175 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 7176 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7177 ParseTypeAndValue(New, NewLoc, PFS) || 7178 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7179 ParseOrdering(FailureOrdering)) 7180 return true; 7181 7182 if (SuccessOrdering == AtomicOrdering::Unordered || 7183 FailureOrdering == AtomicOrdering::Unordered) 7184 return TokError("cmpxchg cannot be unordered"); 7185 if (isStrongerThan(FailureOrdering, SuccessOrdering)) 7186 return TokError("cmpxchg failure argument shall be no stronger than the " 7187 "success argument"); 7188 if (FailureOrdering == AtomicOrdering::Release || 7189 FailureOrdering == AtomicOrdering::AcquireRelease) 7190 return TokError( 7191 "cmpxchg failure ordering cannot include release semantics"); 7192 if (!Ptr->getType()->isPointerTy()) 7193 return Error(PtrLoc, "cmpxchg operand must be a pointer"); 7194 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 7195 return Error(CmpLoc, "compare value and pointer type do not match"); 7196 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 7197 return Error(NewLoc, "new value and pointer type do not match"); 7198 if (!New->getType()->isFirstClassType()) 7199 return Error(NewLoc, "cmpxchg operand must be a first class value"); 7200 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7201 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID); 7202 CXI->setVolatile(isVolatile); 7203 CXI->setWeak(isWeak); 7204 Inst = CXI; 7205 return AteExtraComma ? InstExtraComma : InstNormal; 7206 } 7207 7208 /// ParseAtomicRMW 7209 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7210 /// 'singlethread'? AtomicOrdering 7211 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7212 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7213 bool AteExtraComma = false; 7214 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7215 SyncScope::ID SSID = SyncScope::System; 7216 bool isVolatile = false; 7217 bool IsFP = false; 7218 AtomicRMWInst::BinOp Operation; 7219 7220 if (EatIfPresent(lltok::kw_volatile)) 7221 isVolatile = true; 7222 7223 switch (Lex.getKind()) { 7224 default: return TokError("expected binary operation in atomicrmw"); 7225 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7226 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7227 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7228 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7229 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7230 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7231 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7232 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7233 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7234 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7235 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7236 case lltok::kw_fadd: 7237 Operation = AtomicRMWInst::FAdd; 7238 IsFP = true; 7239 break; 7240 case lltok::kw_fsub: 7241 Operation = AtomicRMWInst::FSub; 7242 IsFP = true; 7243 break; 7244 } 7245 Lex.Lex(); // Eat the operation. 7246 7247 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7248 ParseToken(lltok::comma, "expected ',' after atomicrmw address") || 7249 ParseTypeAndValue(Val, ValLoc, PFS) || 7250 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7251 return true; 7252 7253 if (Ordering == AtomicOrdering::Unordered) 7254 return TokError("atomicrmw cannot be unordered"); 7255 if (!Ptr->getType()->isPointerTy()) 7256 return Error(PtrLoc, "atomicrmw operand must be a pointer"); 7257 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7258 return Error(ValLoc, "atomicrmw value and pointer type do not match"); 7259 7260 if (Operation == AtomicRMWInst::Xchg) { 7261 if (!Val->getType()->isIntegerTy() && 7262 !Val->getType()->isFloatingPointTy()) { 7263 return Error(ValLoc, "atomicrmw " + 7264 AtomicRMWInst::getOperationName(Operation) + 7265 " operand must be an integer or floating point type"); 7266 } 7267 } else if (IsFP) { 7268 if (!Val->getType()->isFloatingPointTy()) { 7269 return Error(ValLoc, "atomicrmw " + 7270 AtomicRMWInst::getOperationName(Operation) + 7271 " operand must be a floating point type"); 7272 } 7273 } else { 7274 if (!Val->getType()->isIntegerTy()) { 7275 return Error(ValLoc, "atomicrmw " + 7276 AtomicRMWInst::getOperationName(Operation) + 7277 " operand must be an integer"); 7278 } 7279 } 7280 7281 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7282 if (Size < 8 || (Size & (Size - 1))) 7283 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7284 " integer"); 7285 7286 AtomicRMWInst *RMWI = 7287 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 7288 RMWI->setVolatile(isVolatile); 7289 Inst = RMWI; 7290 return AteExtraComma ? InstExtraComma : InstNormal; 7291 } 7292 7293 /// ParseFence 7294 /// ::= 'fence' 'singlethread'? AtomicOrdering 7295 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) { 7296 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7297 SyncScope::ID SSID = SyncScope::System; 7298 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7299 return true; 7300 7301 if (Ordering == AtomicOrdering::Unordered) 7302 return TokError("fence cannot be unordered"); 7303 if (Ordering == AtomicOrdering::Monotonic) 7304 return TokError("fence cannot be monotonic"); 7305 7306 Inst = new FenceInst(Context, Ordering, SSID); 7307 return InstNormal; 7308 } 7309 7310 /// ParseGetElementPtr 7311 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7312 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7313 Value *Ptr = nullptr; 7314 Value *Val = nullptr; 7315 LocTy Loc, EltLoc; 7316 7317 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7318 7319 Type *Ty = nullptr; 7320 LocTy ExplicitTypeLoc = Lex.getLoc(); 7321 if (ParseType(Ty) || 7322 ParseToken(lltok::comma, "expected comma after getelementptr's type") || 7323 ParseTypeAndValue(Ptr, Loc, PFS)) 7324 return true; 7325 7326 Type *BaseType = Ptr->getType(); 7327 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7328 if (!BasePointerType) 7329 return Error(Loc, "base of getelementptr must be a pointer"); 7330 7331 if (Ty != BasePointerType->getElementType()) 7332 return Error(ExplicitTypeLoc, 7333 "explicit pointee type doesn't match operand's pointee type"); 7334 7335 SmallVector<Value*, 16> Indices; 7336 bool AteExtraComma = false; 7337 // GEP returns a vector of pointers if at least one of parameters is a vector. 7338 // All vector parameters should have the same vector width. 7339 ElementCount GEPWidth = BaseType->isVectorTy() 7340 ? cast<VectorType>(BaseType)->getElementCount() 7341 : ElementCount(0, false); 7342 7343 while (EatIfPresent(lltok::comma)) { 7344 if (Lex.getKind() == lltok::MetadataVar) { 7345 AteExtraComma = true; 7346 break; 7347 } 7348 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 7349 if (!Val->getType()->isIntOrIntVectorTy()) 7350 return Error(EltLoc, "getelementptr index must be an integer"); 7351 7352 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7353 ElementCount ValNumEl = ValVTy->getElementCount(); 7354 if (GEPWidth != ElementCount(0, false) && GEPWidth != ValNumEl) 7355 return Error(EltLoc, 7356 "getelementptr vector index has a wrong number of elements"); 7357 GEPWidth = ValNumEl; 7358 } 7359 Indices.push_back(Val); 7360 } 7361 7362 SmallPtrSet<Type*, 4> Visited; 7363 if (!Indices.empty() && !Ty->isSized(&Visited)) 7364 return Error(Loc, "base element of getelementptr must be sized"); 7365 7366 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7367 return Error(Loc, "invalid getelementptr indices"); 7368 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7369 if (InBounds) 7370 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7371 return AteExtraComma ? InstExtraComma : InstNormal; 7372 } 7373 7374 /// ParseExtractValue 7375 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7376 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7377 Value *Val; LocTy Loc; 7378 SmallVector<unsigned, 4> Indices; 7379 bool AteExtraComma; 7380 if (ParseTypeAndValue(Val, Loc, PFS) || 7381 ParseIndexList(Indices, AteExtraComma)) 7382 return true; 7383 7384 if (!Val->getType()->isAggregateType()) 7385 return Error(Loc, "extractvalue operand must be aggregate type"); 7386 7387 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7388 return Error(Loc, "invalid indices for extractvalue"); 7389 Inst = ExtractValueInst::Create(Val, Indices); 7390 return AteExtraComma ? InstExtraComma : InstNormal; 7391 } 7392 7393 /// ParseInsertValue 7394 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7395 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7396 Value *Val0, *Val1; LocTy Loc0, Loc1; 7397 SmallVector<unsigned, 4> Indices; 7398 bool AteExtraComma; 7399 if (ParseTypeAndValue(Val0, Loc0, PFS) || 7400 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 7401 ParseTypeAndValue(Val1, Loc1, PFS) || 7402 ParseIndexList(Indices, AteExtraComma)) 7403 return true; 7404 7405 if (!Val0->getType()->isAggregateType()) 7406 return Error(Loc0, "insertvalue operand must be aggregate type"); 7407 7408 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7409 if (!IndexedType) 7410 return Error(Loc0, "invalid indices for insertvalue"); 7411 if (IndexedType != Val1->getType()) 7412 return Error(Loc1, "insertvalue operand and field disagree in type: '" + 7413 getTypeString(Val1->getType()) + "' instead of '" + 7414 getTypeString(IndexedType) + "'"); 7415 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7416 return AteExtraComma ? InstExtraComma : InstNormal; 7417 } 7418 7419 //===----------------------------------------------------------------------===// 7420 // Embedded metadata. 7421 //===----------------------------------------------------------------------===// 7422 7423 /// ParseMDNodeVector 7424 /// ::= { Element (',' Element)* } 7425 /// Element 7426 /// ::= 'null' | TypeAndValue 7427 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7428 if (ParseToken(lltok::lbrace, "expected '{' here")) 7429 return true; 7430 7431 // Check for an empty list. 7432 if (EatIfPresent(lltok::rbrace)) 7433 return false; 7434 7435 do { 7436 // Null is a special case since it is typeless. 7437 if (EatIfPresent(lltok::kw_null)) { 7438 Elts.push_back(nullptr); 7439 continue; 7440 } 7441 7442 Metadata *MD; 7443 if (ParseMetadata(MD, nullptr)) 7444 return true; 7445 Elts.push_back(MD); 7446 } while (EatIfPresent(lltok::comma)); 7447 7448 return ParseToken(lltok::rbrace, "expected end of metadata node"); 7449 } 7450 7451 //===----------------------------------------------------------------------===// 7452 // Use-list order directives. 7453 //===----------------------------------------------------------------------===// 7454 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7455 SMLoc Loc) { 7456 if (V->use_empty()) 7457 return Error(Loc, "value has no uses"); 7458 7459 unsigned NumUses = 0; 7460 SmallDenseMap<const Use *, unsigned, 16> Order; 7461 for (const Use &U : V->uses()) { 7462 if (++NumUses > Indexes.size()) 7463 break; 7464 Order[&U] = Indexes[NumUses - 1]; 7465 } 7466 if (NumUses < 2) 7467 return Error(Loc, "value only has one use"); 7468 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7469 return Error(Loc, 7470 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7471 7472 V->sortUseList([&](const Use &L, const Use &R) { 7473 return Order.lookup(&L) < Order.lookup(&R); 7474 }); 7475 return false; 7476 } 7477 7478 /// ParseUseListOrderIndexes 7479 /// ::= '{' uint32 (',' uint32)+ '}' 7480 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7481 SMLoc Loc = Lex.getLoc(); 7482 if (ParseToken(lltok::lbrace, "expected '{' here")) 7483 return true; 7484 if (Lex.getKind() == lltok::rbrace) 7485 return Lex.Error("expected non-empty list of uselistorder indexes"); 7486 7487 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7488 // indexes should be distinct numbers in the range [0, size-1], and should 7489 // not be in order. 7490 unsigned Offset = 0; 7491 unsigned Max = 0; 7492 bool IsOrdered = true; 7493 assert(Indexes.empty() && "Expected empty order vector"); 7494 do { 7495 unsigned Index; 7496 if (ParseUInt32(Index)) 7497 return true; 7498 7499 // Update consistency checks. 7500 Offset += Index - Indexes.size(); 7501 Max = std::max(Max, Index); 7502 IsOrdered &= Index == Indexes.size(); 7503 7504 Indexes.push_back(Index); 7505 } while (EatIfPresent(lltok::comma)); 7506 7507 if (ParseToken(lltok::rbrace, "expected '}' here")) 7508 return true; 7509 7510 if (Indexes.size() < 2) 7511 return Error(Loc, "expected >= 2 uselistorder indexes"); 7512 if (Offset != 0 || Max >= Indexes.size()) 7513 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)"); 7514 if (IsOrdered) 7515 return Error(Loc, "expected uselistorder indexes to change the order"); 7516 7517 return false; 7518 } 7519 7520 /// ParseUseListOrder 7521 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7522 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) { 7523 SMLoc Loc = Lex.getLoc(); 7524 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7525 return true; 7526 7527 Value *V; 7528 SmallVector<unsigned, 16> Indexes; 7529 if (ParseTypeAndValue(V, PFS) || 7530 ParseToken(lltok::comma, "expected comma in uselistorder directive") || 7531 ParseUseListOrderIndexes(Indexes)) 7532 return true; 7533 7534 return sortUseListOrder(V, Indexes, Loc); 7535 } 7536 7537 /// ParseUseListOrderBB 7538 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7539 bool LLParser::ParseUseListOrderBB() { 7540 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7541 SMLoc Loc = Lex.getLoc(); 7542 Lex.Lex(); 7543 7544 ValID Fn, Label; 7545 SmallVector<unsigned, 16> Indexes; 7546 if (ParseValID(Fn) || 7547 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7548 ParseValID(Label) || 7549 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7550 ParseUseListOrderIndexes(Indexes)) 7551 return true; 7552 7553 // Check the function. 7554 GlobalValue *GV; 7555 if (Fn.Kind == ValID::t_GlobalName) 7556 GV = M->getNamedValue(Fn.StrVal); 7557 else if (Fn.Kind == ValID::t_GlobalID) 7558 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7559 else 7560 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 7561 if (!GV) 7562 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb"); 7563 auto *F = dyn_cast<Function>(GV); 7564 if (!F) 7565 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 7566 if (F->isDeclaration()) 7567 return Error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7568 7569 // Check the basic block. 7570 if (Label.Kind == ValID::t_LocalID) 7571 return Error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7572 if (Label.Kind != ValID::t_LocalName) 7573 return Error(Label.Loc, "expected basic block name in uselistorder_bb"); 7574 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7575 if (!V) 7576 return Error(Label.Loc, "invalid basic block in uselistorder_bb"); 7577 if (!isa<BasicBlock>(V)) 7578 return Error(Label.Loc, "expected basic block in uselistorder_bb"); 7579 7580 return sortUseListOrder(V, Indexes, Loc); 7581 } 7582 7583 /// ModuleEntry 7584 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7585 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7586 bool LLParser::ParseModuleEntry(unsigned ID) { 7587 assert(Lex.getKind() == lltok::kw_module); 7588 Lex.Lex(); 7589 7590 std::string Path; 7591 if (ParseToken(lltok::colon, "expected ':' here") || 7592 ParseToken(lltok::lparen, "expected '(' here") || 7593 ParseToken(lltok::kw_path, "expected 'path' here") || 7594 ParseToken(lltok::colon, "expected ':' here") || 7595 ParseStringConstant(Path) || 7596 ParseToken(lltok::comma, "expected ',' here") || 7597 ParseToken(lltok::kw_hash, "expected 'hash' here") || 7598 ParseToken(lltok::colon, "expected ':' here") || 7599 ParseToken(lltok::lparen, "expected '(' here")) 7600 return true; 7601 7602 ModuleHash Hash; 7603 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") || 7604 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") || 7605 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") || 7606 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") || 7607 ParseUInt32(Hash[4])) 7608 return true; 7609 7610 if (ParseToken(lltok::rparen, "expected ')' here") || 7611 ParseToken(lltok::rparen, "expected ')' here")) 7612 return true; 7613 7614 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7615 ModuleIdMap[ID] = ModuleEntry->first(); 7616 7617 return false; 7618 } 7619 7620 /// TypeIdEntry 7621 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7622 bool LLParser::ParseTypeIdEntry(unsigned ID) { 7623 assert(Lex.getKind() == lltok::kw_typeid); 7624 Lex.Lex(); 7625 7626 std::string Name; 7627 if (ParseToken(lltok::colon, "expected ':' here") || 7628 ParseToken(lltok::lparen, "expected '(' here") || 7629 ParseToken(lltok::kw_name, "expected 'name' here") || 7630 ParseToken(lltok::colon, "expected ':' here") || 7631 ParseStringConstant(Name)) 7632 return true; 7633 7634 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7635 if (ParseToken(lltok::comma, "expected ',' here") || 7636 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here")) 7637 return true; 7638 7639 // Check if this ID was forward referenced, and if so, update the 7640 // corresponding GUIDs. 7641 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7642 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7643 for (auto TIDRef : FwdRefTIDs->second) { 7644 assert(!*TIDRef.first && 7645 "Forward referenced type id GUID expected to be 0"); 7646 *TIDRef.first = GlobalValue::getGUID(Name); 7647 } 7648 ForwardRefTypeIds.erase(FwdRefTIDs); 7649 } 7650 7651 return false; 7652 } 7653 7654 /// TypeIdSummary 7655 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7656 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) { 7657 if (ParseToken(lltok::kw_summary, "expected 'summary' here") || 7658 ParseToken(lltok::colon, "expected ':' here") || 7659 ParseToken(lltok::lparen, "expected '(' here") || 7660 ParseTypeTestResolution(TIS.TTRes)) 7661 return true; 7662 7663 if (EatIfPresent(lltok::comma)) { 7664 // Expect optional wpdResolutions field 7665 if (ParseOptionalWpdResolutions(TIS.WPDRes)) 7666 return true; 7667 } 7668 7669 if (ParseToken(lltok::rparen, "expected ')' here")) 7670 return true; 7671 7672 return false; 7673 } 7674 7675 static ValueInfo EmptyVI = 7676 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7677 7678 /// TypeIdCompatibleVtableEntry 7679 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7680 /// TypeIdCompatibleVtableInfo 7681 /// ')' 7682 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) { 7683 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7684 Lex.Lex(); 7685 7686 std::string Name; 7687 if (ParseToken(lltok::colon, "expected ':' here") || 7688 ParseToken(lltok::lparen, "expected '(' here") || 7689 ParseToken(lltok::kw_name, "expected 'name' here") || 7690 ParseToken(lltok::colon, "expected ':' here") || 7691 ParseStringConstant(Name)) 7692 return true; 7693 7694 TypeIdCompatibleVtableInfo &TI = 7695 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7696 if (ParseToken(lltok::comma, "expected ',' here") || 7697 ParseToken(lltok::kw_summary, "expected 'summary' here") || 7698 ParseToken(lltok::colon, "expected ':' here") || 7699 ParseToken(lltok::lparen, "expected '(' here")) 7700 return true; 7701 7702 IdToIndexMapType IdToIndexMap; 7703 // Parse each call edge 7704 do { 7705 uint64_t Offset; 7706 if (ParseToken(lltok::lparen, "expected '(' here") || 7707 ParseToken(lltok::kw_offset, "expected 'offset' here") || 7708 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) || 7709 ParseToken(lltok::comma, "expected ',' here")) 7710 return true; 7711 7712 LocTy Loc = Lex.getLoc(); 7713 unsigned GVId; 7714 ValueInfo VI; 7715 if (ParseGVReference(VI, GVId)) 7716 return true; 7717 7718 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7719 // forward reference. We will save the location of the ValueInfo needing an 7720 // update, but can only do so once the std::vector is finalized. 7721 if (VI == EmptyVI) 7722 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7723 TI.push_back({Offset, VI}); 7724 7725 if (ParseToken(lltok::rparen, "expected ')' in call")) 7726 return true; 7727 } while (EatIfPresent(lltok::comma)); 7728 7729 // Now that the TI vector is finalized, it is safe to save the locations 7730 // of any forward GV references that need updating later. 7731 for (auto I : IdToIndexMap) { 7732 for (auto P : I.second) { 7733 assert(TI[P.first].VTableVI == EmptyVI && 7734 "Forward referenced ValueInfo expected to be empty"); 7735 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 7736 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 7737 FwdRef.first->second.push_back( 7738 std::make_pair(&TI[P.first].VTableVI, P.second)); 7739 } 7740 } 7741 7742 if (ParseToken(lltok::rparen, "expected ')' here") || 7743 ParseToken(lltok::rparen, "expected ')' here")) 7744 return true; 7745 7746 // Check if this ID was forward referenced, and if so, update the 7747 // corresponding GUIDs. 7748 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7749 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7750 for (auto TIDRef : FwdRefTIDs->second) { 7751 assert(!*TIDRef.first && 7752 "Forward referenced type id GUID expected to be 0"); 7753 *TIDRef.first = GlobalValue::getGUID(Name); 7754 } 7755 ForwardRefTypeIds.erase(FwdRefTIDs); 7756 } 7757 7758 return false; 7759 } 7760 7761 /// TypeTestResolution 7762 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 7763 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 7764 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 7765 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 7766 /// [',' 'inlinesBits' ':' UInt64]? ')' 7767 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) { 7768 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 7769 ParseToken(lltok::colon, "expected ':' here") || 7770 ParseToken(lltok::lparen, "expected '(' here") || 7771 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7772 ParseToken(lltok::colon, "expected ':' here")) 7773 return true; 7774 7775 switch (Lex.getKind()) { 7776 case lltok::kw_unsat: 7777 TTRes.TheKind = TypeTestResolution::Unsat; 7778 break; 7779 case lltok::kw_byteArray: 7780 TTRes.TheKind = TypeTestResolution::ByteArray; 7781 break; 7782 case lltok::kw_inline: 7783 TTRes.TheKind = TypeTestResolution::Inline; 7784 break; 7785 case lltok::kw_single: 7786 TTRes.TheKind = TypeTestResolution::Single; 7787 break; 7788 case lltok::kw_allOnes: 7789 TTRes.TheKind = TypeTestResolution::AllOnes; 7790 break; 7791 default: 7792 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 7793 } 7794 Lex.Lex(); 7795 7796 if (ParseToken(lltok::comma, "expected ',' here") || 7797 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 7798 ParseToken(lltok::colon, "expected ':' here") || 7799 ParseUInt32(TTRes.SizeM1BitWidth)) 7800 return true; 7801 7802 // Parse optional fields 7803 while (EatIfPresent(lltok::comma)) { 7804 switch (Lex.getKind()) { 7805 case lltok::kw_alignLog2: 7806 Lex.Lex(); 7807 if (ParseToken(lltok::colon, "expected ':'") || 7808 ParseUInt64(TTRes.AlignLog2)) 7809 return true; 7810 break; 7811 case lltok::kw_sizeM1: 7812 Lex.Lex(); 7813 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1)) 7814 return true; 7815 break; 7816 case lltok::kw_bitMask: { 7817 unsigned Val; 7818 Lex.Lex(); 7819 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val)) 7820 return true; 7821 assert(Val <= 0xff); 7822 TTRes.BitMask = (uint8_t)Val; 7823 break; 7824 } 7825 case lltok::kw_inlineBits: 7826 Lex.Lex(); 7827 if (ParseToken(lltok::colon, "expected ':'") || 7828 ParseUInt64(TTRes.InlineBits)) 7829 return true; 7830 break; 7831 default: 7832 return Error(Lex.getLoc(), "expected optional TypeTestResolution field"); 7833 } 7834 } 7835 7836 if (ParseToken(lltok::rparen, "expected ')' here")) 7837 return true; 7838 7839 return false; 7840 } 7841 7842 /// OptionalWpdResolutions 7843 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 7844 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 7845 bool LLParser::ParseOptionalWpdResolutions( 7846 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 7847 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 7848 ParseToken(lltok::colon, "expected ':' here") || 7849 ParseToken(lltok::lparen, "expected '(' here")) 7850 return true; 7851 7852 do { 7853 uint64_t Offset; 7854 WholeProgramDevirtResolution WPDRes; 7855 if (ParseToken(lltok::lparen, "expected '(' here") || 7856 ParseToken(lltok::kw_offset, "expected 'offset' here") || 7857 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) || 7858 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) || 7859 ParseToken(lltok::rparen, "expected ')' here")) 7860 return true; 7861 WPDResMap[Offset] = WPDRes; 7862 } while (EatIfPresent(lltok::comma)); 7863 7864 if (ParseToken(lltok::rparen, "expected ')' here")) 7865 return true; 7866 7867 return false; 7868 } 7869 7870 /// WpdRes 7871 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 7872 /// [',' OptionalResByArg]? ')' 7873 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 7874 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 7875 /// [',' OptionalResByArg]? ')' 7876 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 7877 /// [',' OptionalResByArg]? ')' 7878 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) { 7879 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 7880 ParseToken(lltok::colon, "expected ':' here") || 7881 ParseToken(lltok::lparen, "expected '(' here") || 7882 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7883 ParseToken(lltok::colon, "expected ':' here")) 7884 return true; 7885 7886 switch (Lex.getKind()) { 7887 case lltok::kw_indir: 7888 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 7889 break; 7890 case lltok::kw_singleImpl: 7891 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 7892 break; 7893 case lltok::kw_branchFunnel: 7894 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 7895 break; 7896 default: 7897 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 7898 } 7899 Lex.Lex(); 7900 7901 // Parse optional fields 7902 while (EatIfPresent(lltok::comma)) { 7903 switch (Lex.getKind()) { 7904 case lltok::kw_singleImplName: 7905 Lex.Lex(); 7906 if (ParseToken(lltok::colon, "expected ':' here") || 7907 ParseStringConstant(WPDRes.SingleImplName)) 7908 return true; 7909 break; 7910 case lltok::kw_resByArg: 7911 if (ParseOptionalResByArg(WPDRes.ResByArg)) 7912 return true; 7913 break; 7914 default: 7915 return Error(Lex.getLoc(), 7916 "expected optional WholeProgramDevirtResolution field"); 7917 } 7918 } 7919 7920 if (ParseToken(lltok::rparen, "expected ')' here")) 7921 return true; 7922 7923 return false; 7924 } 7925 7926 /// OptionalResByArg 7927 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 7928 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 7929 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 7930 /// 'virtualConstProp' ) 7931 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 7932 /// [',' 'bit' ':' UInt32]? ')' 7933 bool LLParser::ParseOptionalResByArg( 7934 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 7935 &ResByArg) { 7936 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 7937 ParseToken(lltok::colon, "expected ':' here") || 7938 ParseToken(lltok::lparen, "expected '(' here")) 7939 return true; 7940 7941 do { 7942 std::vector<uint64_t> Args; 7943 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") || 7944 ParseToken(lltok::kw_byArg, "expected 'byArg here") || 7945 ParseToken(lltok::colon, "expected ':' here") || 7946 ParseToken(lltok::lparen, "expected '(' here") || 7947 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7948 ParseToken(lltok::colon, "expected ':' here")) 7949 return true; 7950 7951 WholeProgramDevirtResolution::ByArg ByArg; 7952 switch (Lex.getKind()) { 7953 case lltok::kw_indir: 7954 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 7955 break; 7956 case lltok::kw_uniformRetVal: 7957 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 7958 break; 7959 case lltok::kw_uniqueRetVal: 7960 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 7961 break; 7962 case lltok::kw_virtualConstProp: 7963 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 7964 break; 7965 default: 7966 return Error(Lex.getLoc(), 7967 "unexpected WholeProgramDevirtResolution::ByArg kind"); 7968 } 7969 Lex.Lex(); 7970 7971 // Parse optional fields 7972 while (EatIfPresent(lltok::comma)) { 7973 switch (Lex.getKind()) { 7974 case lltok::kw_info: 7975 Lex.Lex(); 7976 if (ParseToken(lltok::colon, "expected ':' here") || 7977 ParseUInt64(ByArg.Info)) 7978 return true; 7979 break; 7980 case lltok::kw_byte: 7981 Lex.Lex(); 7982 if (ParseToken(lltok::colon, "expected ':' here") || 7983 ParseUInt32(ByArg.Byte)) 7984 return true; 7985 break; 7986 case lltok::kw_bit: 7987 Lex.Lex(); 7988 if (ParseToken(lltok::colon, "expected ':' here") || 7989 ParseUInt32(ByArg.Bit)) 7990 return true; 7991 break; 7992 default: 7993 return Error(Lex.getLoc(), 7994 "expected optional whole program devirt field"); 7995 } 7996 } 7997 7998 if (ParseToken(lltok::rparen, "expected ')' here")) 7999 return true; 8000 8001 ResByArg[Args] = ByArg; 8002 } while (EatIfPresent(lltok::comma)); 8003 8004 if (ParseToken(lltok::rparen, "expected ')' here")) 8005 return true; 8006 8007 return false; 8008 } 8009 8010 /// OptionalResByArg 8011 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8012 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) { 8013 if (ParseToken(lltok::kw_args, "expected 'args' here") || 8014 ParseToken(lltok::colon, "expected ':' here") || 8015 ParseToken(lltok::lparen, "expected '(' here")) 8016 return true; 8017 8018 do { 8019 uint64_t Val; 8020 if (ParseUInt64(Val)) 8021 return true; 8022 Args.push_back(Val); 8023 } while (EatIfPresent(lltok::comma)); 8024 8025 if (ParseToken(lltok::rparen, "expected ')' here")) 8026 return true; 8027 8028 return false; 8029 } 8030 8031 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8032 8033 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8034 bool ReadOnly = Fwd->isReadOnly(); 8035 bool WriteOnly = Fwd->isWriteOnly(); 8036 assert(!(ReadOnly && WriteOnly)); 8037 *Fwd = Resolved; 8038 if (ReadOnly) 8039 Fwd->setReadOnly(); 8040 if (WriteOnly) 8041 Fwd->setWriteOnly(); 8042 } 8043 8044 /// Stores the given Name/GUID and associated summary into the Index. 8045 /// Also updates any forward references to the associated entry ID. 8046 void LLParser::AddGlobalValueToIndex( 8047 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8048 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8049 // First create the ValueInfo utilizing the Name or GUID. 8050 ValueInfo VI; 8051 if (GUID != 0) { 8052 assert(Name.empty()); 8053 VI = Index->getOrInsertValueInfo(GUID); 8054 } else { 8055 assert(!Name.empty()); 8056 if (M) { 8057 auto *GV = M->getNamedValue(Name); 8058 assert(GV); 8059 VI = Index->getOrInsertValueInfo(GV); 8060 } else { 8061 assert( 8062 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8063 "Need a source_filename to compute GUID for local"); 8064 GUID = GlobalValue::getGUID( 8065 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8066 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8067 } 8068 } 8069 8070 // Resolve forward references from calls/refs 8071 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8072 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8073 for (auto VIRef : FwdRefVIs->second) { 8074 assert(VIRef.first->getRef() == FwdVIRef && 8075 "Forward referenced ValueInfo expected to be empty"); 8076 resolveFwdRef(VIRef.first, VI); 8077 } 8078 ForwardRefValueInfos.erase(FwdRefVIs); 8079 } 8080 8081 // Resolve forward references from aliases 8082 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8083 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8084 for (auto AliaseeRef : FwdRefAliasees->second) { 8085 assert(!AliaseeRef.first->hasAliasee() && 8086 "Forward referencing alias already has aliasee"); 8087 assert(Summary && "Aliasee must be a definition"); 8088 AliaseeRef.first->setAliasee(VI, Summary.get()); 8089 } 8090 ForwardRefAliasees.erase(FwdRefAliasees); 8091 } 8092 8093 // Add the summary if one was provided. 8094 if (Summary) 8095 Index->addGlobalValueSummary(VI, std::move(Summary)); 8096 8097 // Save the associated ValueInfo for use in later references by ID. 8098 if (ID == NumberedValueInfos.size()) 8099 NumberedValueInfos.push_back(VI); 8100 else { 8101 // Handle non-continuous numbers (to make test simplification easier). 8102 if (ID > NumberedValueInfos.size()) 8103 NumberedValueInfos.resize(ID + 1); 8104 NumberedValueInfos[ID] = VI; 8105 } 8106 } 8107 8108 /// ParseSummaryIndexFlags 8109 /// ::= 'flags' ':' UInt64 8110 bool LLParser::ParseSummaryIndexFlags() { 8111 assert(Lex.getKind() == lltok::kw_flags); 8112 Lex.Lex(); 8113 8114 if (ParseToken(lltok::colon, "expected ':' here")) 8115 return true; 8116 uint64_t Flags; 8117 if (ParseUInt64(Flags)) 8118 return true; 8119 Index->setFlags(Flags); 8120 return false; 8121 } 8122 8123 /// ParseBlockCount 8124 /// ::= 'blockcount' ':' UInt64 8125 bool LLParser::ParseBlockCount() { 8126 assert(Lex.getKind() == lltok::kw_blockcount); 8127 Lex.Lex(); 8128 8129 if (ParseToken(lltok::colon, "expected ':' here")) 8130 return true; 8131 uint64_t BlockCount; 8132 if (ParseUInt64(BlockCount)) 8133 return true; 8134 Index->setBlockCount(BlockCount); 8135 return false; 8136 } 8137 8138 /// ParseGVEntry 8139 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8140 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8141 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8142 bool LLParser::ParseGVEntry(unsigned ID) { 8143 assert(Lex.getKind() == lltok::kw_gv); 8144 Lex.Lex(); 8145 8146 if (ParseToken(lltok::colon, "expected ':' here") || 8147 ParseToken(lltok::lparen, "expected '(' here")) 8148 return true; 8149 8150 std::string Name; 8151 GlobalValue::GUID GUID = 0; 8152 switch (Lex.getKind()) { 8153 case lltok::kw_name: 8154 Lex.Lex(); 8155 if (ParseToken(lltok::colon, "expected ':' here") || 8156 ParseStringConstant(Name)) 8157 return true; 8158 // Can't create GUID/ValueInfo until we have the linkage. 8159 break; 8160 case lltok::kw_guid: 8161 Lex.Lex(); 8162 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID)) 8163 return true; 8164 break; 8165 default: 8166 return Error(Lex.getLoc(), "expected name or guid tag"); 8167 } 8168 8169 if (!EatIfPresent(lltok::comma)) { 8170 // No summaries. Wrap up. 8171 if (ParseToken(lltok::rparen, "expected ')' here")) 8172 return true; 8173 // This was created for a call to an external or indirect target. 8174 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8175 // created for indirect calls with VP. A Name with no GUID came from 8176 // an external definition. We pass ExternalLinkage since that is only 8177 // used when the GUID must be computed from Name, and in that case 8178 // the symbol must have external linkage. 8179 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8180 nullptr); 8181 return false; 8182 } 8183 8184 // Have a list of summaries 8185 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") || 8186 ParseToken(lltok::colon, "expected ':' here") || 8187 ParseToken(lltok::lparen, "expected '(' here")) 8188 return true; 8189 do { 8190 switch (Lex.getKind()) { 8191 case lltok::kw_function: 8192 if (ParseFunctionSummary(Name, GUID, ID)) 8193 return true; 8194 break; 8195 case lltok::kw_variable: 8196 if (ParseVariableSummary(Name, GUID, ID)) 8197 return true; 8198 break; 8199 case lltok::kw_alias: 8200 if (ParseAliasSummary(Name, GUID, ID)) 8201 return true; 8202 break; 8203 default: 8204 return Error(Lex.getLoc(), "expected summary type"); 8205 } 8206 } while (EatIfPresent(lltok::comma)); 8207 8208 if (ParseToken(lltok::rparen, "expected ')' here") || 8209 ParseToken(lltok::rparen, "expected ')' here")) 8210 return true; 8211 8212 return false; 8213 } 8214 8215 /// FunctionSummary 8216 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8217 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8218 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8219 /// [',' OptionalRefs]? ')' 8220 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8221 unsigned ID) { 8222 assert(Lex.getKind() == lltok::kw_function); 8223 Lex.Lex(); 8224 8225 StringRef ModulePath; 8226 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8227 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8228 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8229 unsigned InstCount; 8230 std::vector<FunctionSummary::EdgeTy> Calls; 8231 FunctionSummary::TypeIdInfo TypeIdInfo; 8232 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8233 std::vector<ValueInfo> Refs; 8234 // Default is all-zeros (conservative values). 8235 FunctionSummary::FFlags FFlags = {}; 8236 if (ParseToken(lltok::colon, "expected ':' here") || 8237 ParseToken(lltok::lparen, "expected '(' here") || 8238 ParseModuleReference(ModulePath) || 8239 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8240 ParseToken(lltok::comma, "expected ',' here") || 8241 ParseToken(lltok::kw_insts, "expected 'insts' here") || 8242 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount)) 8243 return true; 8244 8245 // Parse optional fields 8246 while (EatIfPresent(lltok::comma)) { 8247 switch (Lex.getKind()) { 8248 case lltok::kw_funcFlags: 8249 if (ParseOptionalFFlags(FFlags)) 8250 return true; 8251 break; 8252 case lltok::kw_calls: 8253 if (ParseOptionalCalls(Calls)) 8254 return true; 8255 break; 8256 case lltok::kw_typeIdInfo: 8257 if (ParseOptionalTypeIdInfo(TypeIdInfo)) 8258 return true; 8259 break; 8260 case lltok::kw_refs: 8261 if (ParseOptionalRefs(Refs)) 8262 return true; 8263 break; 8264 case lltok::kw_params: 8265 if (ParseOptionalParamAccesses(ParamAccesses)) 8266 return true; 8267 break; 8268 default: 8269 return Error(Lex.getLoc(), "expected optional function summary field"); 8270 } 8271 } 8272 8273 if (ParseToken(lltok::rparen, "expected ')' here")) 8274 return true; 8275 8276 auto FS = std::make_unique<FunctionSummary>( 8277 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8278 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8279 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8280 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8281 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8282 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8283 std::move(ParamAccesses)); 8284 8285 FS->setModulePath(ModulePath); 8286 8287 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8288 ID, std::move(FS)); 8289 8290 return false; 8291 } 8292 8293 /// VariableSummary 8294 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8295 /// [',' OptionalRefs]? ')' 8296 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8297 unsigned ID) { 8298 assert(Lex.getKind() == lltok::kw_variable); 8299 Lex.Lex(); 8300 8301 StringRef ModulePath; 8302 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8303 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8304 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8305 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8306 /* WriteOnly */ false, 8307 /* Constant */ false, 8308 GlobalObject::VCallVisibilityPublic); 8309 std::vector<ValueInfo> Refs; 8310 VTableFuncList VTableFuncs; 8311 if (ParseToken(lltok::colon, "expected ':' here") || 8312 ParseToken(lltok::lparen, "expected '(' here") || 8313 ParseModuleReference(ModulePath) || 8314 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8315 ParseToken(lltok::comma, "expected ',' here") || 8316 ParseGVarFlags(GVarFlags)) 8317 return true; 8318 8319 // Parse optional fields 8320 while (EatIfPresent(lltok::comma)) { 8321 switch (Lex.getKind()) { 8322 case lltok::kw_vTableFuncs: 8323 if (ParseOptionalVTableFuncs(VTableFuncs)) 8324 return true; 8325 break; 8326 case lltok::kw_refs: 8327 if (ParseOptionalRefs(Refs)) 8328 return true; 8329 break; 8330 default: 8331 return Error(Lex.getLoc(), "expected optional variable summary field"); 8332 } 8333 } 8334 8335 if (ParseToken(lltok::rparen, "expected ')' here")) 8336 return true; 8337 8338 auto GS = 8339 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8340 8341 GS->setModulePath(ModulePath); 8342 GS->setVTableFuncs(std::move(VTableFuncs)); 8343 8344 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8345 ID, std::move(GS)); 8346 8347 return false; 8348 } 8349 8350 /// AliasSummary 8351 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8352 /// 'aliasee' ':' GVReference ')' 8353 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8354 unsigned ID) { 8355 assert(Lex.getKind() == lltok::kw_alias); 8356 LocTy Loc = Lex.getLoc(); 8357 Lex.Lex(); 8358 8359 StringRef ModulePath; 8360 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8361 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8362 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8363 if (ParseToken(lltok::colon, "expected ':' here") || 8364 ParseToken(lltok::lparen, "expected '(' here") || 8365 ParseModuleReference(ModulePath) || 8366 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8367 ParseToken(lltok::comma, "expected ',' here") || 8368 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8369 ParseToken(lltok::colon, "expected ':' here")) 8370 return true; 8371 8372 ValueInfo AliaseeVI; 8373 unsigned GVId; 8374 if (ParseGVReference(AliaseeVI, GVId)) 8375 return true; 8376 8377 if (ParseToken(lltok::rparen, "expected ')' here")) 8378 return true; 8379 8380 auto AS = std::make_unique<AliasSummary>(GVFlags); 8381 8382 AS->setModulePath(ModulePath); 8383 8384 // Record forward reference if the aliasee is not parsed yet. 8385 if (AliaseeVI.getRef() == FwdVIRef) { 8386 auto FwdRef = ForwardRefAliasees.insert( 8387 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>())); 8388 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc)); 8389 } else { 8390 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8391 assert(Summary && "Aliasee must be a definition"); 8392 AS->setAliasee(AliaseeVI, Summary); 8393 } 8394 8395 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8396 ID, std::move(AS)); 8397 8398 return false; 8399 } 8400 8401 /// Flag 8402 /// ::= [0|1] 8403 bool LLParser::ParseFlag(unsigned &Val) { 8404 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8405 return TokError("expected integer"); 8406 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8407 Lex.Lex(); 8408 return false; 8409 } 8410 8411 /// OptionalFFlags 8412 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8413 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8414 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8415 /// [',' 'noInline' ':' Flag]? ')' 8416 /// [',' 'alwaysInline' ':' Flag]? ')' 8417 8418 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8419 assert(Lex.getKind() == lltok::kw_funcFlags); 8420 Lex.Lex(); 8421 8422 if (ParseToken(lltok::colon, "expected ':' in funcFlags") | 8423 ParseToken(lltok::lparen, "expected '(' in funcFlags")) 8424 return true; 8425 8426 do { 8427 unsigned Val = 0; 8428 switch (Lex.getKind()) { 8429 case lltok::kw_readNone: 8430 Lex.Lex(); 8431 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8432 return true; 8433 FFlags.ReadNone = Val; 8434 break; 8435 case lltok::kw_readOnly: 8436 Lex.Lex(); 8437 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8438 return true; 8439 FFlags.ReadOnly = Val; 8440 break; 8441 case lltok::kw_noRecurse: 8442 Lex.Lex(); 8443 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8444 return true; 8445 FFlags.NoRecurse = Val; 8446 break; 8447 case lltok::kw_returnDoesNotAlias: 8448 Lex.Lex(); 8449 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8450 return true; 8451 FFlags.ReturnDoesNotAlias = Val; 8452 break; 8453 case lltok::kw_noInline: 8454 Lex.Lex(); 8455 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8456 return true; 8457 FFlags.NoInline = Val; 8458 break; 8459 case lltok::kw_alwaysInline: 8460 Lex.Lex(); 8461 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8462 return true; 8463 FFlags.AlwaysInline = Val; 8464 break; 8465 default: 8466 return Error(Lex.getLoc(), "expected function flag type"); 8467 } 8468 } while (EatIfPresent(lltok::comma)); 8469 8470 if (ParseToken(lltok::rparen, "expected ')' in funcFlags")) 8471 return true; 8472 8473 return false; 8474 } 8475 8476 /// OptionalCalls 8477 /// := 'calls' ':' '(' Call [',' Call]* ')' 8478 /// Call ::= '(' 'callee' ':' GVReference 8479 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8480 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8481 assert(Lex.getKind() == lltok::kw_calls); 8482 Lex.Lex(); 8483 8484 if (ParseToken(lltok::colon, "expected ':' in calls") | 8485 ParseToken(lltok::lparen, "expected '(' in calls")) 8486 return true; 8487 8488 IdToIndexMapType IdToIndexMap; 8489 // Parse each call edge 8490 do { 8491 ValueInfo VI; 8492 if (ParseToken(lltok::lparen, "expected '(' in call") || 8493 ParseToken(lltok::kw_callee, "expected 'callee' in call") || 8494 ParseToken(lltok::colon, "expected ':'")) 8495 return true; 8496 8497 LocTy Loc = Lex.getLoc(); 8498 unsigned GVId; 8499 if (ParseGVReference(VI, GVId)) 8500 return true; 8501 8502 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8503 unsigned RelBF = 0; 8504 if (EatIfPresent(lltok::comma)) { 8505 // Expect either hotness or relbf 8506 if (EatIfPresent(lltok::kw_hotness)) { 8507 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness)) 8508 return true; 8509 } else { 8510 if (ParseToken(lltok::kw_relbf, "expected relbf") || 8511 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF)) 8512 return true; 8513 } 8514 } 8515 // Keep track of the Call array index needing a forward reference. 8516 // We will save the location of the ValueInfo needing an update, but 8517 // can only do so once the std::vector is finalized. 8518 if (VI.getRef() == FwdVIRef) 8519 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8520 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8521 8522 if (ParseToken(lltok::rparen, "expected ')' in call")) 8523 return true; 8524 } while (EatIfPresent(lltok::comma)); 8525 8526 // Now that the Calls vector is finalized, it is safe to save the locations 8527 // of any forward GV references that need updating later. 8528 for (auto I : IdToIndexMap) { 8529 for (auto P : I.second) { 8530 assert(Calls[P.first].first.getRef() == FwdVIRef && 8531 "Forward referenced ValueInfo expected to be empty"); 8532 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8533 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8534 FwdRef.first->second.push_back( 8535 std::make_pair(&Calls[P.first].first, P.second)); 8536 } 8537 } 8538 8539 if (ParseToken(lltok::rparen, "expected ')' in calls")) 8540 return true; 8541 8542 return false; 8543 } 8544 8545 /// Hotness 8546 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8547 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) { 8548 switch (Lex.getKind()) { 8549 case lltok::kw_unknown: 8550 Hotness = CalleeInfo::HotnessType::Unknown; 8551 break; 8552 case lltok::kw_cold: 8553 Hotness = CalleeInfo::HotnessType::Cold; 8554 break; 8555 case lltok::kw_none: 8556 Hotness = CalleeInfo::HotnessType::None; 8557 break; 8558 case lltok::kw_hot: 8559 Hotness = CalleeInfo::HotnessType::Hot; 8560 break; 8561 case lltok::kw_critical: 8562 Hotness = CalleeInfo::HotnessType::Critical; 8563 break; 8564 default: 8565 return Error(Lex.getLoc(), "invalid call edge hotness"); 8566 } 8567 Lex.Lex(); 8568 return false; 8569 } 8570 8571 /// OptionalVTableFuncs 8572 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8573 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8574 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8575 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8576 Lex.Lex(); 8577 8578 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") | 8579 ParseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8580 return true; 8581 8582 IdToIndexMapType IdToIndexMap; 8583 // Parse each virtual function pair 8584 do { 8585 ValueInfo VI; 8586 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") || 8587 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8588 ParseToken(lltok::colon, "expected ':'")) 8589 return true; 8590 8591 LocTy Loc = Lex.getLoc(); 8592 unsigned GVId; 8593 if (ParseGVReference(VI, GVId)) 8594 return true; 8595 8596 uint64_t Offset; 8597 if (ParseToken(lltok::comma, "expected comma") || 8598 ParseToken(lltok::kw_offset, "expected offset") || 8599 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset)) 8600 return true; 8601 8602 // Keep track of the VTableFuncs array index needing a forward reference. 8603 // We will save the location of the ValueInfo needing an update, but 8604 // can only do so once the std::vector is finalized. 8605 if (VI == EmptyVI) 8606 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8607 VTableFuncs.push_back({VI, Offset}); 8608 8609 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc")) 8610 return true; 8611 } while (EatIfPresent(lltok::comma)); 8612 8613 // Now that the VTableFuncs vector is finalized, it is safe to save the 8614 // locations of any forward GV references that need updating later. 8615 for (auto I : IdToIndexMap) { 8616 for (auto P : I.second) { 8617 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8618 "Forward referenced ValueInfo expected to be empty"); 8619 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8620 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8621 FwdRef.first->second.push_back( 8622 std::make_pair(&VTableFuncs[P.first].FuncVI, P.second)); 8623 } 8624 } 8625 8626 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8627 return true; 8628 8629 return false; 8630 } 8631 8632 /// ParamNo := 'param' ':' UInt64 8633 bool LLParser::ParseParamNo(uint64_t &ParamNo) { 8634 if (ParseToken(lltok::kw_param, "expected 'param' here") || 8635 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(ParamNo)) 8636 return true; 8637 return false; 8638 } 8639 8640 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8641 bool LLParser::ParseParamAccessOffset(ConstantRange &Range) { 8642 APSInt Lower; 8643 APSInt Upper; 8644 auto ParseAPSInt = [&](APSInt &Val) { 8645 if (Lex.getKind() != lltok::APSInt) 8646 return TokError("expected integer"); 8647 Val = Lex.getAPSIntVal(); 8648 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8649 Val.setIsSigned(true); 8650 Lex.Lex(); 8651 return false; 8652 }; 8653 if (ParseToken(lltok::kw_offset, "expected 'offset' here") || 8654 ParseToken(lltok::colon, "expected ':' here") || 8655 ParseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8656 ParseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8657 ParseToken(lltok::rsquare, "expected ']' here")) 8658 return true; 8659 8660 ++Upper; 8661 Range = 8662 (Lower == Upper && !Lower.isMaxValue()) 8663 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8664 : ConstantRange(Lower, Upper); 8665 8666 return false; 8667 } 8668 8669 /// ParamAccessCall 8670 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8671 bool LLParser::ParseParamAccessCall(FunctionSummary::ParamAccess::Call &Call) { 8672 if (ParseToken(lltok::lparen, "expected '(' here") || 8673 ParseToken(lltok::kw_callee, "expected 'callee' here") || 8674 ParseToken(lltok::colon, "expected ':' here")) 8675 return true; 8676 8677 unsigned GVId; 8678 ValueInfo VI; 8679 if (ParseGVReference(VI, GVId)) 8680 return true; 8681 8682 Call.Callee = VI.getGUID(); 8683 8684 if (ParseToken(lltok::comma, "expected ',' here") || 8685 ParseParamNo(Call.ParamNo) || 8686 ParseToken(lltok::comma, "expected ',' here") || 8687 ParseParamAccessOffset(Call.Offsets)) 8688 return true; 8689 8690 if (ParseToken(lltok::rparen, "expected ')' here")) 8691 return true; 8692 8693 return false; 8694 } 8695 8696 /// ParamAccess 8697 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8698 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8699 bool LLParser::ParseParamAccess(FunctionSummary::ParamAccess &Param) { 8700 if (ParseToken(lltok::lparen, "expected '(' here") || 8701 ParseParamNo(Param.ParamNo) || 8702 ParseToken(lltok::comma, "expected ',' here") || 8703 ParseParamAccessOffset(Param.Use)) 8704 return true; 8705 8706 if (EatIfPresent(lltok::comma)) { 8707 if (ParseToken(lltok::kw_calls, "expected 'calls' here") || 8708 ParseToken(lltok::colon, "expected ':' here") || 8709 ParseToken(lltok::lparen, "expected '(' here")) 8710 return true; 8711 do { 8712 FunctionSummary::ParamAccess::Call Call; 8713 if (ParseParamAccessCall(Call)) 8714 return true; 8715 Param.Calls.push_back(Call); 8716 } while (EatIfPresent(lltok::comma)); 8717 8718 if (ParseToken(lltok::rparen, "expected ')' here")) 8719 return true; 8720 } 8721 8722 if (ParseToken(lltok::rparen, "expected ')' here")) 8723 return true; 8724 8725 return false; 8726 } 8727 8728 /// OptionalParamAccesses 8729 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8730 bool LLParser::ParseOptionalParamAccesses( 8731 std::vector<FunctionSummary::ParamAccess> &Params) { 8732 assert(Lex.getKind() == lltok::kw_params); 8733 Lex.Lex(); 8734 8735 if (ParseToken(lltok::colon, "expected ':' here") || 8736 ParseToken(lltok::lparen, "expected '(' here")) 8737 return true; 8738 8739 do { 8740 FunctionSummary::ParamAccess ParamAccess; 8741 if (ParseParamAccess(ParamAccess)) 8742 return true; 8743 Params.push_back(ParamAccess); 8744 } while (EatIfPresent(lltok::comma)); 8745 8746 if (ParseToken(lltok::rparen, "expected ')' here")) 8747 return true; 8748 8749 return false; 8750 } 8751 8752 /// OptionalRefs 8753 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 8754 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) { 8755 assert(Lex.getKind() == lltok::kw_refs); 8756 Lex.Lex(); 8757 8758 if (ParseToken(lltok::colon, "expected ':' in refs") || 8759 ParseToken(lltok::lparen, "expected '(' in refs")) 8760 return true; 8761 8762 struct ValueContext { 8763 ValueInfo VI; 8764 unsigned GVId; 8765 LocTy Loc; 8766 }; 8767 std::vector<ValueContext> VContexts; 8768 // Parse each ref edge 8769 do { 8770 ValueContext VC; 8771 VC.Loc = Lex.getLoc(); 8772 if (ParseGVReference(VC.VI, VC.GVId)) 8773 return true; 8774 VContexts.push_back(VC); 8775 } while (EatIfPresent(lltok::comma)); 8776 8777 // Sort value contexts so that ones with writeonly 8778 // and readonly ValueInfo are at the end of VContexts vector. 8779 // See FunctionSummary::specialRefCounts() 8780 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 8781 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 8782 }); 8783 8784 IdToIndexMapType IdToIndexMap; 8785 for (auto &VC : VContexts) { 8786 // Keep track of the Refs array index needing a forward reference. 8787 // We will save the location of the ValueInfo needing an update, but 8788 // can only do so once the std::vector is finalized. 8789 if (VC.VI.getRef() == FwdVIRef) 8790 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 8791 Refs.push_back(VC.VI); 8792 } 8793 8794 // Now that the Refs vector is finalized, it is safe to save the locations 8795 // of any forward GV references that need updating later. 8796 for (auto I : IdToIndexMap) { 8797 for (auto P : I.second) { 8798 assert(Refs[P.first].getRef() == FwdVIRef && 8799 "Forward referenced ValueInfo expected to be empty"); 8800 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8801 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8802 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second)); 8803 } 8804 } 8805 8806 if (ParseToken(lltok::rparen, "expected ')' in refs")) 8807 return true; 8808 8809 return false; 8810 } 8811 8812 /// OptionalTypeIdInfo 8813 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 8814 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 8815 /// [',' TypeCheckedLoadConstVCalls]? ')' 8816 bool LLParser::ParseOptionalTypeIdInfo( 8817 FunctionSummary::TypeIdInfo &TypeIdInfo) { 8818 assert(Lex.getKind() == lltok::kw_typeIdInfo); 8819 Lex.Lex(); 8820 8821 if (ParseToken(lltok::colon, "expected ':' here") || 8822 ParseToken(lltok::lparen, "expected '(' in typeIdInfo")) 8823 return true; 8824 8825 do { 8826 switch (Lex.getKind()) { 8827 case lltok::kw_typeTests: 8828 if (ParseTypeTests(TypeIdInfo.TypeTests)) 8829 return true; 8830 break; 8831 case lltok::kw_typeTestAssumeVCalls: 8832 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 8833 TypeIdInfo.TypeTestAssumeVCalls)) 8834 return true; 8835 break; 8836 case lltok::kw_typeCheckedLoadVCalls: 8837 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 8838 TypeIdInfo.TypeCheckedLoadVCalls)) 8839 return true; 8840 break; 8841 case lltok::kw_typeTestAssumeConstVCalls: 8842 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 8843 TypeIdInfo.TypeTestAssumeConstVCalls)) 8844 return true; 8845 break; 8846 case lltok::kw_typeCheckedLoadConstVCalls: 8847 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 8848 TypeIdInfo.TypeCheckedLoadConstVCalls)) 8849 return true; 8850 break; 8851 default: 8852 return Error(Lex.getLoc(), "invalid typeIdInfo list type"); 8853 } 8854 } while (EatIfPresent(lltok::comma)); 8855 8856 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo")) 8857 return true; 8858 8859 return false; 8860 } 8861 8862 /// TypeTests 8863 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 8864 /// [',' (SummaryID | UInt64)]* ')' 8865 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 8866 assert(Lex.getKind() == lltok::kw_typeTests); 8867 Lex.Lex(); 8868 8869 if (ParseToken(lltok::colon, "expected ':' here") || 8870 ParseToken(lltok::lparen, "expected '(' in typeIdInfo")) 8871 return true; 8872 8873 IdToIndexMapType IdToIndexMap; 8874 do { 8875 GlobalValue::GUID GUID = 0; 8876 if (Lex.getKind() == lltok::SummaryID) { 8877 unsigned ID = Lex.getUIntVal(); 8878 LocTy Loc = Lex.getLoc(); 8879 // Keep track of the TypeTests array index needing a forward reference. 8880 // We will save the location of the GUID needing an update, but 8881 // can only do so once the std::vector is finalized. 8882 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 8883 Lex.Lex(); 8884 } else if (ParseUInt64(GUID)) 8885 return true; 8886 TypeTests.push_back(GUID); 8887 } while (EatIfPresent(lltok::comma)); 8888 8889 // Now that the TypeTests vector is finalized, it is safe to save the 8890 // locations of any forward GV references that need updating later. 8891 for (auto I : IdToIndexMap) { 8892 for (auto P : I.second) { 8893 assert(TypeTests[P.first] == 0 && 8894 "Forward referenced type id GUID expected to be 0"); 8895 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8896 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8897 FwdRef.first->second.push_back( 8898 std::make_pair(&TypeTests[P.first], P.second)); 8899 } 8900 } 8901 8902 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo")) 8903 return true; 8904 8905 return false; 8906 } 8907 8908 /// VFuncIdList 8909 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 8910 bool LLParser::ParseVFuncIdList( 8911 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 8912 assert(Lex.getKind() == Kind); 8913 Lex.Lex(); 8914 8915 if (ParseToken(lltok::colon, "expected ':' here") || 8916 ParseToken(lltok::lparen, "expected '(' here")) 8917 return true; 8918 8919 IdToIndexMapType IdToIndexMap; 8920 do { 8921 FunctionSummary::VFuncId VFuncId; 8922 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 8923 return true; 8924 VFuncIdList.push_back(VFuncId); 8925 } while (EatIfPresent(lltok::comma)); 8926 8927 if (ParseToken(lltok::rparen, "expected ')' here")) 8928 return true; 8929 8930 // Now that the VFuncIdList vector is finalized, it is safe to save the 8931 // locations of any forward GV references that need updating later. 8932 for (auto I : IdToIndexMap) { 8933 for (auto P : I.second) { 8934 assert(VFuncIdList[P.first].GUID == 0 && 8935 "Forward referenced type id GUID expected to be 0"); 8936 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8937 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8938 FwdRef.first->second.push_back( 8939 std::make_pair(&VFuncIdList[P.first].GUID, P.second)); 8940 } 8941 } 8942 8943 return false; 8944 } 8945 8946 /// ConstVCallList 8947 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 8948 bool LLParser::ParseConstVCallList( 8949 lltok::Kind Kind, 8950 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 8951 assert(Lex.getKind() == Kind); 8952 Lex.Lex(); 8953 8954 if (ParseToken(lltok::colon, "expected ':' here") || 8955 ParseToken(lltok::lparen, "expected '(' here")) 8956 return true; 8957 8958 IdToIndexMapType IdToIndexMap; 8959 do { 8960 FunctionSummary::ConstVCall ConstVCall; 8961 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 8962 return true; 8963 ConstVCallList.push_back(ConstVCall); 8964 } while (EatIfPresent(lltok::comma)); 8965 8966 if (ParseToken(lltok::rparen, "expected ')' here")) 8967 return true; 8968 8969 // Now that the ConstVCallList vector is finalized, it is safe to save the 8970 // locations of any forward GV references that need updating later. 8971 for (auto I : IdToIndexMap) { 8972 for (auto P : I.second) { 8973 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 8974 "Forward referenced type id GUID expected to be 0"); 8975 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8976 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8977 FwdRef.first->second.push_back( 8978 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second)); 8979 } 8980 } 8981 8982 return false; 8983 } 8984 8985 /// ConstVCall 8986 /// ::= '(' VFuncId ',' Args ')' 8987 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 8988 IdToIndexMapType &IdToIndexMap, unsigned Index) { 8989 if (ParseToken(lltok::lparen, "expected '(' here") || 8990 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 8991 return true; 8992 8993 if (EatIfPresent(lltok::comma)) 8994 if (ParseArgs(ConstVCall.Args)) 8995 return true; 8996 8997 if (ParseToken(lltok::rparen, "expected ')' here")) 8998 return true; 8999 9000 return false; 9001 } 9002 9003 /// VFuncId 9004 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9005 /// 'offset' ':' UInt64 ')' 9006 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId, 9007 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9008 assert(Lex.getKind() == lltok::kw_vFuncId); 9009 Lex.Lex(); 9010 9011 if (ParseToken(lltok::colon, "expected ':' here") || 9012 ParseToken(lltok::lparen, "expected '(' here")) 9013 return true; 9014 9015 if (Lex.getKind() == lltok::SummaryID) { 9016 VFuncId.GUID = 0; 9017 unsigned ID = Lex.getUIntVal(); 9018 LocTy Loc = Lex.getLoc(); 9019 // Keep track of the array index needing a forward reference. 9020 // We will save the location of the GUID needing an update, but 9021 // can only do so once the caller's std::vector is finalized. 9022 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9023 Lex.Lex(); 9024 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") || 9025 ParseToken(lltok::colon, "expected ':' here") || 9026 ParseUInt64(VFuncId.GUID)) 9027 return true; 9028 9029 if (ParseToken(lltok::comma, "expected ',' here") || 9030 ParseToken(lltok::kw_offset, "expected 'offset' here") || 9031 ParseToken(lltok::colon, "expected ':' here") || 9032 ParseUInt64(VFuncId.Offset) || 9033 ParseToken(lltok::rparen, "expected ')' here")) 9034 return true; 9035 9036 return false; 9037 } 9038 9039 /// GVFlags 9040 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9041 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ',' 9042 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')' 9043 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9044 assert(Lex.getKind() == lltok::kw_flags); 9045 Lex.Lex(); 9046 9047 if (ParseToken(lltok::colon, "expected ':' here") || 9048 ParseToken(lltok::lparen, "expected '(' here")) 9049 return true; 9050 9051 do { 9052 unsigned Flag = 0; 9053 switch (Lex.getKind()) { 9054 case lltok::kw_linkage: 9055 Lex.Lex(); 9056 if (ParseToken(lltok::colon, "expected ':'")) 9057 return true; 9058 bool HasLinkage; 9059 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9060 assert(HasLinkage && "Linkage not optional in summary entry"); 9061 Lex.Lex(); 9062 break; 9063 case lltok::kw_notEligibleToImport: 9064 Lex.Lex(); 9065 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 9066 return true; 9067 GVFlags.NotEligibleToImport = Flag; 9068 break; 9069 case lltok::kw_live: 9070 Lex.Lex(); 9071 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 9072 return true; 9073 GVFlags.Live = Flag; 9074 break; 9075 case lltok::kw_dsoLocal: 9076 Lex.Lex(); 9077 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 9078 return true; 9079 GVFlags.DSOLocal = Flag; 9080 break; 9081 case lltok::kw_canAutoHide: 9082 Lex.Lex(); 9083 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 9084 return true; 9085 GVFlags.CanAutoHide = Flag; 9086 break; 9087 default: 9088 return Error(Lex.getLoc(), "expected gv flag type"); 9089 } 9090 } while (EatIfPresent(lltok::comma)); 9091 9092 if (ParseToken(lltok::rparen, "expected ')' here")) 9093 return true; 9094 9095 return false; 9096 } 9097 9098 /// GVarFlags 9099 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9100 /// ',' 'writeonly' ':' Flag 9101 /// ',' 'constant' ':' Flag ')' 9102 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9103 assert(Lex.getKind() == lltok::kw_varFlags); 9104 Lex.Lex(); 9105 9106 if (ParseToken(lltok::colon, "expected ':' here") || 9107 ParseToken(lltok::lparen, "expected '(' here")) 9108 return true; 9109 9110 auto ParseRest = [this](unsigned int &Val) { 9111 Lex.Lex(); 9112 if (ParseToken(lltok::colon, "expected ':'")) 9113 return true; 9114 return ParseFlag(Val); 9115 }; 9116 9117 do { 9118 unsigned Flag = 0; 9119 switch (Lex.getKind()) { 9120 case lltok::kw_readonly: 9121 if (ParseRest(Flag)) 9122 return true; 9123 GVarFlags.MaybeReadOnly = Flag; 9124 break; 9125 case lltok::kw_writeonly: 9126 if (ParseRest(Flag)) 9127 return true; 9128 GVarFlags.MaybeWriteOnly = Flag; 9129 break; 9130 case lltok::kw_constant: 9131 if (ParseRest(Flag)) 9132 return true; 9133 GVarFlags.Constant = Flag; 9134 break; 9135 case lltok::kw_vcall_visibility: 9136 if (ParseRest(Flag)) 9137 return true; 9138 GVarFlags.VCallVisibility = Flag; 9139 break; 9140 default: 9141 return Error(Lex.getLoc(), "expected gvar flag type"); 9142 } 9143 } while (EatIfPresent(lltok::comma)); 9144 return ParseToken(lltok::rparen, "expected ')' here"); 9145 } 9146 9147 /// ModuleReference 9148 /// ::= 'module' ':' UInt 9149 bool LLParser::ParseModuleReference(StringRef &ModulePath) { 9150 // Parse module id. 9151 if (ParseToken(lltok::kw_module, "expected 'module' here") || 9152 ParseToken(lltok::colon, "expected ':' here") || 9153 ParseToken(lltok::SummaryID, "expected module ID")) 9154 return true; 9155 9156 unsigned ModuleID = Lex.getUIntVal(); 9157 auto I = ModuleIdMap.find(ModuleID); 9158 // We should have already parsed all module IDs 9159 assert(I != ModuleIdMap.end()); 9160 ModulePath = I->second; 9161 return false; 9162 } 9163 9164 /// GVReference 9165 /// ::= SummaryID 9166 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) { 9167 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9168 if (!ReadOnly) 9169 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9170 if (ParseToken(lltok::SummaryID, "expected GV ID")) 9171 return true; 9172 9173 GVId = Lex.getUIntVal(); 9174 // Check if we already have a VI for this GV 9175 if (GVId < NumberedValueInfos.size()) { 9176 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9177 VI = NumberedValueInfos[GVId]; 9178 } else 9179 // We will create a forward reference to the stored location. 9180 VI = ValueInfo(false, FwdVIRef); 9181 9182 if (ReadOnly) 9183 VI.setReadOnly(); 9184 if (WriteOnly) 9185 VI.setWriteOnly(); 9186 return false; 9187 } 9188