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