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