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