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