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