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