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