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