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