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