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