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