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