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