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