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