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