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