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