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/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_linker_private: // OptionalLinkage 250 case lltok::kw_linker_private_weak: // OptionalLinkage 251 case lltok::kw_internal: // OptionalLinkage 252 case lltok::kw_weak: // OptionalLinkage 253 case lltok::kw_weak_odr: // OptionalLinkage 254 case lltok::kw_linkonce: // OptionalLinkage 255 case lltok::kw_linkonce_odr: // OptionalLinkage 256 case lltok::kw_appending: // OptionalLinkage 257 case lltok::kw_common: // OptionalLinkage 258 case lltok::kw_extern_weak: // OptionalLinkage 259 case lltok::kw_external: { // OptionalLinkage 260 unsigned Linkage, Visibility, DLLStorageClass; 261 if (ParseOptionalLinkage(Linkage) || 262 ParseOptionalVisibility(Visibility) || 263 ParseOptionalDLLStorageClass(DLLStorageClass) || 264 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass)) 265 return true; 266 break; 267 } 268 case lltok::kw_default: // OptionalVisibility 269 case lltok::kw_hidden: // OptionalVisibility 270 case lltok::kw_protected: { // OptionalVisibility 271 unsigned Visibility, DLLStorageClass; 272 if (ParseOptionalVisibility(Visibility) || 273 ParseOptionalDLLStorageClass(DLLStorageClass) || 274 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass)) 275 return true; 276 break; 277 } 278 279 case lltok::kw_thread_local: // OptionalThreadLocal 280 case lltok::kw_addrspace: // OptionalAddrSpace 281 case lltok::kw_constant: // GlobalType 282 case lltok::kw_global: // GlobalType 283 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true; 284 break; 285 286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break; 287 } 288 } 289 } 290 291 292 /// toplevelentity 293 /// ::= 'module' 'asm' STRINGCONSTANT 294 bool LLParser::ParseModuleAsm() { 295 assert(Lex.getKind() == lltok::kw_module); 296 Lex.Lex(); 297 298 std::string AsmStr; 299 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 300 ParseStringConstant(AsmStr)) return true; 301 302 M->appendModuleInlineAsm(AsmStr); 303 return false; 304 } 305 306 /// toplevelentity 307 /// ::= 'target' 'triple' '=' STRINGCONSTANT 308 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 309 bool LLParser::ParseTargetDefinition() { 310 assert(Lex.getKind() == lltok::kw_target); 311 std::string Str; 312 switch (Lex.Lex()) { 313 default: return TokError("unknown target property"); 314 case lltok::kw_triple: 315 Lex.Lex(); 316 if (ParseToken(lltok::equal, "expected '=' after target triple") || 317 ParseStringConstant(Str)) 318 return true; 319 M->setTargetTriple(Str); 320 return false; 321 case lltok::kw_datalayout: 322 Lex.Lex(); 323 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 324 ParseStringConstant(Str)) 325 return true; 326 M->setDataLayout(Str); 327 return false; 328 } 329 } 330 331 /// toplevelentity 332 /// ::= 'deplibs' '=' '[' ']' 333 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 334 /// FIXME: Remove in 4.0. Currently parse, but ignore. 335 bool LLParser::ParseDepLibs() { 336 assert(Lex.getKind() == lltok::kw_deplibs); 337 Lex.Lex(); 338 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 339 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 340 return true; 341 342 if (EatIfPresent(lltok::rsquare)) 343 return false; 344 345 do { 346 std::string Str; 347 if (ParseStringConstant(Str)) return true; 348 } while (EatIfPresent(lltok::comma)); 349 350 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 351 } 352 353 /// ParseUnnamedType: 354 /// ::= LocalVarID '=' 'type' type 355 bool LLParser::ParseUnnamedType() { 356 LocTy TypeLoc = Lex.getLoc(); 357 unsigned TypeID = Lex.getUIntVal(); 358 Lex.Lex(); // eat LocalVarID; 359 360 if (ParseToken(lltok::equal, "expected '=' after name") || 361 ParseToken(lltok::kw_type, "expected 'type' after '='")) 362 return true; 363 364 if (TypeID >= NumberedTypes.size()) 365 NumberedTypes.resize(TypeID+1); 366 367 Type *Result = 0; 368 if (ParseStructDefinition(TypeLoc, "", 369 NumberedTypes[TypeID], Result)) return true; 370 371 if (!isa<StructType>(Result)) { 372 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 373 if (Entry.first) 374 return Error(TypeLoc, "non-struct types may not be recursive"); 375 Entry.first = Result; 376 Entry.second = SMLoc(); 377 } 378 379 return false; 380 } 381 382 383 /// toplevelentity 384 /// ::= LocalVar '=' 'type' type 385 bool LLParser::ParseNamedType() { 386 std::string Name = Lex.getStrVal(); 387 LocTy NameLoc = Lex.getLoc(); 388 Lex.Lex(); // eat LocalVar. 389 390 if (ParseToken(lltok::equal, "expected '=' after name") || 391 ParseToken(lltok::kw_type, "expected 'type' after name")) 392 return true; 393 394 Type *Result = 0; 395 if (ParseStructDefinition(NameLoc, Name, 396 NamedTypes[Name], Result)) return true; 397 398 if (!isa<StructType>(Result)) { 399 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 400 if (Entry.first) 401 return Error(NameLoc, "non-struct types may not be recursive"); 402 Entry.first = Result; 403 Entry.second = SMLoc(); 404 } 405 406 return false; 407 } 408 409 410 /// toplevelentity 411 /// ::= 'declare' FunctionHeader 412 bool LLParser::ParseDeclare() { 413 assert(Lex.getKind() == lltok::kw_declare); 414 Lex.Lex(); 415 416 Function *F; 417 return ParseFunctionHeader(F, false); 418 } 419 420 /// toplevelentity 421 /// ::= 'define' FunctionHeader '{' ... 422 bool LLParser::ParseDefine() { 423 assert(Lex.getKind() == lltok::kw_define); 424 Lex.Lex(); 425 426 Function *F; 427 return ParseFunctionHeader(F, true) || 428 ParseFunctionBody(*F); 429 } 430 431 /// ParseGlobalType 432 /// ::= 'constant' 433 /// ::= 'global' 434 bool LLParser::ParseGlobalType(bool &IsConstant) { 435 if (Lex.getKind() == lltok::kw_constant) 436 IsConstant = true; 437 else if (Lex.getKind() == lltok::kw_global) 438 IsConstant = false; 439 else { 440 IsConstant = false; 441 return TokError("expected 'global' or 'constant'"); 442 } 443 Lex.Lex(); 444 return false; 445 } 446 447 /// ParseUnnamedGlobal: 448 /// OptionalVisibility ALIAS ... 449 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass 450 /// ... -> global variable 451 /// GlobalID '=' OptionalVisibility ALIAS ... 452 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 453 /// ... -> global variable 454 bool LLParser::ParseUnnamedGlobal() { 455 unsigned VarID = NumberedVals.size(); 456 std::string Name; 457 LocTy NameLoc = Lex.getLoc(); 458 459 // Handle the GlobalID form. 460 if (Lex.getKind() == lltok::GlobalID) { 461 if (Lex.getUIntVal() != VarID) 462 return Error(Lex.getLoc(), "variable expected to be numbered '%" + 463 Twine(VarID) + "'"); 464 Lex.Lex(); // eat GlobalID; 465 466 if (ParseToken(lltok::equal, "expected '=' after name")) 467 return true; 468 } 469 470 bool HasLinkage; 471 unsigned Linkage, Visibility, DLLStorageClass; 472 if (ParseOptionalLinkage(Linkage, HasLinkage) || 473 ParseOptionalVisibility(Visibility) || 474 ParseOptionalDLLStorageClass(DLLStorageClass)) 475 return true; 476 477 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 478 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 479 DLLStorageClass); 480 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass); 481 } 482 483 /// ParseNamedGlobal: 484 /// GlobalVar '=' OptionalVisibility ALIAS ... 485 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 486 /// ... -> global variable 487 bool LLParser::ParseNamedGlobal() { 488 assert(Lex.getKind() == lltok::GlobalVar); 489 LocTy NameLoc = Lex.getLoc(); 490 std::string Name = Lex.getStrVal(); 491 Lex.Lex(); 492 493 bool HasLinkage; 494 unsigned Linkage, Visibility, DLLStorageClass; 495 if (ParseToken(lltok::equal, "expected '=' in global variable") || 496 ParseOptionalLinkage(Linkage, HasLinkage) || 497 ParseOptionalVisibility(Visibility) || 498 ParseOptionalDLLStorageClass(DLLStorageClass)) 499 return true; 500 501 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 502 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 503 DLLStorageClass); 504 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass); 505 } 506 507 // MDString: 508 // ::= '!' STRINGCONSTANT 509 bool LLParser::ParseMDString(MDString *&Result) { 510 std::string Str; 511 if (ParseStringConstant(Str)) return true; 512 Result = MDString::get(Context, Str); 513 return false; 514 } 515 516 // MDNode: 517 // ::= '!' MDNodeNumber 518 // 519 /// This version of ParseMDNodeID returns the slot number and null in the case 520 /// of a forward reference. 521 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) { 522 // !{ ..., !42, ... } 523 if (ParseUInt32(SlotNo)) return true; 524 525 // Check existing MDNode. 526 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0) 527 Result = NumberedMetadata[SlotNo]; 528 else 529 Result = 0; 530 return false; 531 } 532 533 bool LLParser::ParseMDNodeID(MDNode *&Result) { 534 // !{ ..., !42, ... } 535 unsigned MID = 0; 536 if (ParseMDNodeID(Result, MID)) return true; 537 538 // If not a forward reference, just return it now. 539 if (Result) return false; 540 541 // Otherwise, create MDNode forward reference. 542 MDNode *FwdNode = MDNode::getTemporary(Context, None); 543 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); 544 545 if (NumberedMetadata.size() <= MID) 546 NumberedMetadata.resize(MID+1); 547 NumberedMetadata[MID] = FwdNode; 548 Result = FwdNode; 549 return false; 550 } 551 552 /// ParseNamedMetadata: 553 /// !foo = !{ !1, !2 } 554 bool LLParser::ParseNamedMetadata() { 555 assert(Lex.getKind() == lltok::MetadataVar); 556 std::string Name = Lex.getStrVal(); 557 Lex.Lex(); 558 559 if (ParseToken(lltok::equal, "expected '=' here") || 560 ParseToken(lltok::exclaim, "Expected '!' here") || 561 ParseToken(lltok::lbrace, "Expected '{' here")) 562 return true; 563 564 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 565 if (Lex.getKind() != lltok::rbrace) 566 do { 567 if (ParseToken(lltok::exclaim, "Expected '!' here")) 568 return true; 569 570 MDNode *N = 0; 571 if (ParseMDNodeID(N)) return true; 572 NMD->addOperand(N); 573 } while (EatIfPresent(lltok::comma)); 574 575 if (ParseToken(lltok::rbrace, "expected end of metadata node")) 576 return true; 577 578 return false; 579 } 580 581 /// ParseStandaloneMetadata: 582 /// !42 = !{...} 583 bool LLParser::ParseStandaloneMetadata() { 584 assert(Lex.getKind() == lltok::exclaim); 585 Lex.Lex(); 586 unsigned MetadataID = 0; 587 588 LocTy TyLoc; 589 Type *Ty = 0; 590 SmallVector<Value *, 16> Elts; 591 if (ParseUInt32(MetadataID) || 592 ParseToken(lltok::equal, "expected '=' here") || 593 ParseType(Ty, TyLoc) || 594 ParseToken(lltok::exclaim, "Expected '!' here") || 595 ParseToken(lltok::lbrace, "Expected '{' here") || 596 ParseMDNodeVector(Elts, NULL) || 597 ParseToken(lltok::rbrace, "expected end of metadata node")) 598 return true; 599 600 MDNode *Init = MDNode::get(Context, Elts); 601 602 // See if this was forward referenced, if so, handle it. 603 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator 604 FI = ForwardRefMDNodes.find(MetadataID); 605 if (FI != ForwardRefMDNodes.end()) { 606 MDNode *Temp = FI->second.first; 607 Temp->replaceAllUsesWith(Init); 608 MDNode::deleteTemporary(Temp); 609 ForwardRefMDNodes.erase(FI); 610 611 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 612 } else { 613 if (MetadataID >= NumberedMetadata.size()) 614 NumberedMetadata.resize(MetadataID+1); 615 616 if (NumberedMetadata[MetadataID] != 0) 617 return TokError("Metadata id is already used"); 618 NumberedMetadata[MetadataID] = Init; 619 } 620 621 return false; 622 } 623 624 /// ParseAlias: 625 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias' 626 /// OptionalLinkage Aliasee 627 /// Aliasee 628 /// ::= TypeAndValue 629 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')' 630 /// ::= 'getelementptr' 'inbounds'? '(' ... ')' 631 /// 632 /// Everything through DLL storage class has already been parsed. 633 /// 634 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, 635 unsigned Visibility, unsigned DLLStorageClass) { 636 assert(Lex.getKind() == lltok::kw_alias); 637 Lex.Lex(); 638 LocTy LinkageLoc = Lex.getLoc(); 639 unsigned L; 640 if (ParseOptionalLinkage(L)) 641 return true; 642 643 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; 644 645 if(!GlobalAlias::isValidLinkage(Linkage)) 646 return Error(LinkageLoc, "invalid linkage type for alias"); 647 648 Constant *Aliasee; 649 LocTy AliaseeLoc = Lex.getLoc(); 650 if (Lex.getKind() != lltok::kw_bitcast && 651 Lex.getKind() != lltok::kw_getelementptr) { 652 if (ParseGlobalTypeAndValue(Aliasee)) return true; 653 } else { 654 // The bitcast dest type is not present, it is implied by the dest type. 655 ValID ID; 656 if (ParseValID(ID)) return true; 657 if (ID.Kind != ValID::t_Constant) 658 return Error(AliaseeLoc, "invalid aliasee"); 659 Aliasee = ID.ConstantVal; 660 } 661 662 if (!Aliasee->getType()->isPointerTy()) 663 return Error(AliaseeLoc, "alias must have pointer type"); 664 665 // Okay, create the alias but do not insert it into the module yet. 666 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), 667 (GlobalValue::LinkageTypes)Linkage, Name, 668 Aliasee); 669 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 670 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 671 672 // See if this value already exists in the symbol table. If so, it is either 673 // a redefinition or a definition of a forward reference. 674 if (GlobalValue *Val = M->getNamedValue(Name)) { 675 // See if this was a redefinition. If so, there is no entry in 676 // ForwardRefVals. 677 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 678 I = ForwardRefVals.find(Name); 679 if (I == ForwardRefVals.end()) 680 return Error(NameLoc, "redefinition of global named '@" + Name + "'"); 681 682 // Otherwise, this was a definition of forward ref. Verify that types 683 // agree. 684 if (Val->getType() != GA->getType()) 685 return Error(NameLoc, 686 "forward reference and definition of alias have different types"); 687 688 // If they agree, just RAUW the old value with the alias and remove the 689 // forward ref info. 690 Val->replaceAllUsesWith(GA); 691 Val->eraseFromParent(); 692 ForwardRefVals.erase(I); 693 } 694 695 // Insert into the module, we know its name won't collide now. 696 M->getAliasList().push_back(GA); 697 assert(GA->getName() == Name && "Should not be a name conflict!"); 698 699 return false; 700 } 701 702 /// ParseGlobal 703 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 704 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr 705 /// OptionalExternallyInitialized GlobalType Type Const 706 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass 707 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr 708 /// OptionalExternallyInitialized GlobalType Type Const 709 /// 710 /// Everything through visibility has been parsed already. 711 /// 712 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 713 unsigned Linkage, bool HasLinkage, 714 unsigned Visibility, unsigned DLLStorageClass) { 715 unsigned AddrSpace; 716 bool IsConstant, UnnamedAddr, IsExternallyInitialized; 717 GlobalVariable::ThreadLocalMode TLM; 718 LocTy UnnamedAddrLoc; 719 LocTy IsExternallyInitializedLoc; 720 LocTy TyLoc; 721 722 Type *Ty = 0; 723 if (ParseOptionalThreadLocal(TLM) || 724 ParseOptionalAddrSpace(AddrSpace) || 725 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr, 726 &UnnamedAddrLoc) || 727 ParseOptionalToken(lltok::kw_externally_initialized, 728 IsExternallyInitialized, 729 &IsExternallyInitializedLoc) || 730 ParseGlobalType(IsConstant) || 731 ParseType(Ty, TyLoc)) 732 return true; 733 734 // If the linkage is specified and is external, then no initializer is 735 // present. 736 Constant *Init = 0; 737 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage && 738 Linkage != GlobalValue::ExternalLinkage)) { 739 if (ParseGlobalValue(Ty, Init)) 740 return true; 741 } 742 743 if (Ty->isFunctionTy() || Ty->isLabelTy()) 744 return Error(TyLoc, "invalid type for global variable"); 745 746 GlobalVariable *GV = 0; 747 748 // See if the global was forward referenced, if so, use the global. 749 if (!Name.empty()) { 750 if (GlobalValue *GVal = M->getNamedValue(Name)) { 751 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal)) 752 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 753 GV = cast<GlobalVariable>(GVal); 754 } 755 } else { 756 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 757 I = ForwardRefValIDs.find(NumberedVals.size()); 758 if (I != ForwardRefValIDs.end()) { 759 GV = cast<GlobalVariable>(I->second.first); 760 ForwardRefValIDs.erase(I); 761 } 762 } 763 764 if (GV == 0) { 765 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, 766 Name, 0, GlobalVariable::NotThreadLocal, 767 AddrSpace); 768 } else { 769 if (GV->getType()->getElementType() != Ty) 770 return Error(TyLoc, 771 "forward reference and definition of global have different types"); 772 773 // Move the forward-reference to the correct spot in the module. 774 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 775 } 776 777 if (Name.empty()) 778 NumberedVals.push_back(GV); 779 780 // Set the parsed properties on the global. 781 if (Init) 782 GV->setInitializer(Init); 783 GV->setConstant(IsConstant); 784 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 785 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 786 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 787 GV->setExternallyInitialized(IsExternallyInitialized); 788 GV->setThreadLocalMode(TLM); 789 GV->setUnnamedAddr(UnnamedAddr); 790 791 // Parse attributes on the global. 792 while (Lex.getKind() == lltok::comma) { 793 Lex.Lex(); 794 795 if (Lex.getKind() == lltok::kw_section) { 796 Lex.Lex(); 797 GV->setSection(Lex.getStrVal()); 798 if (ParseToken(lltok::StringConstant, "expected global section string")) 799 return true; 800 } else if (Lex.getKind() == lltok::kw_align) { 801 unsigned Alignment; 802 if (ParseOptionalAlignment(Alignment)) return true; 803 GV->setAlignment(Alignment); 804 } else { 805 TokError("unknown global variable property!"); 806 } 807 } 808 809 return false; 810 } 811 812 /// ParseUnnamedAttrGrp 813 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 814 bool LLParser::ParseUnnamedAttrGrp() { 815 assert(Lex.getKind() == lltok::kw_attributes); 816 LocTy AttrGrpLoc = Lex.getLoc(); 817 Lex.Lex(); 818 819 assert(Lex.getKind() == lltok::AttrGrpID); 820 unsigned VarID = Lex.getUIntVal(); 821 std::vector<unsigned> unused; 822 LocTy BuiltinLoc; 823 Lex.Lex(); 824 825 if (ParseToken(lltok::equal, "expected '=' here") || 826 ParseToken(lltok::lbrace, "expected '{' here") || 827 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true, 828 BuiltinLoc) || 829 ParseToken(lltok::rbrace, "expected end of attribute group")) 830 return true; 831 832 if (!NumberedAttrBuilders[VarID].hasAttributes()) 833 return Error(AttrGrpLoc, "attribute group has no attributes"); 834 835 return false; 836 } 837 838 /// ParseFnAttributeValuePairs 839 /// ::= <attr> | <attr> '=' <value> 840 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B, 841 std::vector<unsigned> &FwdRefAttrGrps, 842 bool inAttrGrp, LocTy &BuiltinLoc) { 843 bool HaveError = false; 844 845 B.clear(); 846 847 while (true) { 848 lltok::Kind Token = Lex.getKind(); 849 if (Token == lltok::kw_builtin) 850 BuiltinLoc = Lex.getLoc(); 851 switch (Token) { 852 default: 853 if (!inAttrGrp) return HaveError; 854 return Error(Lex.getLoc(), "unterminated attribute group"); 855 case lltok::rbrace: 856 // Finished. 857 return false; 858 859 case lltok::AttrGrpID: { 860 // Allow a function to reference an attribute group: 861 // 862 // define void @foo() #1 { ... } 863 if (inAttrGrp) 864 HaveError |= 865 Error(Lex.getLoc(), 866 "cannot have an attribute group reference in an attribute group"); 867 868 unsigned AttrGrpNum = Lex.getUIntVal(); 869 if (inAttrGrp) break; 870 871 // Save the reference to the attribute group. We'll fill it in later. 872 FwdRefAttrGrps.push_back(AttrGrpNum); 873 break; 874 } 875 // Target-dependent attributes: 876 case lltok::StringConstant: { 877 std::string Attr = Lex.getStrVal(); 878 Lex.Lex(); 879 std::string Val; 880 if (EatIfPresent(lltok::equal) && 881 ParseStringConstant(Val)) 882 return true; 883 884 B.addAttribute(Attr, Val); 885 continue; 886 } 887 888 // Target-independent attributes: 889 case lltok::kw_align: { 890 // As a hack, we allow function alignment to be initially parsed as an 891 // attribute on a function declaration/definition or added to an attribute 892 // group and later moved to the alignment field. 893 unsigned Alignment; 894 if (inAttrGrp) { 895 Lex.Lex(); 896 if (ParseToken(lltok::equal, "expected '=' here") || 897 ParseUInt32(Alignment)) 898 return true; 899 } else { 900 if (ParseOptionalAlignment(Alignment)) 901 return true; 902 } 903 B.addAlignmentAttr(Alignment); 904 continue; 905 } 906 case lltok::kw_alignstack: { 907 unsigned Alignment; 908 if (inAttrGrp) { 909 Lex.Lex(); 910 if (ParseToken(lltok::equal, "expected '=' here") || 911 ParseUInt32(Alignment)) 912 return true; 913 } else { 914 if (ParseOptionalStackAlignment(Alignment)) 915 return true; 916 } 917 B.addStackAlignmentAttr(Alignment); 918 continue; 919 } 920 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break; 921 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break; 922 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break; 923 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break; 924 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break; 925 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break; 926 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break; 927 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break; 928 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break; 929 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break; 930 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break; 931 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break; 932 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break; 933 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break; 934 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break; 935 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break; 936 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 937 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 938 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break; 939 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break; 940 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break; 941 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break; 942 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break; 943 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break; 944 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break; 945 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break; 946 947 // Error handling. 948 case lltok::kw_inreg: 949 case lltok::kw_signext: 950 case lltok::kw_zeroext: 951 HaveError |= 952 Error(Lex.getLoc(), 953 "invalid use of attribute on a function"); 954 break; 955 case lltok::kw_byval: 956 case lltok::kw_inalloca: 957 case lltok::kw_nest: 958 case lltok::kw_noalias: 959 case lltok::kw_nocapture: 960 case lltok::kw_returned: 961 case lltok::kw_sret: 962 HaveError |= 963 Error(Lex.getLoc(), 964 "invalid use of parameter-only attribute on a function"); 965 break; 966 } 967 968 Lex.Lex(); 969 } 970 } 971 972 //===----------------------------------------------------------------------===// 973 // GlobalValue Reference/Resolution Routines. 974 //===----------------------------------------------------------------------===// 975 976 /// GetGlobalVal - Get a value with the specified name or ID, creating a 977 /// forward reference record if needed. This can return null if the value 978 /// exists but does not have the right type. 979 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty, 980 LocTy Loc) { 981 PointerType *PTy = dyn_cast<PointerType>(Ty); 982 if (PTy == 0) { 983 Error(Loc, "global variable reference must have pointer type"); 984 return 0; 985 } 986 987 // Look this name up in the normal function symbol table. 988 GlobalValue *Val = 989 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 990 991 // If this is a forward reference for the value, see if we already created a 992 // forward ref record. 993 if (Val == 0) { 994 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 995 I = ForwardRefVals.find(Name); 996 if (I != ForwardRefVals.end()) 997 Val = I->second.first; 998 } 999 1000 // If we have the value in the symbol table or fwd-ref table, return it. 1001 if (Val) { 1002 if (Val->getType() == Ty) return Val; 1003 Error(Loc, "'@" + Name + "' defined with type '" + 1004 getTypeString(Val->getType()) + "'"); 1005 return 0; 1006 } 1007 1008 // Otherwise, create a new forward reference for this value and remember it. 1009 GlobalValue *FwdVal; 1010 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 1011 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 1012 else 1013 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 1014 GlobalValue::ExternalWeakLinkage, 0, Name, 1015 0, GlobalVariable::NotThreadLocal, 1016 PTy->getAddressSpace()); 1017 1018 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1019 return FwdVal; 1020 } 1021 1022 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 1023 PointerType *PTy = dyn_cast<PointerType>(Ty); 1024 if (PTy == 0) { 1025 Error(Loc, "global variable reference must have pointer type"); 1026 return 0; 1027 } 1028 1029 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 1030 1031 // If this is a forward reference for the value, see if we already created a 1032 // forward ref record. 1033 if (Val == 0) { 1034 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 1035 I = ForwardRefValIDs.find(ID); 1036 if (I != ForwardRefValIDs.end()) 1037 Val = I->second.first; 1038 } 1039 1040 // If we have the value in the symbol table or fwd-ref table, return it. 1041 if (Val) { 1042 if (Val->getType() == Ty) return Val; 1043 Error(Loc, "'@" + Twine(ID) + "' defined with type '" + 1044 getTypeString(Val->getType()) + "'"); 1045 return 0; 1046 } 1047 1048 // Otherwise, create a new forward reference for this value and remember it. 1049 GlobalValue *FwdVal; 1050 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) 1051 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); 1052 else 1053 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, 1054 GlobalValue::ExternalWeakLinkage, 0, ""); 1055 1056 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1057 return FwdVal; 1058 } 1059 1060 1061 //===----------------------------------------------------------------------===// 1062 // Helper Routines. 1063 //===----------------------------------------------------------------------===// 1064 1065 /// ParseToken - If the current token has the specified kind, eat it and return 1066 /// success. Otherwise, emit the specified error and return failure. 1067 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 1068 if (Lex.getKind() != T) 1069 return TokError(ErrMsg); 1070 Lex.Lex(); 1071 return false; 1072 } 1073 1074 /// ParseStringConstant 1075 /// ::= StringConstant 1076 bool LLParser::ParseStringConstant(std::string &Result) { 1077 if (Lex.getKind() != lltok::StringConstant) 1078 return TokError("expected string constant"); 1079 Result = Lex.getStrVal(); 1080 Lex.Lex(); 1081 return false; 1082 } 1083 1084 /// ParseUInt32 1085 /// ::= uint32 1086 bool LLParser::ParseUInt32(unsigned &Val) { 1087 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1088 return TokError("expected integer"); 1089 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 1090 if (Val64 != unsigned(Val64)) 1091 return TokError("expected 32-bit integer (too large)"); 1092 Val = Val64; 1093 Lex.Lex(); 1094 return false; 1095 } 1096 1097 /// ParseTLSModel 1098 /// := 'localdynamic' 1099 /// := 'initialexec' 1100 /// := 'localexec' 1101 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 1102 switch (Lex.getKind()) { 1103 default: 1104 return TokError("expected localdynamic, initialexec or localexec"); 1105 case lltok::kw_localdynamic: 1106 TLM = GlobalVariable::LocalDynamicTLSModel; 1107 break; 1108 case lltok::kw_initialexec: 1109 TLM = GlobalVariable::InitialExecTLSModel; 1110 break; 1111 case lltok::kw_localexec: 1112 TLM = GlobalVariable::LocalExecTLSModel; 1113 break; 1114 } 1115 1116 Lex.Lex(); 1117 return false; 1118 } 1119 1120 /// ParseOptionalThreadLocal 1121 /// := /*empty*/ 1122 /// := 'thread_local' 1123 /// := 'thread_local' '(' tlsmodel ')' 1124 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 1125 TLM = GlobalVariable::NotThreadLocal; 1126 if (!EatIfPresent(lltok::kw_thread_local)) 1127 return false; 1128 1129 TLM = GlobalVariable::GeneralDynamicTLSModel; 1130 if (Lex.getKind() == lltok::lparen) { 1131 Lex.Lex(); 1132 return ParseTLSModel(TLM) || 1133 ParseToken(lltok::rparen, "expected ')' after thread local model"); 1134 } 1135 return false; 1136 } 1137 1138 /// ParseOptionalAddrSpace 1139 /// := /*empty*/ 1140 /// := 'addrspace' '(' uint32 ')' 1141 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 1142 AddrSpace = 0; 1143 if (!EatIfPresent(lltok::kw_addrspace)) 1144 return false; 1145 return ParseToken(lltok::lparen, "expected '(' in address space") || 1146 ParseUInt32(AddrSpace) || 1147 ParseToken(lltok::rparen, "expected ')' in address space"); 1148 } 1149 1150 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes. 1151 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) { 1152 bool HaveError = false; 1153 1154 B.clear(); 1155 1156 while (1) { 1157 lltok::Kind Token = Lex.getKind(); 1158 switch (Token) { 1159 default: // End of attributes. 1160 return HaveError; 1161 case lltok::kw_align: { 1162 unsigned Alignment; 1163 if (ParseOptionalAlignment(Alignment)) 1164 return true; 1165 B.addAlignmentAttr(Alignment); 1166 continue; 1167 } 1168 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break; 1169 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break; 1170 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1171 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break; 1172 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1173 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break; 1174 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 1175 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 1176 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break; 1177 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1178 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break; 1179 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1180 1181 case lltok::kw_alignstack: 1182 case lltok::kw_alwaysinline: 1183 case lltok::kw_builtin: 1184 case lltok::kw_inlinehint: 1185 case lltok::kw_minsize: 1186 case lltok::kw_naked: 1187 case lltok::kw_nobuiltin: 1188 case lltok::kw_noduplicate: 1189 case lltok::kw_noimplicitfloat: 1190 case lltok::kw_noinline: 1191 case lltok::kw_nonlazybind: 1192 case lltok::kw_noredzone: 1193 case lltok::kw_noreturn: 1194 case lltok::kw_nounwind: 1195 case lltok::kw_optnone: 1196 case lltok::kw_optsize: 1197 case lltok::kw_returns_twice: 1198 case lltok::kw_sanitize_address: 1199 case lltok::kw_sanitize_memory: 1200 case lltok::kw_sanitize_thread: 1201 case lltok::kw_ssp: 1202 case lltok::kw_sspreq: 1203 case lltok::kw_sspstrong: 1204 case lltok::kw_uwtable: 1205 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 1206 break; 1207 } 1208 1209 Lex.Lex(); 1210 } 1211 } 1212 1213 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes. 1214 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) { 1215 bool HaveError = false; 1216 1217 B.clear(); 1218 1219 while (1) { 1220 lltok::Kind Token = Lex.getKind(); 1221 switch (Token) { 1222 default: // End of attributes. 1223 return HaveError; 1224 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1225 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1226 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1227 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1228 1229 // Error handling. 1230 case lltok::kw_align: 1231 case lltok::kw_byval: 1232 case lltok::kw_inalloca: 1233 case lltok::kw_nest: 1234 case lltok::kw_nocapture: 1235 case lltok::kw_returned: 1236 case lltok::kw_sret: 1237 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute"); 1238 break; 1239 1240 case lltok::kw_alignstack: 1241 case lltok::kw_alwaysinline: 1242 case lltok::kw_builtin: 1243 case lltok::kw_cold: 1244 case lltok::kw_inlinehint: 1245 case lltok::kw_minsize: 1246 case lltok::kw_naked: 1247 case lltok::kw_nobuiltin: 1248 case lltok::kw_noduplicate: 1249 case lltok::kw_noimplicitfloat: 1250 case lltok::kw_noinline: 1251 case lltok::kw_nonlazybind: 1252 case lltok::kw_noredzone: 1253 case lltok::kw_noreturn: 1254 case lltok::kw_nounwind: 1255 case lltok::kw_optnone: 1256 case lltok::kw_optsize: 1257 case lltok::kw_returns_twice: 1258 case lltok::kw_sanitize_address: 1259 case lltok::kw_sanitize_memory: 1260 case lltok::kw_sanitize_thread: 1261 case lltok::kw_ssp: 1262 case lltok::kw_sspreq: 1263 case lltok::kw_sspstrong: 1264 case lltok::kw_uwtable: 1265 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 1266 break; 1267 1268 case lltok::kw_readnone: 1269 case lltok::kw_readonly: 1270 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type"); 1271 } 1272 1273 Lex.Lex(); 1274 } 1275 } 1276 1277 /// ParseOptionalLinkage 1278 /// ::= /*empty*/ 1279 /// ::= 'private' 1280 /// ::= 'linker_private' 1281 /// ::= 'linker_private_weak' 1282 /// ::= 'internal' 1283 /// ::= 'weak' 1284 /// ::= 'weak_odr' 1285 /// ::= 'linkonce' 1286 /// ::= 'linkonce_odr' 1287 /// ::= 'available_externally' 1288 /// ::= 'appending' 1289 /// ::= 'common' 1290 /// ::= 'extern_weak' 1291 /// ::= 'external' 1292 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { 1293 HasLinkage = false; 1294 switch (Lex.getKind()) { 1295 default: Res=GlobalValue::ExternalLinkage; return false; 1296 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; 1297 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break; 1298 case lltok::kw_linker_private_weak: 1299 Res = GlobalValue::LinkerPrivateWeakLinkage; 1300 break; 1301 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; 1302 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break; 1303 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break; 1304 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break; 1305 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break; 1306 case lltok::kw_available_externally: 1307 Res = GlobalValue::AvailableExternallyLinkage; 1308 break; 1309 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; 1310 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; 1311 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; 1312 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; 1313 } 1314 Lex.Lex(); 1315 HasLinkage = true; 1316 return false; 1317 } 1318 1319 /// ParseOptionalVisibility 1320 /// ::= /*empty*/ 1321 /// ::= 'default' 1322 /// ::= 'hidden' 1323 /// ::= 'protected' 1324 /// 1325 bool LLParser::ParseOptionalVisibility(unsigned &Res) { 1326 switch (Lex.getKind()) { 1327 default: Res = GlobalValue::DefaultVisibility; return false; 1328 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break; 1329 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break; 1330 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break; 1331 } 1332 Lex.Lex(); 1333 return false; 1334 } 1335 1336 /// ParseOptionalDLLStorageClass 1337 /// ::= /*empty*/ 1338 /// ::= 'dllimport' 1339 /// ::= 'dllexport' 1340 /// 1341 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) { 1342 switch (Lex.getKind()) { 1343 default: Res = GlobalValue::DefaultStorageClass; return false; 1344 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break; 1345 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break; 1346 } 1347 Lex.Lex(); 1348 return false; 1349 } 1350 1351 /// ParseOptionalCallingConv 1352 /// ::= /*empty*/ 1353 /// ::= 'ccc' 1354 /// ::= 'fastcc' 1355 /// ::= 'kw_intel_ocl_bicc' 1356 /// ::= 'coldcc' 1357 /// ::= 'x86_stdcallcc' 1358 /// ::= 'x86_fastcallcc' 1359 /// ::= 'x86_thiscallcc' 1360 /// ::= 'x86_cdeclmethodcc' 1361 /// ::= 'arm_apcscc' 1362 /// ::= 'arm_aapcscc' 1363 /// ::= 'arm_aapcs_vfpcc' 1364 /// ::= 'msp430_intrcc' 1365 /// ::= 'ptx_kernel' 1366 /// ::= 'ptx_device' 1367 /// ::= 'spir_func' 1368 /// ::= 'spir_kernel' 1369 /// ::= 'x86_64_sysvcc' 1370 /// ::= 'x86_64_win64cc' 1371 /// ::= 'webkit_jscc' 1372 /// ::= 'anyregcc' 1373 /// ::= 'preserve_mostcc' 1374 /// ::= 'preserve_allcc' 1375 /// ::= 'cc' UINT 1376 /// 1377 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) { 1378 switch (Lex.getKind()) { 1379 default: CC = CallingConv::C; return false; 1380 case lltok::kw_ccc: CC = CallingConv::C; break; 1381 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 1382 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 1383 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 1384 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 1385 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 1386 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break; 1387 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 1388 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 1389 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 1390 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 1391 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 1392 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 1393 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 1394 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 1395 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 1396 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; 1397 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break; 1398 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break; 1399 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; 1400 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; 1401 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; 1402 case lltok::kw_cc: { 1403 unsigned ArbitraryCC; 1404 Lex.Lex(); 1405 if (ParseUInt32(ArbitraryCC)) 1406 return true; 1407 CC = static_cast<CallingConv::ID>(ArbitraryCC); 1408 return false; 1409 } 1410 } 1411 1412 Lex.Lex(); 1413 return false; 1414 } 1415 1416 /// ParseInstructionMetadata 1417 /// ::= !dbg !42 (',' !dbg !57)* 1418 bool LLParser::ParseInstructionMetadata(Instruction *Inst, 1419 PerFunctionState *PFS) { 1420 do { 1421 if (Lex.getKind() != lltok::MetadataVar) 1422 return TokError("expected metadata after comma"); 1423 1424 std::string Name = Lex.getStrVal(); 1425 unsigned MDK = M->getMDKindID(Name); 1426 Lex.Lex(); 1427 1428 MDNode *Node; 1429 SMLoc Loc = Lex.getLoc(); 1430 1431 if (ParseToken(lltok::exclaim, "expected '!' here")) 1432 return true; 1433 1434 // This code is similar to that of ParseMetadataValue, however it needs to 1435 // have special-case code for a forward reference; see the comments on 1436 // ForwardRefInstMetadata for details. Also, MDStrings are not supported 1437 // at the top level here. 1438 if (Lex.getKind() == lltok::lbrace) { 1439 ValID ID; 1440 if (ParseMetadataListValue(ID, PFS)) 1441 return true; 1442 assert(ID.Kind == ValID::t_MDNode); 1443 Inst->setMetadata(MDK, ID.MDNodeVal); 1444 } else { 1445 unsigned NodeID = 0; 1446 if (ParseMDNodeID(Node, NodeID)) 1447 return true; 1448 if (Node) { 1449 // If we got the node, add it to the instruction. 1450 Inst->setMetadata(MDK, Node); 1451 } else { 1452 MDRef R = { Loc, MDK, NodeID }; 1453 // Otherwise, remember that this should be resolved later. 1454 ForwardRefInstMetadata[Inst].push_back(R); 1455 } 1456 } 1457 1458 if (MDK == LLVMContext::MD_tbaa) 1459 InstsWithTBAATag.push_back(Inst); 1460 1461 // If this is the end of the list, we're done. 1462 } while (EatIfPresent(lltok::comma)); 1463 return false; 1464 } 1465 1466 /// ParseOptionalAlignment 1467 /// ::= /* empty */ 1468 /// ::= 'align' 4 1469 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 1470 Alignment = 0; 1471 if (!EatIfPresent(lltok::kw_align)) 1472 return false; 1473 LocTy AlignLoc = Lex.getLoc(); 1474 if (ParseUInt32(Alignment)) return true; 1475 if (!isPowerOf2_32(Alignment)) 1476 return Error(AlignLoc, "alignment is not a power of two"); 1477 if (Alignment > Value::MaximumAlignment) 1478 return Error(AlignLoc, "huge alignments are not supported yet"); 1479 return false; 1480 } 1481 1482 /// ParseOptionalCommaAlign 1483 /// ::= 1484 /// ::= ',' align 4 1485 /// 1486 /// This returns with AteExtraComma set to true if it ate an excess comma at the 1487 /// end. 1488 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment, 1489 bool &AteExtraComma) { 1490 AteExtraComma = false; 1491 while (EatIfPresent(lltok::comma)) { 1492 // Metadata at the end is an early exit. 1493 if (Lex.getKind() == lltok::MetadataVar) { 1494 AteExtraComma = true; 1495 return false; 1496 } 1497 1498 if (Lex.getKind() != lltok::kw_align) 1499 return Error(Lex.getLoc(), "expected metadata or 'align'"); 1500 1501 if (ParseOptionalAlignment(Alignment)) return true; 1502 } 1503 1504 return false; 1505 } 1506 1507 /// ParseScopeAndOrdering 1508 /// if isAtomic: ::= 'singlethread'? AtomicOrdering 1509 /// else: ::= 1510 /// 1511 /// This sets Scope and Ordering to the parsed values. 1512 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope, 1513 AtomicOrdering &Ordering) { 1514 if (!isAtomic) 1515 return false; 1516 1517 Scope = CrossThread; 1518 if (EatIfPresent(lltok::kw_singlethread)) 1519 Scope = SingleThread; 1520 switch (Lex.getKind()) { 1521 default: return TokError("Expected ordering on atomic instruction"); 1522 case lltok::kw_unordered: Ordering = Unordered; break; 1523 case lltok::kw_monotonic: Ordering = Monotonic; break; 1524 case lltok::kw_acquire: Ordering = Acquire; break; 1525 case lltok::kw_release: Ordering = Release; break; 1526 case lltok::kw_acq_rel: Ordering = AcquireRelease; break; 1527 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break; 1528 } 1529 Lex.Lex(); 1530 return false; 1531 } 1532 1533 /// ParseOptionalStackAlignment 1534 /// ::= /* empty */ 1535 /// ::= 'alignstack' '(' 4 ')' 1536 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) { 1537 Alignment = 0; 1538 if (!EatIfPresent(lltok::kw_alignstack)) 1539 return false; 1540 LocTy ParenLoc = Lex.getLoc(); 1541 if (!EatIfPresent(lltok::lparen)) 1542 return Error(ParenLoc, "expected '('"); 1543 LocTy AlignLoc = Lex.getLoc(); 1544 if (ParseUInt32(Alignment)) return true; 1545 ParenLoc = Lex.getLoc(); 1546 if (!EatIfPresent(lltok::rparen)) 1547 return Error(ParenLoc, "expected ')'"); 1548 if (!isPowerOf2_32(Alignment)) 1549 return Error(AlignLoc, "stack alignment is not a power of two"); 1550 return false; 1551 } 1552 1553 /// ParseIndexList - This parses the index list for an insert/extractvalue 1554 /// instruction. This sets AteExtraComma in the case where we eat an extra 1555 /// comma at the end of the line and find that it is followed by metadata. 1556 /// Clients that don't allow metadata can call the version of this function that 1557 /// only takes one argument. 1558 /// 1559 /// ParseIndexList 1560 /// ::= (',' uint32)+ 1561 /// 1562 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices, 1563 bool &AteExtraComma) { 1564 AteExtraComma = false; 1565 1566 if (Lex.getKind() != lltok::comma) 1567 return TokError("expected ',' as start of index list"); 1568 1569 while (EatIfPresent(lltok::comma)) { 1570 if (Lex.getKind() == lltok::MetadataVar) { 1571 AteExtraComma = true; 1572 return false; 1573 } 1574 unsigned Idx = 0; 1575 if (ParseUInt32(Idx)) return true; 1576 Indices.push_back(Idx); 1577 } 1578 1579 return false; 1580 } 1581 1582 //===----------------------------------------------------------------------===// 1583 // Type Parsing. 1584 //===----------------------------------------------------------------------===// 1585 1586 /// ParseType - Parse a type. 1587 bool LLParser::ParseType(Type *&Result, bool AllowVoid) { 1588 SMLoc TypeLoc = Lex.getLoc(); 1589 switch (Lex.getKind()) { 1590 default: 1591 return TokError("expected type"); 1592 case lltok::Type: 1593 // Type ::= 'float' | 'void' (etc) 1594 Result = Lex.getTyVal(); 1595 Lex.Lex(); 1596 break; 1597 case lltok::lbrace: 1598 // Type ::= StructType 1599 if (ParseAnonStructType(Result, false)) 1600 return true; 1601 break; 1602 case lltok::lsquare: 1603 // Type ::= '[' ... ']' 1604 Lex.Lex(); // eat the lsquare. 1605 if (ParseArrayVectorType(Result, false)) 1606 return true; 1607 break; 1608 case lltok::less: // Either vector or packed struct. 1609 // Type ::= '<' ... '>' 1610 Lex.Lex(); 1611 if (Lex.getKind() == lltok::lbrace) { 1612 if (ParseAnonStructType(Result, true) || 1613 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 1614 return true; 1615 } else if (ParseArrayVectorType(Result, true)) 1616 return true; 1617 break; 1618 case lltok::LocalVar: { 1619 // Type ::= %foo 1620 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 1621 1622 // If the type hasn't been defined yet, create a forward definition and 1623 // remember where that forward def'n was seen (in case it never is defined). 1624 if (Entry.first == 0) { 1625 Entry.first = StructType::create(Context, Lex.getStrVal()); 1626 Entry.second = Lex.getLoc(); 1627 } 1628 Result = Entry.first; 1629 Lex.Lex(); 1630 break; 1631 } 1632 1633 case lltok::LocalVarID: { 1634 // Type ::= %4 1635 if (Lex.getUIntVal() >= NumberedTypes.size()) 1636 NumberedTypes.resize(Lex.getUIntVal()+1); 1637 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 1638 1639 // If the type hasn't been defined yet, create a forward definition and 1640 // remember where that forward def'n was seen (in case it never is defined). 1641 if (Entry.first == 0) { 1642 Entry.first = StructType::create(Context); 1643 Entry.second = Lex.getLoc(); 1644 } 1645 Result = Entry.first; 1646 Lex.Lex(); 1647 break; 1648 } 1649 } 1650 1651 // Parse the type suffixes. 1652 while (1) { 1653 switch (Lex.getKind()) { 1654 // End of type. 1655 default: 1656 if (!AllowVoid && Result->isVoidTy()) 1657 return Error(TypeLoc, "void type only allowed for function results"); 1658 return false; 1659 1660 // Type ::= Type '*' 1661 case lltok::star: 1662 if (Result->isLabelTy()) 1663 return TokError("basic block pointers are invalid"); 1664 if (Result->isVoidTy()) 1665 return TokError("pointers to void are invalid - use i8* instead"); 1666 if (!PointerType::isValidElementType(Result)) 1667 return TokError("pointer to this type is invalid"); 1668 Result = PointerType::getUnqual(Result); 1669 Lex.Lex(); 1670 break; 1671 1672 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 1673 case lltok::kw_addrspace: { 1674 if (Result->isLabelTy()) 1675 return TokError("basic block pointers are invalid"); 1676 if (Result->isVoidTy()) 1677 return TokError("pointers to void are invalid; use i8* instead"); 1678 if (!PointerType::isValidElementType(Result)) 1679 return TokError("pointer to this type is invalid"); 1680 unsigned AddrSpace; 1681 if (ParseOptionalAddrSpace(AddrSpace) || 1682 ParseToken(lltok::star, "expected '*' in address space")) 1683 return true; 1684 1685 Result = PointerType::get(Result, AddrSpace); 1686 break; 1687 } 1688 1689 /// Types '(' ArgTypeListI ')' OptFuncAttrs 1690 case lltok::lparen: 1691 if (ParseFunctionType(Result)) 1692 return true; 1693 break; 1694 } 1695 } 1696 } 1697 1698 /// ParseParameterList 1699 /// ::= '(' ')' 1700 /// ::= '(' Arg (',' Arg)* ')' 1701 /// Arg 1702 /// ::= Type OptionalAttributes Value OptionalAttributes 1703 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 1704 PerFunctionState &PFS) { 1705 if (ParseToken(lltok::lparen, "expected '(' in call")) 1706 return true; 1707 1708 unsigned AttrIndex = 1; 1709 while (Lex.getKind() != lltok::rparen) { 1710 // If this isn't the first argument, we need a comma. 1711 if (!ArgList.empty() && 1712 ParseToken(lltok::comma, "expected ',' in argument list")) 1713 return true; 1714 1715 // Parse the argument. 1716 LocTy ArgLoc; 1717 Type *ArgTy = 0; 1718 AttrBuilder ArgAttrs; 1719 Value *V; 1720 if (ParseType(ArgTy, ArgLoc)) 1721 return true; 1722 1723 // Otherwise, handle normal operands. 1724 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS)) 1725 return true; 1726 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(), 1727 AttrIndex++, 1728 ArgAttrs))); 1729 } 1730 1731 Lex.Lex(); // Lex the ')'. 1732 return false; 1733 } 1734 1735 1736 1737 /// ParseArgumentList - Parse the argument list for a function type or function 1738 /// prototype. 1739 /// ::= '(' ArgTypeListI ')' 1740 /// ArgTypeListI 1741 /// ::= /*empty*/ 1742 /// ::= '...' 1743 /// ::= ArgTypeList ',' '...' 1744 /// ::= ArgType (',' ArgType)* 1745 /// 1746 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 1747 bool &isVarArg){ 1748 isVarArg = false; 1749 assert(Lex.getKind() == lltok::lparen); 1750 Lex.Lex(); // eat the (. 1751 1752 if (Lex.getKind() == lltok::rparen) { 1753 // empty 1754 } else if (Lex.getKind() == lltok::dotdotdot) { 1755 isVarArg = true; 1756 Lex.Lex(); 1757 } else { 1758 LocTy TypeLoc = Lex.getLoc(); 1759 Type *ArgTy = 0; 1760 AttrBuilder Attrs; 1761 std::string Name; 1762 1763 if (ParseType(ArgTy) || 1764 ParseOptionalParamAttrs(Attrs)) return true; 1765 1766 if (ArgTy->isVoidTy()) 1767 return Error(TypeLoc, "argument can not have void type"); 1768 1769 if (Lex.getKind() == lltok::LocalVar) { 1770 Name = Lex.getStrVal(); 1771 Lex.Lex(); 1772 } 1773 1774 if (!FunctionType::isValidArgumentType(ArgTy)) 1775 return Error(TypeLoc, "invalid type for function argument"); 1776 1777 unsigned AttrIndex = 1; 1778 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, 1779 AttributeSet::get(ArgTy->getContext(), 1780 AttrIndex++, Attrs), Name)); 1781 1782 while (EatIfPresent(lltok::comma)) { 1783 // Handle ... at end of arg list. 1784 if (EatIfPresent(lltok::dotdotdot)) { 1785 isVarArg = true; 1786 break; 1787 } 1788 1789 // Otherwise must be an argument type. 1790 TypeLoc = Lex.getLoc(); 1791 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true; 1792 1793 if (ArgTy->isVoidTy()) 1794 return Error(TypeLoc, "argument can not have void type"); 1795 1796 if (Lex.getKind() == lltok::LocalVar) { 1797 Name = Lex.getStrVal(); 1798 Lex.Lex(); 1799 } else { 1800 Name = ""; 1801 } 1802 1803 if (!ArgTy->isFirstClassType()) 1804 return Error(TypeLoc, "invalid type for function argument"); 1805 1806 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, 1807 AttributeSet::get(ArgTy->getContext(), 1808 AttrIndex++, Attrs), 1809 Name)); 1810 } 1811 } 1812 1813 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 1814 } 1815 1816 /// ParseFunctionType 1817 /// ::= Type ArgumentList OptionalAttrs 1818 bool LLParser::ParseFunctionType(Type *&Result) { 1819 assert(Lex.getKind() == lltok::lparen); 1820 1821 if (!FunctionType::isValidReturnType(Result)) 1822 return TokError("invalid function return type"); 1823 1824 SmallVector<ArgInfo, 8> ArgList; 1825 bool isVarArg; 1826 if (ParseArgumentList(ArgList, isVarArg)) 1827 return true; 1828 1829 // Reject names on the arguments lists. 1830 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 1831 if (!ArgList[i].Name.empty()) 1832 return Error(ArgList[i].Loc, "argument name invalid in function type"); 1833 if (ArgList[i].Attrs.hasAttributes(i + 1)) 1834 return Error(ArgList[i].Loc, 1835 "argument attributes invalid in function type"); 1836 } 1837 1838 SmallVector<Type*, 16> ArgListTy; 1839 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 1840 ArgListTy.push_back(ArgList[i].Ty); 1841 1842 Result = FunctionType::get(Result, ArgListTy, isVarArg); 1843 return false; 1844 } 1845 1846 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into 1847 /// other structs. 1848 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) { 1849 SmallVector<Type*, 8> Elts; 1850 if (ParseStructBody(Elts)) return true; 1851 1852 Result = StructType::get(Context, Elts, Packed); 1853 return false; 1854 } 1855 1856 /// ParseStructDefinition - Parse a struct in a 'type' definition. 1857 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name, 1858 std::pair<Type*, LocTy> &Entry, 1859 Type *&ResultTy) { 1860 // If the type was already defined, diagnose the redefinition. 1861 if (Entry.first && !Entry.second.isValid()) 1862 return Error(TypeLoc, "redefinition of type"); 1863 1864 // If we have opaque, just return without filling in the definition for the 1865 // struct. This counts as a definition as far as the .ll file goes. 1866 if (EatIfPresent(lltok::kw_opaque)) { 1867 // This type is being defined, so clear the location to indicate this. 1868 Entry.second = SMLoc(); 1869 1870 // If this type number has never been uttered, create it. 1871 if (Entry.first == 0) 1872 Entry.first = StructType::create(Context, Name); 1873 ResultTy = Entry.first; 1874 return false; 1875 } 1876 1877 // If the type starts with '<', then it is either a packed struct or a vector. 1878 bool isPacked = EatIfPresent(lltok::less); 1879 1880 // If we don't have a struct, then we have a random type alias, which we 1881 // accept for compatibility with old files. These types are not allowed to be 1882 // forward referenced and not allowed to be recursive. 1883 if (Lex.getKind() != lltok::lbrace) { 1884 if (Entry.first) 1885 return Error(TypeLoc, "forward references to non-struct type"); 1886 1887 ResultTy = 0; 1888 if (isPacked) 1889 return ParseArrayVectorType(ResultTy, true); 1890 return ParseType(ResultTy); 1891 } 1892 1893 // This type is being defined, so clear the location to indicate this. 1894 Entry.second = SMLoc(); 1895 1896 // If this type number has never been uttered, create it. 1897 if (Entry.first == 0) 1898 Entry.first = StructType::create(Context, Name); 1899 1900 StructType *STy = cast<StructType>(Entry.first); 1901 1902 SmallVector<Type*, 8> Body; 1903 if (ParseStructBody(Body) || 1904 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct"))) 1905 return true; 1906 1907 STy->setBody(Body, isPacked); 1908 ResultTy = STy; 1909 return false; 1910 } 1911 1912 1913 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 1914 /// StructType 1915 /// ::= '{' '}' 1916 /// ::= '{' Type (',' Type)* '}' 1917 /// ::= '<' '{' '}' '>' 1918 /// ::= '<' '{' Type (',' Type)* '}' '>' 1919 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) { 1920 assert(Lex.getKind() == lltok::lbrace); 1921 Lex.Lex(); // Consume the '{' 1922 1923 // Handle the empty struct. 1924 if (EatIfPresent(lltok::rbrace)) 1925 return false; 1926 1927 LocTy EltTyLoc = Lex.getLoc(); 1928 Type *Ty = 0; 1929 if (ParseType(Ty)) return true; 1930 Body.push_back(Ty); 1931 1932 if (!StructType::isValidElementType(Ty)) 1933 return Error(EltTyLoc, "invalid element type for struct"); 1934 1935 while (EatIfPresent(lltok::comma)) { 1936 EltTyLoc = Lex.getLoc(); 1937 if (ParseType(Ty)) return true; 1938 1939 if (!StructType::isValidElementType(Ty)) 1940 return Error(EltTyLoc, "invalid element type for struct"); 1941 1942 Body.push_back(Ty); 1943 } 1944 1945 return ParseToken(lltok::rbrace, "expected '}' at end of struct"); 1946 } 1947 1948 /// ParseArrayVectorType - Parse an array or vector type, assuming the first 1949 /// token has already been consumed. 1950 /// Type 1951 /// ::= '[' APSINTVAL 'x' Types ']' 1952 /// ::= '<' APSINTVAL 'x' Types '>' 1953 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) { 1954 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 1955 Lex.getAPSIntVal().getBitWidth() > 64) 1956 return TokError("expected number in address space"); 1957 1958 LocTy SizeLoc = Lex.getLoc(); 1959 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 1960 Lex.Lex(); 1961 1962 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 1963 return true; 1964 1965 LocTy TypeLoc = Lex.getLoc(); 1966 Type *EltTy = 0; 1967 if (ParseType(EltTy)) return true; 1968 1969 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 1970 "expected end of sequential type")) 1971 return true; 1972 1973 if (isVector) { 1974 if (Size == 0) 1975 return Error(SizeLoc, "zero element vector is illegal"); 1976 if ((unsigned)Size != Size) 1977 return Error(SizeLoc, "size too large for vector"); 1978 if (!VectorType::isValidElementType(EltTy)) 1979 return Error(TypeLoc, "invalid vector element type"); 1980 Result = VectorType::get(EltTy, unsigned(Size)); 1981 } else { 1982 if (!ArrayType::isValidElementType(EltTy)) 1983 return Error(TypeLoc, "invalid array element type"); 1984 Result = ArrayType::get(EltTy, Size); 1985 } 1986 return false; 1987 } 1988 1989 //===----------------------------------------------------------------------===// 1990 // Function Semantic Analysis. 1991 //===----------------------------------------------------------------------===// 1992 1993 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 1994 int functionNumber) 1995 : P(p), F(f), FunctionNumber(functionNumber) { 1996 1997 // Insert unnamed arguments into the NumberedVals list. 1998 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 1999 AI != E; ++AI) 2000 if (!AI->hasName()) 2001 NumberedVals.push_back(AI); 2002 } 2003 2004 LLParser::PerFunctionState::~PerFunctionState() { 2005 // If there were any forward referenced non-basicblock values, delete them. 2006 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator 2007 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) 2008 if (!isa<BasicBlock>(I->second.first)) { 2009 I->second.first->replaceAllUsesWith( 2010 UndefValue::get(I->second.first->getType())); 2011 delete I->second.first; 2012 I->second.first = 0; 2013 } 2014 2015 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator 2016 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) 2017 if (!isa<BasicBlock>(I->second.first)) { 2018 I->second.first->replaceAllUsesWith( 2019 UndefValue::get(I->second.first->getType())); 2020 delete I->second.first; 2021 I->second.first = 0; 2022 } 2023 } 2024 2025 bool LLParser::PerFunctionState::FinishFunction() { 2026 // Check to see if someone took the address of labels in this block. 2027 if (!P.ForwardRefBlockAddresses.empty()) { 2028 ValID FunctionID; 2029 if (!F.getName().empty()) { 2030 FunctionID.Kind = ValID::t_GlobalName; 2031 FunctionID.StrVal = F.getName(); 2032 } else { 2033 FunctionID.Kind = ValID::t_GlobalID; 2034 FunctionID.UIntVal = FunctionNumber; 2035 } 2036 2037 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator 2038 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID); 2039 if (FRBAI != P.ForwardRefBlockAddresses.end()) { 2040 // Resolve all these references. 2041 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this)) 2042 return true; 2043 2044 P.ForwardRefBlockAddresses.erase(FRBAI); 2045 } 2046 } 2047 2048 if (!ForwardRefVals.empty()) 2049 return P.Error(ForwardRefVals.begin()->second.second, 2050 "use of undefined value '%" + ForwardRefVals.begin()->first + 2051 "'"); 2052 if (!ForwardRefValIDs.empty()) 2053 return P.Error(ForwardRefValIDs.begin()->second.second, 2054 "use of undefined value '%" + 2055 Twine(ForwardRefValIDs.begin()->first) + "'"); 2056 return false; 2057 } 2058 2059 2060 /// GetVal - Get a value with the specified name or ID, creating a 2061 /// forward reference record if needed. This can return null if the value 2062 /// exists but does not have the right type. 2063 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, 2064 Type *Ty, LocTy Loc) { 2065 // Look this name up in the normal function symbol table. 2066 Value *Val = F.getValueSymbolTable().lookup(Name); 2067 2068 // If this is a forward reference for the value, see if we already created a 2069 // forward ref record. 2070 if (Val == 0) { 2071 std::map<std::string, std::pair<Value*, LocTy> >::iterator 2072 I = ForwardRefVals.find(Name); 2073 if (I != ForwardRefVals.end()) 2074 Val = I->second.first; 2075 } 2076 2077 // If we have the value in the symbol table or fwd-ref table, return it. 2078 if (Val) { 2079 if (Val->getType() == Ty) return Val; 2080 if (Ty->isLabelTy()) 2081 P.Error(Loc, "'%" + Name + "' is not a basic block"); 2082 else 2083 P.Error(Loc, "'%" + Name + "' defined with type '" + 2084 getTypeString(Val->getType()) + "'"); 2085 return 0; 2086 } 2087 2088 // Don't make placeholders with invalid type. 2089 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 2090 P.Error(Loc, "invalid use of a non-first-class type"); 2091 return 0; 2092 } 2093 2094 // Otherwise, create a new forward reference for this value and remember it. 2095 Value *FwdVal; 2096 if (Ty->isLabelTy()) 2097 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 2098 else 2099 FwdVal = new Argument(Ty, Name); 2100 2101 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 2102 return FwdVal; 2103 } 2104 2105 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, 2106 LocTy Loc) { 2107 // Look this name up in the normal function symbol table. 2108 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 2109 2110 // If this is a forward reference for the value, see if we already created a 2111 // forward ref record. 2112 if (Val == 0) { 2113 std::map<unsigned, std::pair<Value*, LocTy> >::iterator 2114 I = ForwardRefValIDs.find(ID); 2115 if (I != ForwardRefValIDs.end()) 2116 Val = I->second.first; 2117 } 2118 2119 // If we have the value in the symbol table or fwd-ref table, return it. 2120 if (Val) { 2121 if (Val->getType() == Ty) return Val; 2122 if (Ty->isLabelTy()) 2123 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block"); 2124 else 2125 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" + 2126 getTypeString(Val->getType()) + "'"); 2127 return 0; 2128 } 2129 2130 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) { 2131 P.Error(Loc, "invalid use of a non-first-class type"); 2132 return 0; 2133 } 2134 2135 // Otherwise, create a new forward reference for this value and remember it. 2136 Value *FwdVal; 2137 if (Ty->isLabelTy()) 2138 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 2139 else 2140 FwdVal = new Argument(Ty); 2141 2142 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 2143 return FwdVal; 2144 } 2145 2146 /// SetInstName - After an instruction is parsed and inserted into its 2147 /// basic block, this installs its name. 2148 bool LLParser::PerFunctionState::SetInstName(int NameID, 2149 const std::string &NameStr, 2150 LocTy NameLoc, Instruction *Inst) { 2151 // If this instruction has void type, it cannot have a name or ID specified. 2152 if (Inst->getType()->isVoidTy()) { 2153 if (NameID != -1 || !NameStr.empty()) 2154 return P.Error(NameLoc, "instructions returning void cannot have a name"); 2155 return false; 2156 } 2157 2158 // If this was a numbered instruction, verify that the instruction is the 2159 // expected value and resolve any forward references. 2160 if (NameStr.empty()) { 2161 // If neither a name nor an ID was specified, just use the next ID. 2162 if (NameID == -1) 2163 NameID = NumberedVals.size(); 2164 2165 if (unsigned(NameID) != NumberedVals.size()) 2166 return P.Error(NameLoc, "instruction expected to be numbered '%" + 2167 Twine(NumberedVals.size()) + "'"); 2168 2169 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = 2170 ForwardRefValIDs.find(NameID); 2171 if (FI != ForwardRefValIDs.end()) { 2172 if (FI->second.first->getType() != Inst->getType()) 2173 return P.Error(NameLoc, "instruction forward referenced with type '" + 2174 getTypeString(FI->second.first->getType()) + "'"); 2175 FI->second.first->replaceAllUsesWith(Inst); 2176 delete FI->second.first; 2177 ForwardRefValIDs.erase(FI); 2178 } 2179 2180 NumberedVals.push_back(Inst); 2181 return false; 2182 } 2183 2184 // Otherwise, the instruction had a name. Resolve forward refs and set it. 2185 std::map<std::string, std::pair<Value*, LocTy> >::iterator 2186 FI = ForwardRefVals.find(NameStr); 2187 if (FI != ForwardRefVals.end()) { 2188 if (FI->second.first->getType() != Inst->getType()) 2189 return P.Error(NameLoc, "instruction forward referenced with type '" + 2190 getTypeString(FI->second.first->getType()) + "'"); 2191 FI->second.first->replaceAllUsesWith(Inst); 2192 delete FI->second.first; 2193 ForwardRefVals.erase(FI); 2194 } 2195 2196 // Set the name on the instruction. 2197 Inst->setName(NameStr); 2198 2199 if (Inst->getName() != NameStr) 2200 return P.Error(NameLoc, "multiple definition of local value named '" + 2201 NameStr + "'"); 2202 return false; 2203 } 2204 2205 /// GetBB - Get a basic block with the specified name or ID, creating a 2206 /// forward reference record if needed. 2207 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 2208 LocTy Loc) { 2209 return cast_or_null<BasicBlock>(GetVal(Name, 2210 Type::getLabelTy(F.getContext()), Loc)); 2211 } 2212 2213 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 2214 return cast_or_null<BasicBlock>(GetVal(ID, 2215 Type::getLabelTy(F.getContext()), Loc)); 2216 } 2217 2218 /// DefineBB - Define the specified basic block, which is either named or 2219 /// unnamed. If there is an error, this returns null otherwise it returns 2220 /// the block being defined. 2221 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 2222 LocTy Loc) { 2223 BasicBlock *BB; 2224 if (Name.empty()) 2225 BB = GetBB(NumberedVals.size(), Loc); 2226 else 2227 BB = GetBB(Name, Loc); 2228 if (BB == 0) return 0; // Already diagnosed error. 2229 2230 // Move the block to the end of the function. Forward ref'd blocks are 2231 // inserted wherever they happen to be referenced. 2232 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 2233 2234 // Remove the block from forward ref sets. 2235 if (Name.empty()) { 2236 ForwardRefValIDs.erase(NumberedVals.size()); 2237 NumberedVals.push_back(BB); 2238 } else { 2239 // BB forward references are already in the function symbol table. 2240 ForwardRefVals.erase(Name); 2241 } 2242 2243 return BB; 2244 } 2245 2246 //===----------------------------------------------------------------------===// 2247 // Constants. 2248 //===----------------------------------------------------------------------===// 2249 2250 /// ParseValID - Parse an abstract value that doesn't necessarily have a 2251 /// type implied. For example, if we parse "4" we don't know what integer type 2252 /// it has. The value will later be combined with its type and checked for 2253 /// sanity. PFS is used to convert function-local operands of metadata (since 2254 /// metadata operands are not just parsed here but also converted to values). 2255 /// PFS can be null when we are not parsing metadata values inside a function. 2256 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) { 2257 ID.Loc = Lex.getLoc(); 2258 switch (Lex.getKind()) { 2259 default: return TokError("expected value token"); 2260 case lltok::GlobalID: // @42 2261 ID.UIntVal = Lex.getUIntVal(); 2262 ID.Kind = ValID::t_GlobalID; 2263 break; 2264 case lltok::GlobalVar: // @foo 2265 ID.StrVal = Lex.getStrVal(); 2266 ID.Kind = ValID::t_GlobalName; 2267 break; 2268 case lltok::LocalVarID: // %42 2269 ID.UIntVal = Lex.getUIntVal(); 2270 ID.Kind = ValID::t_LocalID; 2271 break; 2272 case lltok::LocalVar: // %foo 2273 ID.StrVal = Lex.getStrVal(); 2274 ID.Kind = ValID::t_LocalName; 2275 break; 2276 case lltok::exclaim: // !42, !{...}, or !"foo" 2277 return ParseMetadataValue(ID, PFS); 2278 case lltok::APSInt: 2279 ID.APSIntVal = Lex.getAPSIntVal(); 2280 ID.Kind = ValID::t_APSInt; 2281 break; 2282 case lltok::APFloat: 2283 ID.APFloatVal = Lex.getAPFloatVal(); 2284 ID.Kind = ValID::t_APFloat; 2285 break; 2286 case lltok::kw_true: 2287 ID.ConstantVal = ConstantInt::getTrue(Context); 2288 ID.Kind = ValID::t_Constant; 2289 break; 2290 case lltok::kw_false: 2291 ID.ConstantVal = ConstantInt::getFalse(Context); 2292 ID.Kind = ValID::t_Constant; 2293 break; 2294 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 2295 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 2296 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 2297 2298 case lltok::lbrace: { 2299 // ValID ::= '{' ConstVector '}' 2300 Lex.Lex(); 2301 SmallVector<Constant*, 16> Elts; 2302 if (ParseGlobalValueVector(Elts) || 2303 ParseToken(lltok::rbrace, "expected end of struct constant")) 2304 return true; 2305 2306 ID.ConstantStructElts = new Constant*[Elts.size()]; 2307 ID.UIntVal = Elts.size(); 2308 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 2309 ID.Kind = ValID::t_ConstantStruct; 2310 return false; 2311 } 2312 case lltok::less: { 2313 // ValID ::= '<' ConstVector '>' --> Vector. 2314 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 2315 Lex.Lex(); 2316 bool isPackedStruct = EatIfPresent(lltok::lbrace); 2317 2318 SmallVector<Constant*, 16> Elts; 2319 LocTy FirstEltLoc = Lex.getLoc(); 2320 if (ParseGlobalValueVector(Elts) || 2321 (isPackedStruct && 2322 ParseToken(lltok::rbrace, "expected end of packed struct")) || 2323 ParseToken(lltok::greater, "expected end of constant")) 2324 return true; 2325 2326 if (isPackedStruct) { 2327 ID.ConstantStructElts = new Constant*[Elts.size()]; 2328 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0])); 2329 ID.UIntVal = Elts.size(); 2330 ID.Kind = ValID::t_PackedConstantStruct; 2331 return false; 2332 } 2333 2334 if (Elts.empty()) 2335 return Error(ID.Loc, "constant vector must not be empty"); 2336 2337 if (!Elts[0]->getType()->isIntegerTy() && 2338 !Elts[0]->getType()->isFloatingPointTy() && 2339 !Elts[0]->getType()->isPointerTy()) 2340 return Error(FirstEltLoc, 2341 "vector elements must have integer, pointer or floating point type"); 2342 2343 // Verify that all the vector elements have the same type. 2344 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 2345 if (Elts[i]->getType() != Elts[0]->getType()) 2346 return Error(FirstEltLoc, 2347 "vector element #" + Twine(i) + 2348 " is not of type '" + getTypeString(Elts[0]->getType())); 2349 2350 ID.ConstantVal = ConstantVector::get(Elts); 2351 ID.Kind = ValID::t_Constant; 2352 return false; 2353 } 2354 case lltok::lsquare: { // Array Constant 2355 Lex.Lex(); 2356 SmallVector<Constant*, 16> Elts; 2357 LocTy FirstEltLoc = Lex.getLoc(); 2358 if (ParseGlobalValueVector(Elts) || 2359 ParseToken(lltok::rsquare, "expected end of array constant")) 2360 return true; 2361 2362 // Handle empty element. 2363 if (Elts.empty()) { 2364 // Use undef instead of an array because it's inconvenient to determine 2365 // the element type at this point, there being no elements to examine. 2366 ID.Kind = ValID::t_EmptyArray; 2367 return false; 2368 } 2369 2370 if (!Elts[0]->getType()->isFirstClassType()) 2371 return Error(FirstEltLoc, "invalid array element type: " + 2372 getTypeString(Elts[0]->getType())); 2373 2374 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 2375 2376 // Verify all elements are correct type! 2377 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 2378 if (Elts[i]->getType() != Elts[0]->getType()) 2379 return Error(FirstEltLoc, 2380 "array element #" + Twine(i) + 2381 " is not of type '" + getTypeString(Elts[0]->getType())); 2382 } 2383 2384 ID.ConstantVal = ConstantArray::get(ATy, Elts); 2385 ID.Kind = ValID::t_Constant; 2386 return false; 2387 } 2388 case lltok::kw_c: // c "foo" 2389 Lex.Lex(); 2390 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 2391 false); 2392 if (ParseToken(lltok::StringConstant, "expected string")) return true; 2393 ID.Kind = ValID::t_Constant; 2394 return false; 2395 2396 case lltok::kw_asm: { 2397 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 2398 // STRINGCONSTANT 2399 bool HasSideEffect, AlignStack, AsmDialect; 2400 Lex.Lex(); 2401 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 2402 ParseOptionalToken(lltok::kw_alignstack, AlignStack) || 2403 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 2404 ParseStringConstant(ID.StrVal) || 2405 ParseToken(lltok::comma, "expected comma in inline asm expression") || 2406 ParseToken(lltok::StringConstant, "expected constraint string")) 2407 return true; 2408 ID.StrVal2 = Lex.getStrVal(); 2409 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) | 2410 (unsigned(AsmDialect)<<2); 2411 ID.Kind = ValID::t_InlineAsm; 2412 return false; 2413 } 2414 2415 case lltok::kw_blockaddress: { 2416 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 2417 Lex.Lex(); 2418 2419 ValID Fn, Label; 2420 2421 if (ParseToken(lltok::lparen, "expected '(' in block address expression") || 2422 ParseValID(Fn) || 2423 ParseToken(lltok::comma, "expected comma in block address expression")|| 2424 ParseValID(Label) || 2425 ParseToken(lltok::rparen, "expected ')' in block address expression")) 2426 return true; 2427 2428 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 2429 return Error(Fn.Loc, "expected function name in blockaddress"); 2430 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 2431 return Error(Label.Loc, "expected basic block name in blockaddress"); 2432 2433 // Make a global variable as a placeholder for this reference. 2434 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), 2435 false, GlobalValue::InternalLinkage, 2436 0, ""); 2437 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef)); 2438 ID.ConstantVal = FwdRef; 2439 ID.Kind = ValID::t_Constant; 2440 return false; 2441 } 2442 2443 case lltok::kw_trunc: 2444 case lltok::kw_zext: 2445 case lltok::kw_sext: 2446 case lltok::kw_fptrunc: 2447 case lltok::kw_fpext: 2448 case lltok::kw_bitcast: 2449 case lltok::kw_addrspacecast: 2450 case lltok::kw_uitofp: 2451 case lltok::kw_sitofp: 2452 case lltok::kw_fptoui: 2453 case lltok::kw_fptosi: 2454 case lltok::kw_inttoptr: 2455 case lltok::kw_ptrtoint: { 2456 unsigned Opc = Lex.getUIntVal(); 2457 Type *DestTy = 0; 2458 Constant *SrcVal; 2459 Lex.Lex(); 2460 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 2461 ParseGlobalTypeAndValue(SrcVal) || 2462 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 2463 ParseType(DestTy) || 2464 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 2465 return true; 2466 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 2467 return Error(ID.Loc, "invalid cast opcode for cast from '" + 2468 getTypeString(SrcVal->getType()) + "' to '" + 2469 getTypeString(DestTy) + "'"); 2470 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 2471 SrcVal, DestTy); 2472 ID.Kind = ValID::t_Constant; 2473 return false; 2474 } 2475 case lltok::kw_extractvalue: { 2476 Lex.Lex(); 2477 Constant *Val; 2478 SmallVector<unsigned, 4> Indices; 2479 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 2480 ParseGlobalTypeAndValue(Val) || 2481 ParseIndexList(Indices) || 2482 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 2483 return true; 2484 2485 if (!Val->getType()->isAggregateType()) 2486 return Error(ID.Loc, "extractvalue operand must be aggregate type"); 2487 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 2488 return Error(ID.Loc, "invalid indices for extractvalue"); 2489 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 2490 ID.Kind = ValID::t_Constant; 2491 return false; 2492 } 2493 case lltok::kw_insertvalue: { 2494 Lex.Lex(); 2495 Constant *Val0, *Val1; 2496 SmallVector<unsigned, 4> Indices; 2497 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 2498 ParseGlobalTypeAndValue(Val0) || 2499 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 2500 ParseGlobalTypeAndValue(Val1) || 2501 ParseIndexList(Indices) || 2502 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 2503 return true; 2504 if (!Val0->getType()->isAggregateType()) 2505 return Error(ID.Loc, "insertvalue operand must be aggregate type"); 2506 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices)) 2507 return Error(ID.Loc, "invalid indices for insertvalue"); 2508 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 2509 ID.Kind = ValID::t_Constant; 2510 return false; 2511 } 2512 case lltok::kw_icmp: 2513 case lltok::kw_fcmp: { 2514 unsigned PredVal, Opc = Lex.getUIntVal(); 2515 Constant *Val0, *Val1; 2516 Lex.Lex(); 2517 if (ParseCmpPredicate(PredVal, Opc) || 2518 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 2519 ParseGlobalTypeAndValue(Val0) || 2520 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 2521 ParseGlobalTypeAndValue(Val1) || 2522 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 2523 return true; 2524 2525 if (Val0->getType() != Val1->getType()) 2526 return Error(ID.Loc, "compare operands must have the same type"); 2527 2528 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 2529 2530 if (Opc == Instruction::FCmp) { 2531 if (!Val0->getType()->isFPOrFPVectorTy()) 2532 return Error(ID.Loc, "fcmp requires floating point operands"); 2533 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 2534 } else { 2535 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 2536 if (!Val0->getType()->isIntOrIntVectorTy() && 2537 !Val0->getType()->getScalarType()->isPointerTy()) 2538 return Error(ID.Loc, "icmp requires pointer or integer operands"); 2539 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 2540 } 2541 ID.Kind = ValID::t_Constant; 2542 return false; 2543 } 2544 2545 // Binary Operators. 2546 case lltok::kw_add: 2547 case lltok::kw_fadd: 2548 case lltok::kw_sub: 2549 case lltok::kw_fsub: 2550 case lltok::kw_mul: 2551 case lltok::kw_fmul: 2552 case lltok::kw_udiv: 2553 case lltok::kw_sdiv: 2554 case lltok::kw_fdiv: 2555 case lltok::kw_urem: 2556 case lltok::kw_srem: 2557 case lltok::kw_frem: 2558 case lltok::kw_shl: 2559 case lltok::kw_lshr: 2560 case lltok::kw_ashr: { 2561 bool NUW = false; 2562 bool NSW = false; 2563 bool Exact = false; 2564 unsigned Opc = Lex.getUIntVal(); 2565 Constant *Val0, *Val1; 2566 Lex.Lex(); 2567 LocTy ModifierLoc = Lex.getLoc(); 2568 if (Opc == Instruction::Add || Opc == Instruction::Sub || 2569 Opc == Instruction::Mul || Opc == Instruction::Shl) { 2570 if (EatIfPresent(lltok::kw_nuw)) 2571 NUW = true; 2572 if (EatIfPresent(lltok::kw_nsw)) { 2573 NSW = true; 2574 if (EatIfPresent(lltok::kw_nuw)) 2575 NUW = true; 2576 } 2577 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 2578 Opc == Instruction::LShr || Opc == Instruction::AShr) { 2579 if (EatIfPresent(lltok::kw_exact)) 2580 Exact = true; 2581 } 2582 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 2583 ParseGlobalTypeAndValue(Val0) || 2584 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 2585 ParseGlobalTypeAndValue(Val1) || 2586 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 2587 return true; 2588 if (Val0->getType() != Val1->getType()) 2589 return Error(ID.Loc, "operands of constexpr must have same type"); 2590 if (!Val0->getType()->isIntOrIntVectorTy()) { 2591 if (NUW) 2592 return Error(ModifierLoc, "nuw only applies to integer operations"); 2593 if (NSW) 2594 return Error(ModifierLoc, "nsw only applies to integer operations"); 2595 } 2596 // Check that the type is valid for the operator. 2597 switch (Opc) { 2598 case Instruction::Add: 2599 case Instruction::Sub: 2600 case Instruction::Mul: 2601 case Instruction::UDiv: 2602 case Instruction::SDiv: 2603 case Instruction::URem: 2604 case Instruction::SRem: 2605 case Instruction::Shl: 2606 case Instruction::AShr: 2607 case Instruction::LShr: 2608 if (!Val0->getType()->isIntOrIntVectorTy()) 2609 return Error(ID.Loc, "constexpr requires integer operands"); 2610 break; 2611 case Instruction::FAdd: 2612 case Instruction::FSub: 2613 case Instruction::FMul: 2614 case Instruction::FDiv: 2615 case Instruction::FRem: 2616 if (!Val0->getType()->isFPOrFPVectorTy()) 2617 return Error(ID.Loc, "constexpr requires fp operands"); 2618 break; 2619 default: llvm_unreachable("Unknown binary operator!"); 2620 } 2621 unsigned Flags = 0; 2622 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 2623 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 2624 if (Exact) Flags |= PossiblyExactOperator::IsExact; 2625 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 2626 ID.ConstantVal = C; 2627 ID.Kind = ValID::t_Constant; 2628 return false; 2629 } 2630 2631 // Logical Operations 2632 case lltok::kw_and: 2633 case lltok::kw_or: 2634 case lltok::kw_xor: { 2635 unsigned Opc = Lex.getUIntVal(); 2636 Constant *Val0, *Val1; 2637 Lex.Lex(); 2638 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 2639 ParseGlobalTypeAndValue(Val0) || 2640 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 2641 ParseGlobalTypeAndValue(Val1) || 2642 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 2643 return true; 2644 if (Val0->getType() != Val1->getType()) 2645 return Error(ID.Loc, "operands of constexpr must have same type"); 2646 if (!Val0->getType()->isIntOrIntVectorTy()) 2647 return Error(ID.Loc, 2648 "constexpr requires integer or integer vector operands"); 2649 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 2650 ID.Kind = ValID::t_Constant; 2651 return false; 2652 } 2653 2654 case lltok::kw_getelementptr: 2655 case lltok::kw_shufflevector: 2656 case lltok::kw_insertelement: 2657 case lltok::kw_extractelement: 2658 case lltok::kw_select: { 2659 unsigned Opc = Lex.getUIntVal(); 2660 SmallVector<Constant*, 16> Elts; 2661 bool InBounds = false; 2662 Lex.Lex(); 2663 if (Opc == Instruction::GetElementPtr) 2664 InBounds = EatIfPresent(lltok::kw_inbounds); 2665 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || 2666 ParseGlobalValueVector(Elts) || 2667 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 2668 return true; 2669 2670 if (Opc == Instruction::GetElementPtr) { 2671 if (Elts.size() == 0 || 2672 !Elts[0]->getType()->getScalarType()->isPointerTy()) 2673 return Error(ID.Loc, "getelementptr requires pointer operand"); 2674 2675 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2676 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices)) 2677 return Error(ID.Loc, "invalid indices for getelementptr"); 2678 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices, 2679 InBounds); 2680 } else if (Opc == Instruction::Select) { 2681 if (Elts.size() != 3) 2682 return Error(ID.Loc, "expected three operands to select"); 2683 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 2684 Elts[2])) 2685 return Error(ID.Loc, Reason); 2686 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 2687 } else if (Opc == Instruction::ShuffleVector) { 2688 if (Elts.size() != 3) 2689 return Error(ID.Loc, "expected three operands to shufflevector"); 2690 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 2691 return Error(ID.Loc, "invalid operands to shufflevector"); 2692 ID.ConstantVal = 2693 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 2694 } else if (Opc == Instruction::ExtractElement) { 2695 if (Elts.size() != 2) 2696 return Error(ID.Loc, "expected two operands to extractelement"); 2697 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 2698 return Error(ID.Loc, "invalid extractelement operands"); 2699 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 2700 } else { 2701 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 2702 if (Elts.size() != 3) 2703 return Error(ID.Loc, "expected three operands to insertelement"); 2704 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 2705 return Error(ID.Loc, "invalid insertelement operands"); 2706 ID.ConstantVal = 2707 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 2708 } 2709 2710 ID.Kind = ValID::t_Constant; 2711 return false; 2712 } 2713 } 2714 2715 Lex.Lex(); 2716 return false; 2717 } 2718 2719 /// ParseGlobalValue - Parse a global value with the specified type. 2720 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 2721 C = 0; 2722 ValID ID; 2723 Value *V = NULL; 2724 bool Parsed = ParseValID(ID) || 2725 ConvertValIDToValue(Ty, ID, V, NULL); 2726 if (V && !(C = dyn_cast<Constant>(V))) 2727 return Error(ID.Loc, "global values must be constants"); 2728 return Parsed; 2729 } 2730 2731 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 2732 Type *Ty = 0; 2733 return ParseType(Ty) || 2734 ParseGlobalValue(Ty, V); 2735 } 2736 2737 /// ParseGlobalValueVector 2738 /// ::= /*empty*/ 2739 /// ::= TypeAndValue (',' TypeAndValue)* 2740 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { 2741 // Empty list. 2742 if (Lex.getKind() == lltok::rbrace || 2743 Lex.getKind() == lltok::rsquare || 2744 Lex.getKind() == lltok::greater || 2745 Lex.getKind() == lltok::rparen) 2746 return false; 2747 2748 Constant *C; 2749 if (ParseGlobalTypeAndValue(C)) return true; 2750 Elts.push_back(C); 2751 2752 while (EatIfPresent(lltok::comma)) { 2753 if (ParseGlobalTypeAndValue(C)) return true; 2754 Elts.push_back(C); 2755 } 2756 2757 return false; 2758 } 2759 2760 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) { 2761 assert(Lex.getKind() == lltok::lbrace); 2762 Lex.Lex(); 2763 2764 SmallVector<Value*, 16> Elts; 2765 if (ParseMDNodeVector(Elts, PFS) || 2766 ParseToken(lltok::rbrace, "expected end of metadata node")) 2767 return true; 2768 2769 ID.MDNodeVal = MDNode::get(Context, Elts); 2770 ID.Kind = ValID::t_MDNode; 2771 return false; 2772 } 2773 2774 /// ParseMetadataValue 2775 /// ::= !42 2776 /// ::= !{...} 2777 /// ::= !"string" 2778 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) { 2779 assert(Lex.getKind() == lltok::exclaim); 2780 Lex.Lex(); 2781 2782 // MDNode: 2783 // !{ ... } 2784 if (Lex.getKind() == lltok::lbrace) 2785 return ParseMetadataListValue(ID, PFS); 2786 2787 // Standalone metadata reference 2788 // !42 2789 if (Lex.getKind() == lltok::APSInt) { 2790 if (ParseMDNodeID(ID.MDNodeVal)) return true; 2791 ID.Kind = ValID::t_MDNode; 2792 return false; 2793 } 2794 2795 // MDString: 2796 // ::= '!' STRINGCONSTANT 2797 if (ParseMDString(ID.MDStringVal)) return true; 2798 ID.Kind = ValID::t_MDString; 2799 return false; 2800 } 2801 2802 2803 //===----------------------------------------------------------------------===// 2804 // Function Parsing. 2805 //===----------------------------------------------------------------------===// 2806 2807 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 2808 PerFunctionState *PFS) { 2809 if (Ty->isFunctionTy()) 2810 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 2811 2812 switch (ID.Kind) { 2813 case ValID::t_LocalID: 2814 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 2815 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc); 2816 return (V == 0); 2817 case ValID::t_LocalName: 2818 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 2819 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc); 2820 return (V == 0); 2821 case ValID::t_InlineAsm: { 2822 PointerType *PTy = dyn_cast<PointerType>(Ty); 2823 FunctionType *FTy = 2824 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; 2825 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) 2826 return Error(ID.Loc, "invalid type for inline asm constraint string"); 2827 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, 2828 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2))); 2829 return false; 2830 } 2831 case ValID::t_MDNode: 2832 if (!Ty->isMetadataTy()) 2833 return Error(ID.Loc, "metadata value must have metadata type"); 2834 V = ID.MDNodeVal; 2835 return false; 2836 case ValID::t_MDString: 2837 if (!Ty->isMetadataTy()) 2838 return Error(ID.Loc, "metadata value must have metadata type"); 2839 V = ID.MDStringVal; 2840 return false; 2841 case ValID::t_GlobalName: 2842 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 2843 return V == 0; 2844 case ValID::t_GlobalID: 2845 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 2846 return V == 0; 2847 case ValID::t_APSInt: 2848 if (!Ty->isIntegerTy()) 2849 return Error(ID.Loc, "integer constant must have integer type"); 2850 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 2851 V = ConstantInt::get(Context, ID.APSIntVal); 2852 return false; 2853 case ValID::t_APFloat: 2854 if (!Ty->isFloatingPointTy() || 2855 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 2856 return Error(ID.Loc, "floating point constant invalid for type"); 2857 2858 // The lexer has no type info, so builds all half, float, and double FP 2859 // constants as double. Fix this here. Long double does not need this. 2860 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) { 2861 bool Ignored; 2862 if (Ty->isHalfTy()) 2863 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, 2864 &Ignored); 2865 else if (Ty->isFloatTy()) 2866 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, 2867 &Ignored); 2868 } 2869 V = ConstantFP::get(Context, ID.APFloatVal); 2870 2871 if (V->getType() != Ty) 2872 return Error(ID.Loc, "floating point constant does not have type '" + 2873 getTypeString(Ty) + "'"); 2874 2875 return false; 2876 case ValID::t_Null: 2877 if (!Ty->isPointerTy()) 2878 return Error(ID.Loc, "null must be a pointer type"); 2879 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 2880 return false; 2881 case ValID::t_Undef: 2882 // FIXME: LabelTy should not be a first-class type. 2883 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 2884 return Error(ID.Loc, "invalid type for undef constant"); 2885 V = UndefValue::get(Ty); 2886 return false; 2887 case ValID::t_EmptyArray: 2888 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 2889 return Error(ID.Loc, "invalid empty array initializer"); 2890 V = UndefValue::get(Ty); 2891 return false; 2892 case ValID::t_Zero: 2893 // FIXME: LabelTy should not be a first-class type. 2894 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 2895 return Error(ID.Loc, "invalid type for null constant"); 2896 V = Constant::getNullValue(Ty); 2897 return false; 2898 case ValID::t_Constant: 2899 if (ID.ConstantVal->getType() != Ty) 2900 return Error(ID.Loc, "constant expression type mismatch"); 2901 2902 V = ID.ConstantVal; 2903 return false; 2904 case ValID::t_ConstantStruct: 2905 case ValID::t_PackedConstantStruct: 2906 if (StructType *ST = dyn_cast<StructType>(Ty)) { 2907 if (ST->getNumElements() != ID.UIntVal) 2908 return Error(ID.Loc, 2909 "initializer with struct type has wrong # elements"); 2910 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 2911 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 2912 2913 // Verify that the elements are compatible with the structtype. 2914 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 2915 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 2916 return Error(ID.Loc, "element " + Twine(i) + 2917 " of struct initializer doesn't match struct element type"); 2918 2919 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts, 2920 ID.UIntVal)); 2921 } else 2922 return Error(ID.Loc, "constant expression type mismatch"); 2923 return false; 2924 } 2925 llvm_unreachable("Invalid ValID"); 2926 } 2927 2928 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 2929 V = 0; 2930 ValID ID; 2931 return ParseValID(ID, PFS) || 2932 ConvertValIDToValue(Ty, ID, V, PFS); 2933 } 2934 2935 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 2936 Type *Ty = 0; 2937 return ParseType(Ty) || 2938 ParseValue(Ty, V, PFS); 2939 } 2940 2941 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 2942 PerFunctionState &PFS) { 2943 Value *V; 2944 Loc = Lex.getLoc(); 2945 if (ParseTypeAndValue(V, PFS)) return true; 2946 if (!isa<BasicBlock>(V)) 2947 return Error(Loc, "expected a basic block"); 2948 BB = cast<BasicBlock>(V); 2949 return false; 2950 } 2951 2952 2953 /// FunctionHeader 2954 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 2955 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 2956 /// OptionalAlign OptGC OptionalPrefix 2957 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 2958 // Parse the linkage. 2959 LocTy LinkageLoc = Lex.getLoc(); 2960 unsigned Linkage; 2961 2962 unsigned Visibility; 2963 unsigned DLLStorageClass; 2964 AttrBuilder RetAttrs; 2965 CallingConv::ID CC; 2966 Type *RetType = 0; 2967 LocTy RetTypeLoc = Lex.getLoc(); 2968 if (ParseOptionalLinkage(Linkage) || 2969 ParseOptionalVisibility(Visibility) || 2970 ParseOptionalDLLStorageClass(DLLStorageClass) || 2971 ParseOptionalCallingConv(CC) || 2972 ParseOptionalReturnAttrs(RetAttrs) || 2973 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 2974 return true; 2975 2976 // Verify that the linkage is ok. 2977 switch ((GlobalValue::LinkageTypes)Linkage) { 2978 case GlobalValue::ExternalLinkage: 2979 break; // always ok. 2980 case GlobalValue::ExternalWeakLinkage: 2981 if (isDefine) 2982 return Error(LinkageLoc, "invalid linkage for function definition"); 2983 break; 2984 case GlobalValue::PrivateLinkage: 2985 case GlobalValue::LinkerPrivateLinkage: 2986 case GlobalValue::LinkerPrivateWeakLinkage: 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' Type (',' 'inalloca')? (',' TypeAndValue)? (',' OptionalInfo)? 4075 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 4076 Value *Size = 0; 4077 LocTy SizeLoc; 4078 unsigned Alignment = 0; 4079 bool IsInAlloca = false; 4080 Type *Ty = 0; 4081 if (ParseType(Ty)) return true; 4082 4083 bool AteExtraComma = false; 4084 if (EatIfPresent(lltok::comma)) { 4085 bool HaveComma = true; 4086 if (EatIfPresent(lltok::kw_inalloca)) { 4087 IsInAlloca = true; 4088 HaveComma = EatIfPresent(lltok::comma); 4089 } 4090 4091 if (HaveComma) { 4092 if (Lex.getKind() == lltok::kw_align) { 4093 if (ParseOptionalAlignment(Alignment)) return true; 4094 } else if (Lex.getKind() == lltok::MetadataVar) { 4095 AteExtraComma = true; 4096 } else { 4097 if (ParseTypeAndValue(Size, SizeLoc, PFS) || 4098 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 4099 return true; 4100 } 4101 } 4102 } 4103 4104 if (Size && !Size->getType()->isIntegerTy()) 4105 return Error(SizeLoc, "element count must have integer type"); 4106 4107 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment); 4108 AI->setUsedWithInAlloca(IsInAlloca); 4109 Inst = AI; 4110 return AteExtraComma ? InstExtraComma : InstNormal; 4111 } 4112 4113 /// ParseLoad 4114 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 4115 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 4116 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 4117 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 4118 Value *Val; LocTy Loc; 4119 unsigned Alignment = 0; 4120 bool AteExtraComma = false; 4121 bool isAtomic = false; 4122 AtomicOrdering Ordering = NotAtomic; 4123 SynchronizationScope Scope = CrossThread; 4124 4125 if (Lex.getKind() == lltok::kw_atomic) { 4126 isAtomic = true; 4127 Lex.Lex(); 4128 } 4129 4130 bool isVolatile = false; 4131 if (Lex.getKind() == lltok::kw_volatile) { 4132 isVolatile = true; 4133 Lex.Lex(); 4134 } 4135 4136 if (ParseTypeAndValue(Val, Loc, PFS) || 4137 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 4138 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 4139 return true; 4140 4141 if (!Val->getType()->isPointerTy() || 4142 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) 4143 return Error(Loc, "load operand must be a pointer to a first class type"); 4144 if (isAtomic && !Alignment) 4145 return Error(Loc, "atomic load must have explicit non-zero alignment"); 4146 if (Ordering == Release || Ordering == AcquireRelease) 4147 return Error(Loc, "atomic load cannot use Release ordering"); 4148 4149 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope); 4150 return AteExtraComma ? InstExtraComma : InstNormal; 4151 } 4152 4153 /// ParseStore 4154 4155 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 4156 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 4157 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 4158 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 4159 Value *Val, *Ptr; LocTy Loc, PtrLoc; 4160 unsigned Alignment = 0; 4161 bool AteExtraComma = false; 4162 bool isAtomic = false; 4163 AtomicOrdering Ordering = NotAtomic; 4164 SynchronizationScope Scope = CrossThread; 4165 4166 if (Lex.getKind() == lltok::kw_atomic) { 4167 isAtomic = true; 4168 Lex.Lex(); 4169 } 4170 4171 bool isVolatile = false; 4172 if (Lex.getKind() == lltok::kw_volatile) { 4173 isVolatile = true; 4174 Lex.Lex(); 4175 } 4176 4177 if (ParseTypeAndValue(Val, Loc, PFS) || 4178 ParseToken(lltok::comma, "expected ',' after store operand") || 4179 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 4180 ParseScopeAndOrdering(isAtomic, Scope, Ordering) || 4181 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 4182 return true; 4183 4184 if (!Ptr->getType()->isPointerTy()) 4185 return Error(PtrLoc, "store operand must be a pointer"); 4186 if (!Val->getType()->isFirstClassType()) 4187 return Error(Loc, "store operand must be a first class value"); 4188 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 4189 return Error(Loc, "stored value and pointer type do not match"); 4190 if (isAtomic && !Alignment) 4191 return Error(Loc, "atomic store must have explicit non-zero alignment"); 4192 if (Ordering == Acquire || Ordering == AcquireRelease) 4193 return Error(Loc, "atomic store cannot use Acquire ordering"); 4194 4195 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope); 4196 return AteExtraComma ? InstExtraComma : InstNormal; 4197 } 4198 4199 /// ParseCmpXchg 4200 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue 4201 /// 'singlethread'? AtomicOrdering 4202 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 4203 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 4204 bool AteExtraComma = false; 4205 AtomicOrdering Ordering = NotAtomic; 4206 SynchronizationScope Scope = CrossThread; 4207 bool isVolatile = false; 4208 4209 if (EatIfPresent(lltok::kw_volatile)) 4210 isVolatile = true; 4211 4212 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 4213 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 4214 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 4215 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 4216 ParseTypeAndValue(New, NewLoc, PFS) || 4217 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering)) 4218 return true; 4219 4220 if (Ordering == Unordered) 4221 return TokError("cmpxchg cannot be unordered"); 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 = 4236 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, 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