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