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