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