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