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