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