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