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