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