LLVM API Documentation
00001 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the parser class for .ll files. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "LLParser.h" 00015 #include "llvm/AutoUpgrade.h" 00016 #include "llvm/CallingConv.h" 00017 #include "llvm/Constants.h" 00018 #include "llvm/DerivedTypes.h" 00019 #include "llvm/InlineAsm.h" 00020 #include "llvm/Instructions.h" 00021 #include "llvm/Module.h" 00022 #include "llvm/ValueSymbolTable.h" 00023 #include "llvm/ADT/SmallPtrSet.h" 00024 #include "llvm/ADT/StringExtras.h" 00025 #include "llvm/Support/raw_ostream.h" 00026 using namespace llvm; 00027 00028 namespace llvm { 00029 /// ValID - Represents a reference of a definition of some sort with no type. 00030 /// There are several cases where we have to parse the value but where the 00031 /// type can depend on later context. This may either be a numeric reference 00032 /// or a symbolic (%var) reference. This is just a discriminated union. 00033 struct ValID { 00034 enum { 00035 t_LocalID, t_GlobalID, // ID in UIntVal. 00036 t_LocalName, t_GlobalName, // Name in StrVal. 00037 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal. 00038 t_Null, t_Undef, t_Zero, // No value. 00039 t_EmptyArray, // No value: [] 00040 t_Constant, // Value in ConstantVal. 00041 t_InlineAsm // Value in StrVal/StrVal2/UIntVal. 00042 } Kind; 00043 00044 LLParser::LocTy Loc; 00045 unsigned UIntVal; 00046 std::string StrVal, StrVal2; 00047 APSInt APSIntVal; 00048 APFloat APFloatVal; 00049 Constant *ConstantVal; 00050 ValID() : APFloatVal(0.0) {} 00051 }; 00052 } 00053 00054 /// Run: module ::= toplevelentity* 00055 bool LLParser::Run() { 00056 // Prime the lexer. 00057 Lex.Lex(); 00058 00059 return ParseTopLevelEntities() || 00060 ValidateEndOfModule(); 00061 } 00062 00063 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the 00064 /// module. 00065 bool LLParser::ValidateEndOfModule() { 00066 if (!ForwardRefTypes.empty()) 00067 return Error(ForwardRefTypes.begin()->second.second, 00068 "use of undefined type named '" + 00069 ForwardRefTypes.begin()->first + "'"); 00070 if (!ForwardRefTypeIDs.empty()) 00071 return Error(ForwardRefTypeIDs.begin()->second.second, 00072 "use of undefined type '%" + 00073 utostr(ForwardRefTypeIDs.begin()->first) + "'"); 00074 00075 if (!ForwardRefVals.empty()) 00076 return Error(ForwardRefVals.begin()->second.second, 00077 "use of undefined value '@" + ForwardRefVals.begin()->first + 00078 "'"); 00079 00080 if (!ForwardRefValIDs.empty()) 00081 return Error(ForwardRefValIDs.begin()->second.second, 00082 "use of undefined value '@" + 00083 utostr(ForwardRefValIDs.begin()->first) + "'"); 00084 00085 // Look for intrinsic functions and CallInst that need to be upgraded 00086 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) 00087 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove 00088 00089 return false; 00090 } 00091 00092 //===----------------------------------------------------------------------===// 00093 // Top-Level Entities 00094 //===----------------------------------------------------------------------===// 00095 00096 bool LLParser::ParseTopLevelEntities() { 00097 while (1) { 00098 switch (Lex.getKind()) { 00099 default: return TokError("expected top-level entity"); 00100 case lltok::Eof: return false; 00101 //case lltok::kw_define: 00102 case lltok::kw_declare: if (ParseDeclare()) return true; break; 00103 case lltok::kw_define: if (ParseDefine()) return true; break; 00104 case lltok::kw_module: if (ParseModuleAsm()) return true; break; 00105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break; 00106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break; 00107 case lltok::kw_type: if (ParseUnnamedType()) return true; break; 00108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0 00109 case lltok::LocalVar: if (ParseNamedType()) return true; break; 00110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; 00111 00112 // The Global variable production with no name can have many different 00113 // optional leading prefixes, the production is: 00114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 00115 // OptionalAddrSpace ('constant'|'global') ... 00116 case lltok::kw_private: // OptionalLinkage 00117 case lltok::kw_internal: // OptionalLinkage 00118 case lltok::kw_weak: // OptionalLinkage 00119 case lltok::kw_linkonce: // OptionalLinkage 00120 case lltok::kw_appending: // OptionalLinkage 00121 case lltok::kw_dllexport: // OptionalLinkage 00122 case lltok::kw_common: // OptionalLinkage 00123 case lltok::kw_dllimport: // OptionalLinkage 00124 case lltok::kw_extern_weak: // OptionalLinkage 00125 case lltok::kw_external: { // OptionalLinkage 00126 unsigned Linkage, Visibility; 00127 if (ParseOptionalLinkage(Linkage) || 00128 ParseOptionalVisibility(Visibility) || 00129 ParseGlobal("", 0, Linkage, true, Visibility)) 00130 return true; 00131 break; 00132 } 00133 case lltok::kw_default: // OptionalVisibility 00134 case lltok::kw_hidden: // OptionalVisibility 00135 case lltok::kw_protected: { // OptionalVisibility 00136 unsigned Visibility; 00137 if (ParseOptionalVisibility(Visibility) || 00138 ParseGlobal("", 0, 0, false, Visibility)) 00139 return true; 00140 break; 00141 } 00142 00143 case lltok::kw_thread_local: // OptionalThreadLocal 00144 case lltok::kw_addrspace: // OptionalAddrSpace 00145 case lltok::kw_constant: // GlobalType 00146 case lltok::kw_global: // GlobalType 00147 if (ParseGlobal("", 0, 0, false, 0)) return true; 00148 break; 00149 } 00150 } 00151 } 00152 00153 00154 /// toplevelentity 00155 /// ::= 'module' 'asm' STRINGCONSTANT 00156 bool LLParser::ParseModuleAsm() { 00157 assert(Lex.getKind() == lltok::kw_module); 00158 Lex.Lex(); 00159 00160 std::string AsmStr; 00161 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 00162 ParseStringConstant(AsmStr)) return true; 00163 00164 const std::string &AsmSoFar = M->getModuleInlineAsm(); 00165 if (AsmSoFar.empty()) 00166 M->setModuleInlineAsm(AsmStr); 00167 else 00168 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr); 00169 return false; 00170 } 00171 00172 /// toplevelentity 00173 /// ::= 'target' 'triple' '=' STRINGCONSTANT 00174 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 00175 bool LLParser::ParseTargetDefinition() { 00176 assert(Lex.getKind() == lltok::kw_target); 00177 std::string Str; 00178 switch (Lex.Lex()) { 00179 default: return TokError("unknown target property"); 00180 case lltok::kw_triple: 00181 Lex.Lex(); 00182 if (ParseToken(lltok::equal, "expected '=' after target triple") || 00183 ParseStringConstant(Str)) 00184 return true; 00185 M->setTargetTriple(Str); 00186 return false; 00187 case lltok::kw_datalayout: 00188 Lex.Lex(); 00189 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 00190 ParseStringConstant(Str)) 00191 return true; 00192 M->setDataLayout(Str); 00193 return false; 00194 } 00195 } 00196 00197 /// toplevelentity 00198 /// ::= 'deplibs' '=' '[' ']' 00199 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 00200 bool LLParser::ParseDepLibs() { 00201 assert(Lex.getKind() == lltok::kw_deplibs); 00202 Lex.Lex(); 00203 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 00204 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 00205 return true; 00206 00207 if (EatIfPresent(lltok::rsquare)) 00208 return false; 00209 00210 std::string Str; 00211 if (ParseStringConstant(Str)) return true; 00212 M->addLibrary(Str); 00213 00214 while (EatIfPresent(lltok::comma)) { 00215 if (ParseStringConstant(Str)) return true; 00216 M->addLibrary(Str); 00217 } 00218 00219 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 00220 } 00221 00222 /// toplevelentity 00223 /// ::= 'type' type 00224 bool LLParser::ParseUnnamedType() { 00225 assert(Lex.getKind() == lltok::kw_type); 00226 LocTy TypeLoc = Lex.getLoc(); 00227 Lex.Lex(); // eat kw_type 00228 00229 PATypeHolder Ty(Type::VoidTy); 00230 if (ParseType(Ty)) return true; 00231 00232 unsigned TypeID = NumberedTypes.size(); 00233 00234 // We don't allow assigning names to void type 00235 if (Ty == Type::VoidTy) 00236 return Error(TypeLoc, "can't assign name to the void type"); 00237 00238 // See if this type was previously referenced. 00239 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator 00240 FI = ForwardRefTypeIDs.find(TypeID); 00241 if (FI != ForwardRefTypeIDs.end()) { 00242 if (FI->second.first.get() == Ty) 00243 return Error(TypeLoc, "self referential type is invalid"); 00244 00245 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty); 00246 Ty = FI->second.first.get(); 00247 ForwardRefTypeIDs.erase(FI); 00248 } 00249 00250 NumberedTypes.push_back(Ty); 00251 00252 return false; 00253 } 00254 00255 /// toplevelentity 00256 /// ::= LocalVar '=' 'type' type 00257 bool LLParser::ParseNamedType() { 00258 std::string Name = Lex.getStrVal(); 00259 LocTy NameLoc = Lex.getLoc(); 00260 Lex.Lex(); // eat LocalVar. 00261 00262 PATypeHolder Ty(Type::VoidTy); 00263 00264 if (ParseToken(lltok::equal, "expected '=' after name") || 00265 ParseToken(lltok::kw_type, "expected 'type' after name") || 00266 ParseType(Ty)) 00267 return true; 00268 00269 // We don't allow assigning names to void type 00270 if (Ty == Type::VoidTy) 00271 return Error(NameLoc, "can't assign name '" + Name + "' to the void type"); 00272 00273 // Set the type name, checking for conflicts as we do so. 00274 bool AlreadyExists = M->addTypeName(Name, Ty); 00275 if (!AlreadyExists) return false; 00276 00277 // See if this type is a forward reference. We need to eagerly resolve 00278 // types to allow recursive type redefinitions below. 00279 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator 00280 FI = ForwardRefTypes.find(Name); 00281 if (FI != ForwardRefTypes.end()) { 00282 if (FI->second.first.get() == Ty) 00283 return Error(NameLoc, "self referential type is invalid"); 00284 00285 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty); 00286 Ty = FI->second.first.get(); 00287 ForwardRefTypes.erase(FI); 00288 } 00289 00290 // Inserting a name that is already defined, get the existing name. 00291 const Type *Existing = M->getTypeByName(Name); 00292 assert(Existing && "Conflict but no matching type?!"); 00293 00294 // Otherwise, this is an attempt to redefine a type. That's okay if 00295 // the redefinition is identical to the original. 00296 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0 00297 if (Existing == Ty) return false; 00298 00299 // Any other kind of (non-equivalent) redefinition is an error. 00300 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" + 00301 Ty->getDescription() + "'"); 00302 } 00303 00304 00305 /// toplevelentity 00306 /// ::= 'declare' FunctionHeader 00307 bool LLParser::ParseDeclare() { 00308 assert(Lex.getKind() == lltok::kw_declare); 00309 Lex.Lex(); 00310 00311 Function *F; 00312 return ParseFunctionHeader(F, false); 00313 } 00314 00315 /// toplevelentity 00316 /// ::= 'define' FunctionHeader '{' ... 00317 bool LLParser::ParseDefine() { 00318 assert(Lex.getKind() == lltok::kw_define); 00319 Lex.Lex(); 00320 00321 Function *F; 00322 return ParseFunctionHeader(F, true) || 00323 ParseFunctionBody(*F); 00324 } 00325 00326 /// ParseGlobalType 00327 /// ::= 'constant' 00328 /// ::= 'global' 00329 bool LLParser::ParseGlobalType(bool &IsConstant) { 00330 if (Lex.getKind() == lltok::kw_constant) 00331 IsConstant = true; 00332 else if (Lex.getKind() == lltok::kw_global) 00333 IsConstant = false; 00334 else 00335 return TokError("expected 'global' or 'constant'"); 00336 Lex.Lex(); 00337 return false; 00338 } 00339 00340 /// ParseNamedGlobal: 00341 /// GlobalVar '=' OptionalVisibility ALIAS ... 00342 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable 00343 bool LLParser::ParseNamedGlobal() { 00344 assert(Lex.getKind() == lltok::GlobalVar); 00345 LocTy NameLoc = Lex.getLoc(); 00346 std::string Name = Lex.getStrVal(); 00347 Lex.Lex(); 00348 00349 bool HasLinkage; 00350 unsigned Linkage, Visibility; 00351 if (ParseToken(lltok::equal, "expected '=' in global variable") || 00352 ParseOptionalLinkage(Linkage, HasLinkage) || 00353 ParseOptionalVisibility(Visibility)) 00354 return true; 00355 00356 if (HasLinkage || Lex.getKind() != lltok::kw_alias) 00357 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); 00358 return ParseAlias(Name, NameLoc, Visibility); 00359 } 00360 00361 /// ParseAlias: 00362 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee 00363 /// Aliasee 00364 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')' 00365 /// 00366 /// Everything through visibility has already been parsed. 00367 /// 00368 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, 00369 unsigned Visibility) { 00370 assert(Lex.getKind() == lltok::kw_alias); 00371 Lex.Lex(); 00372 unsigned Linkage; 00373 LocTy LinkageLoc = Lex.getLoc(); 00374 if (ParseOptionalLinkage(Linkage)) 00375 return true; 00376 00377 if (Linkage != GlobalValue::ExternalLinkage && 00378 Linkage != GlobalValue::WeakLinkage && 00379 Linkage != GlobalValue::InternalLinkage && 00380 Linkage != GlobalValue::PrivateLinkage) 00381 return Error(LinkageLoc, "invalid linkage type for alias"); 00382 00383 Constant *Aliasee; 00384 LocTy AliaseeLoc = Lex.getLoc(); 00385 if (Lex.getKind() != lltok::kw_bitcast) { 00386 if (ParseGlobalTypeAndValue(Aliasee)) return true; 00387 } else { 00388 // The bitcast dest type is not present, it is implied by the dest type. 00389 ValID ID; 00390 if (ParseValID(ID)) return true; 00391 if (ID.Kind != ValID::t_Constant) 00392 return Error(AliaseeLoc, "invalid aliasee"); 00393 Aliasee = ID.ConstantVal; 00394 } 00395 00396 if (!isa<PointerType>(Aliasee->getType())) 00397 return Error(AliaseeLoc, "alias must have pointer type"); 00398 00399 // Okay, create the alias but do not insert it into the module yet. 00400 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), 00401 (GlobalValue::LinkageTypes)Linkage, Name, 00402 Aliasee); 00403 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 00404 00405 // See if this value already exists in the symbol table. If so, it is either 00406 // a redefinition or a definition of a forward reference. 00407 if (GlobalValue *Val = 00408 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) { 00409 // See if this was a redefinition. If so, there is no entry in 00410 // ForwardRefVals. 00411 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 00412 I = ForwardRefVals.find(Name); 00413 if (I == ForwardRefVals.end()) 00414 return Error(NameLoc, "redefinition of global named '@" + Name + "'"); 00415 00416 // Otherwise, this was a definition of forward ref. Verify that types 00417 // agree. 00418 if (Val->getType() != GA->getType()) 00419 return Error(NameLoc, 00420 "forward reference and definition of alias have different types"); 00421 00422 // If they agree, just RAUW the old value with the alias and remove the 00423 // forward ref info. 00424 Val->replaceAllUsesWith(GA); 00425 Val->eraseFromParent(); 00426 ForwardRefVals.erase(I); 00427 } 00428 00429 // Insert into the module, we know its name won't collide now. 00430 M->getAliasList().push_back(GA); 00431 assert(GA->getNameStr() == Name && "Should not be a name conflict!"); 00432 00433 return false; 00434 } 00435 00436 /// ParseGlobal 00437 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal 00438 /// OptionalAddrSpace GlobalType Type Const 00439 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal 00440 /// OptionalAddrSpace GlobalType Type Const 00441 /// 00442 /// Everything through visibility has been parsed already. 00443 /// 00444 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 00445 unsigned Linkage, bool HasLinkage, 00446 unsigned Visibility) { 00447 unsigned AddrSpace; 00448 bool ThreadLocal, IsConstant; 00449 LocTy TyLoc; 00450 00451 PATypeHolder Ty(Type::VoidTy); 00452 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) || 00453 ParseOptionalAddrSpace(AddrSpace) || 00454 ParseGlobalType(IsConstant) || 00455 ParseType(Ty, TyLoc)) 00456 return true; 00457 00458 // If the linkage is specified and is external, then no initializer is 00459 // present. 00460 Constant *Init = 0; 00461 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage && 00462 Linkage != GlobalValue::ExternalWeakLinkage && 00463 Linkage != GlobalValue::ExternalLinkage)) { 00464 if (ParseGlobalValue(Ty, Init)) 00465 return true; 00466 } 00467 00468 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy) 00469 return Error(TyLoc, "invald type for global variable"); 00470 00471 GlobalVariable *GV = 0; 00472 00473 // See if the global was forward referenced, if so, use the global. 00474 if (!Name.empty()) { 00475 if ((GV = M->getGlobalVariable(Name, true)) && 00476 !ForwardRefVals.erase(Name)) 00477 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 00478 } else { 00479 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 00480 I = ForwardRefValIDs.find(NumberedVals.size()); 00481 if (I != ForwardRefValIDs.end()) { 00482 GV = cast<GlobalVariable>(I->second.first); 00483 ForwardRefValIDs.erase(I); 00484 } 00485 } 00486 00487 if (GV == 0) { 00488 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name, 00489 M, false, AddrSpace); 00490 } else { 00491 if (GV->getType()->getElementType() != Ty) 00492 return Error(TyLoc, 00493 "forward reference and definition of global have different types"); 00494 00495 // Move the forward-reference to the correct spot in the module. 00496 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 00497 } 00498 00499 if (Name.empty()) 00500 NumberedVals.push_back(GV); 00501 00502 // Set the parsed properties on the global. 00503 if (Init) 00504 GV->setInitializer(Init); 00505 GV->setConstant(IsConstant); 00506 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 00507 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 00508 GV->setThreadLocal(ThreadLocal); 00509 00510 // Parse attributes on the global. 00511 while (Lex.getKind() == lltok::comma) { 00512 Lex.Lex(); 00513 00514 if (Lex.getKind() == lltok::kw_section) { 00515 Lex.Lex(); 00516 GV->setSection(Lex.getStrVal()); 00517 if (ParseToken(lltok::StringConstant, "expected global section string")) 00518 return true; 00519 } else if (Lex.getKind() == lltok::kw_align) { 00520 unsigned Alignment; 00521 if (ParseOptionalAlignment(Alignment)) return true; 00522 GV->setAlignment(Alignment); 00523 } else { 00524 TokError("unknown global variable property!"); 00525 } 00526 } 00527 00528 return false; 00529 } 00530 00531 00532 //===----------------------------------------------------------------------===// 00533 // GlobalValue Reference/Resolution Routines. 00534 //===----------------------------------------------------------------------===// 00535 00536 /// GetGlobalVal - Get a value with the specified name or ID, creating a 00537 /// forward reference record if needed. This can return null if the value 00538 /// exists but does not have the right type. 00539 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, 00540 LocTy Loc) { 00541 const PointerType *PTy = dyn_cast<PointerType>(Ty); 00542 if (PTy == 0) { 00543 Error(Loc, "global variable reference must have pointer type"); 00544 return 0; 00545 } 00546 00547 // Look this name up in the normal function symbol table. 00548 GlobalValue *Val = 00549 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 00550 00551 // If this is a forward reference for the value, see if we already created a 00552 // forward ref record. 00553 if (Val == 0) { 00554 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator 00555 I = ForwardRefVals.find(Name); 00556 if (I != ForwardRefVals.end()) 00557 Val = I->second.first; 00558 } 00559 00560 // If we have the value in the symbol table or fwd-ref table, return it. 00561 if (Val) { 00562 if (Val->getType() == Ty) return Val; 00563 Error(Loc, "'@" + Name + "' defined with type '" + 00564 Val->getType()->getDescription() + "'"); 00565 return 0; 00566 } 00567 00568 // Otherwise, create a new forward reference for this value and remember it. 00569 GlobalValue *FwdVal; 00570 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { 00571 // Function types can return opaque but functions can't. 00572 if (isa<OpaqueType>(FT->getReturnType())) { 00573 Error(Loc, "function may not return opaque type"); 00574 return 0; 00575 } 00576 00577 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 00578 } else { 00579 FwdVal = new GlobalVariable(PTy->getElementType(), false, 00580 GlobalValue::ExternalWeakLinkage, 0, Name, M); 00581 } 00582 00583 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 00584 return FwdVal; 00585 } 00586 00587 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { 00588 const PointerType *PTy = dyn_cast<PointerType>(Ty); 00589 if (PTy == 0) { 00590 Error(Loc, "global variable reference must have pointer type"); 00591 return 0; 00592 } 00593 00594 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 00595 00596 // If this is a forward reference for the value, see if we already created a 00597 // forward ref record. 00598 if (Val == 0) { 00599 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator 00600 I = ForwardRefValIDs.find(ID); 00601 if (I != ForwardRefValIDs.end()) 00602 Val = I->second.first; 00603 } 00604 00605 // If we have the value in the symbol table or fwd-ref table, return it. 00606 if (Val) { 00607 if (Val->getType() == Ty) return Val; 00608 Error(Loc, "'@" + utostr(ID) + "' defined with type '" + 00609 Val->getType()->getDescription() + "'"); 00610 return 0; 00611 } 00612 00613 // Otherwise, create a new forward reference for this value and remember it. 00614 GlobalValue *FwdVal; 00615 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) { 00616 // Function types can return opaque but functions can't. 00617 if (isa<OpaqueType>(FT->getReturnType())) { 00618 Error(Loc, "function may not return opaque type"); 00619 return 0; 00620 } 00621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M); 00622 } else { 00623 FwdVal = new GlobalVariable(PTy->getElementType(), false, 00624 GlobalValue::ExternalWeakLinkage, 0, "", M); 00625 } 00626 00627 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 00628 return FwdVal; 00629 } 00630 00631 00632 //===----------------------------------------------------------------------===// 00633 // Helper Routines. 00634 //===----------------------------------------------------------------------===// 00635 00636 /// ParseToken - If the current token has the specified kind, eat it and return 00637 /// success. Otherwise, emit the specified error and return failure. 00638 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 00639 if (Lex.getKind() != T) 00640 return TokError(ErrMsg); 00641 Lex.Lex(); 00642 return false; 00643 } 00644 00645 /// ParseStringConstant 00646 /// ::= StringConstant 00647 bool LLParser::ParseStringConstant(std::string &Result) { 00648 if (Lex.getKind() != lltok::StringConstant) 00649 return TokError("expected string constant"); 00650 Result = Lex.getStrVal(); 00651 Lex.Lex(); 00652 return false; 00653 } 00654 00655 /// ParseUInt32 00656 /// ::= uint32 00657 bool LLParser::ParseUInt32(unsigned &Val) { 00658 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 00659 return TokError("expected integer"); 00660 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 00661 if (Val64 != unsigned(Val64)) 00662 return TokError("expected 32-bit integer (too large)"); 00663 Val = Val64; 00664 Lex.Lex(); 00665 return false; 00666 } 00667 00668 00669 /// ParseOptionalAddrSpace 00670 /// := /*empty*/ 00671 /// := 'addrspace' '(' uint32 ')' 00672 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 00673 AddrSpace = 0; 00674 if (!EatIfPresent(lltok::kw_addrspace)) 00675 return false; 00676 return ParseToken(lltok::lparen, "expected '(' in address space") || 00677 ParseUInt32(AddrSpace) || 00678 ParseToken(lltok::rparen, "expected ')' in address space"); 00679 } 00680 00681 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind 00682 /// indicates what kind of attribute list this is: 0: function arg, 1: result, 00683 /// 2: function attr. 00684 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { 00685 Attrs = Attribute::None; 00686 LocTy AttrLoc = Lex.getLoc(); 00687 00688 while (1) { 00689 switch (Lex.getKind()) { 00690 case lltok::kw_sext: 00691 case lltok::kw_zext: 00692 // Treat these as signext/zeroext unless they are function attrs. 00693 // FIXME: REMOVE THIS IN LLVM 3.0 00694 if (AttrKind != 2) { 00695 if (Lex.getKind() == lltok::kw_sext) 00696 Attrs |= Attribute::SExt; 00697 else 00698 Attrs |= Attribute::ZExt; 00699 break; 00700 } 00701 // FALL THROUGH. 00702 default: // End of attributes. 00703 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly)) 00704 return Error(AttrLoc, "invalid use of function-only attribute"); 00705 00706 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly)) 00707 return Error(AttrLoc, "invalid use of parameter-only attribute"); 00708 00709 return false; 00710 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break; 00711 case lltok::kw_signext: Attrs |= Attribute::SExt; break; 00712 case lltok::kw_inreg: Attrs |= Attribute::InReg; break; 00713 case lltok::kw_sret: Attrs |= Attribute::StructRet; break; 00714 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break; 00715 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break; 00716 case lltok::kw_byval: Attrs |= Attribute::ByVal; break; 00717 case lltok::kw_nest: Attrs |= Attribute::Nest; break; 00718 00719 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break; 00720 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break; 00721 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break; 00722 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break; 00723 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break; 00724 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break; 00725 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break; 00726 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break; 00727 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break; 00728 00729 00730 case lltok::kw_align: { 00731 unsigned Alignment; 00732 if (ParseOptionalAlignment(Alignment)) 00733 return true; 00734 Attrs |= Attribute::constructAlignmentFromInt(Alignment); 00735 continue; 00736 } 00737 } 00738 Lex.Lex(); 00739 } 00740 } 00741 00742 /// ParseOptionalLinkage 00743 /// ::= /*empty*/ 00744 /// ::= 'private' 00745 /// ::= 'internal' 00746 /// ::= 'weak' 00747 /// ::= 'linkonce' 00748 /// ::= 'appending' 00749 /// ::= 'dllexport' 00750 /// ::= 'common' 00751 /// ::= 'dllimport' 00752 /// ::= 'extern_weak' 00753 /// ::= 'external' 00754 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { 00755 HasLinkage = false; 00756 switch (Lex.getKind()) { 00757 default: Res = GlobalValue::ExternalLinkage; return false; 00758 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break; 00759 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break; 00760 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break; 00761 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break; 00762 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break; 00763 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break; 00764 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break; 00765 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break; 00766 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break; 00767 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break; 00768 } 00769 Lex.Lex(); 00770 HasLinkage = true; 00771 return false; 00772 } 00773 00774 /// ParseOptionalVisibility 00775 /// ::= /*empty*/ 00776 /// ::= 'default' 00777 /// ::= 'hidden' 00778 /// ::= 'protected' 00779 /// 00780 bool LLParser::ParseOptionalVisibility(unsigned &Res) { 00781 switch (Lex.getKind()) { 00782 default: Res = GlobalValue::DefaultVisibility; return false; 00783 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break; 00784 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break; 00785 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break; 00786 } 00787 Lex.Lex(); 00788 return false; 00789 } 00790 00791 /// ParseOptionalCallingConv 00792 /// ::= /*empty*/ 00793 /// ::= 'ccc' 00794 /// ::= 'fastcc' 00795 /// ::= 'coldcc' 00796 /// ::= 'x86_stdcallcc' 00797 /// ::= 'x86_fastcallcc' 00798 /// ::= 'cc' UINT 00799 /// 00800 bool LLParser::ParseOptionalCallingConv(unsigned &CC) { 00801 switch (Lex.getKind()) { 00802 default: CC = CallingConv::C; return false; 00803 case lltok::kw_ccc: CC = CallingConv::C; break; 00804 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 00805 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 00806 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 00807 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 00808 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC); 00809 } 00810 Lex.Lex(); 00811 return false; 00812 } 00813 00814 /// ParseOptionalAlignment 00815 /// ::= /* empty */ 00816 /// ::= 'align' 4 00817 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 00818 Alignment = 0; 00819 if (!EatIfPresent(lltok::kw_align)) 00820 return false; 00821 LocTy AlignLoc = Lex.getLoc(); 00822 if (ParseUInt32(Alignment)) return true; 00823 if (!isPowerOf2_32(Alignment)) 00824 return Error(AlignLoc, "alignment is not a power of two"); 00825 return false; 00826 } 00827 00828 /// ParseOptionalCommaAlignment 00829 /// ::= /* empty */ 00830 /// ::= ',' 'align' 4 00831 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) { 00832 Alignment = 0; 00833 if (!EatIfPresent(lltok::comma)) 00834 return false; 00835 return ParseToken(lltok::kw_align, "expected 'align'") || 00836 ParseUInt32(Alignment); 00837 } 00838 00839 /// ParseIndexList 00840 /// ::= (',' uint32)+ 00841 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) { 00842 if (Lex.getKind() != lltok::comma) 00843 return TokError("expected ',' as start of index list"); 00844 00845 while (EatIfPresent(lltok::comma)) { 00846 unsigned Idx; 00847 if (ParseUInt32(Idx)) return true; 00848 Indices.push_back(Idx); 00849 } 00850 00851 return false; 00852 } 00853 00854 //===----------------------------------------------------------------------===// 00855 // Type Parsing. 00856 //===----------------------------------------------------------------------===// 00857 00858 /// ParseType - Parse and resolve a full type. 00859 bool LLParser::ParseType(PATypeHolder &Result) { 00860 if (ParseTypeRec(Result)) return true; 00861 00862 // Verify no unresolved uprefs. 00863 if (!UpRefs.empty()) 00864 return Error(UpRefs.back().Loc, "invalid unresolved type up reference"); 00865 00866 return false; 00867 } 00868 00869 /// HandleUpRefs - Every time we finish a new layer of types, this function is 00870 /// called. It loops through the UpRefs vector, which is a list of the 00871 /// currently active types. For each type, if the up-reference is contained in 00872 /// the newly completed type, we decrement the level count. When the level 00873 /// count reaches zero, the up-referenced type is the type that is passed in: 00874 /// thus we can complete the cycle. 00875 /// 00876 PATypeHolder LLParser::HandleUpRefs(const Type *ty) { 00877 // If Ty isn't abstract, or if there are no up-references in it, then there is 00878 // nothing to resolve here. 00879 if (!ty->isAbstract() || UpRefs.empty()) return ty; 00880 00881 PATypeHolder Ty(ty); 00882 #if 0 00883 errs() << "Type '" << Ty->getDescription() 00884 << "' newly formed. Resolving upreferences.\n" 00885 << UpRefs.size() << " upreferences active!\n"; 00886 #endif 00887 00888 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes 00889 // to zero), we resolve them all together before we resolve them to Ty. At 00890 // the end of the loop, if there is anything to resolve to Ty, it will be in 00891 // this variable. 00892 OpaqueType *TypeToResolve = 0; 00893 00894 for (unsigned i = 0; i != UpRefs.size(); ++i) { 00895 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'. 00896 bool ContainsType = 00897 std::find(Ty->subtype_begin(), Ty->subtype_end(), 00898 UpRefs[i].LastContainedTy) != Ty->subtype_end(); 00899 00900 #if 0 00901 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " 00902 << UpRefs[i].LastContainedTy->getDescription() << ") = " 00903 << (ContainsType ? "true" : "false") 00904 << " level=" << UpRefs[i].NestingLevel << "\n"; 00905 #endif 00906 if (!ContainsType) 00907 continue; 00908 00909 // Decrement level of upreference 00910 unsigned Level = --UpRefs[i].NestingLevel; 00911 UpRefs[i].LastContainedTy = Ty; 00912 00913 // If the Up-reference has a non-zero level, it shouldn't be resolved yet. 00914 if (Level != 0) 00915 continue; 00916 00917 #if 0 00918 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n"; 00919 #endif 00920 if (!TypeToResolve) 00921 TypeToResolve = UpRefs[i].UpRefTy; 00922 else 00923 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve); 00924 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list. 00925 --i; // Do not skip the next element. 00926 } 00927 00928 if (TypeToResolve) 00929 TypeToResolve->refineAbstractTypeTo(Ty); 00930 00931 return Ty; 00932 } 00933 00934 00935 /// ParseTypeRec - The recursive function used to process the internal 00936 /// implementation details of types. 00937 bool LLParser::ParseTypeRec(PATypeHolder &Result) { 00938 switch (Lex.getKind()) { 00939 default: 00940 return TokError("expected type"); 00941 case lltok::Type: 00942 // TypeRec ::= 'float' | 'void' (etc) 00943 Result = Lex.getTyVal(); 00944 Lex.Lex(); 00945 break; 00946 case lltok::kw_opaque: 00947 // TypeRec ::= 'opaque' 00948 Result = OpaqueType::get(); 00949 Lex.Lex(); 00950 break; 00951 case lltok::lbrace: 00952 // TypeRec ::= '{' ... '}' 00953 if (ParseStructType(Result, false)) 00954 return true; 00955 break; 00956 case lltok::lsquare: 00957 // TypeRec ::= '[' ... ']' 00958 Lex.Lex(); // eat the lsquare. 00959 if (ParseArrayVectorType(Result, false)) 00960 return true; 00961 break; 00962 case lltok::less: // Either vector or packed struct. 00963 // TypeRec ::= '<' ... '>' 00964 Lex.Lex(); 00965 if (Lex.getKind() == lltok::lbrace) { 00966 if (ParseStructType(Result, true) || 00967 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 00968 return true; 00969 } else if (ParseArrayVectorType(Result, true)) 00970 return true; 00971 break; 00972 case lltok::LocalVar: 00973 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0 00974 // TypeRec ::= %foo 00975 if (const Type *T = M->getTypeByName(Lex.getStrVal())) { 00976 Result = T; 00977 } else { 00978 Result = OpaqueType::get(); 00979 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(), 00980 std::make_pair(Result, 00981 Lex.getLoc()))); 00982 M->addTypeName(Lex.getStrVal(), Result.get()); 00983 } 00984 Lex.Lex(); 00985 break; 00986 00987 case lltok::LocalVarID: 00988 // TypeRec ::= %4 00989 if (Lex.getUIntVal() < NumberedTypes.size()) 00990 Result = NumberedTypes[Lex.getUIntVal()]; 00991 else { 00992 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator 00993 I = ForwardRefTypeIDs.find(Lex.getUIntVal()); 00994 if (I != ForwardRefTypeIDs.end()) 00995 Result = I->second.first; 00996 else { 00997 Result = OpaqueType::get(); 00998 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(), 00999 std::make_pair(Result, 01000 Lex.getLoc()))); 01001 } 01002 } 01003 Lex.Lex(); 01004 break; 01005 case lltok::backslash: { 01006 // TypeRec ::= '\' 4 01007 Lex.Lex(); 01008 unsigned Val; 01009 if (ParseUInt32(Val)) return true; 01010 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder. 01011 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT)); 01012 Result = OT; 01013 break; 01014 } 01015 } 01016 01017 // Parse the type suffixes. 01018 while (1) { 01019 switch (Lex.getKind()) { 01020 // End of type. 01021 default: return false; 01022 01023 // TypeRec ::= TypeRec '*' 01024 case lltok::star: 01025 if (Result.get() == Type::LabelTy) 01026 return TokError("basic block pointers are invalid"); 01027 Result = HandleUpRefs(PointerType::getUnqual(Result.get())); 01028 Lex.Lex(); 01029 break; 01030 01031 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*' 01032 case lltok::kw_addrspace: { 01033 if (Result.get() == Type::LabelTy) 01034 return TokError("basic block pointers are invalid"); 01035 unsigned AddrSpace; 01036 if (ParseOptionalAddrSpace(AddrSpace) || 01037 ParseToken(lltok::star, "expected '*' in address space")) 01038 return true; 01039 01040 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace)); 01041 break; 01042 } 01043 01044 /// Types '(' ArgTypeListI ')' OptFuncAttrs 01045 case lltok::lparen: 01046 if (ParseFunctionType(Result)) 01047 return true; 01048 break; 01049 } 01050 } 01051 } 01052 01053 /// ParseParameterList 01054 /// ::= '(' ')' 01055 /// ::= '(' Arg (',' Arg)* ')' 01056 /// Arg 01057 /// ::= Type OptionalAttributes Value OptionalAttributes 01058 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 01059 PerFunctionState &PFS) { 01060 if (ParseToken(lltok::lparen, "expected '(' in call")) 01061 return true; 01062 01063 while (Lex.getKind() != lltok::rparen) { 01064 // If this isn't the first argument, we need a comma. 01065 if (!ArgList.empty() && 01066 ParseToken(lltok::comma, "expected ',' in argument list")) 01067 return true; 01068 01069 // Parse the argument. 01070 LocTy ArgLoc; 01071 PATypeHolder ArgTy(Type::VoidTy); 01072 unsigned ArgAttrs1, ArgAttrs2; 01073 Value *V; 01074 if (ParseType(ArgTy, ArgLoc) || 01075 ParseOptionalAttrs(ArgAttrs1, 0) || 01076 ParseValue(ArgTy, V, PFS) || 01077 // FIXME: Should not allow attributes after the argument, remove this in 01078 // LLVM 3.0. 01079 ParseOptionalAttrs(ArgAttrs2, 0)) 01080 return true; 01081 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2)); 01082 } 01083 01084 Lex.Lex(); // Lex the ')'. 01085 return false; 01086 } 01087 01088 01089 01090 /// ParseArgumentList - Parse the argument list for a function type or function 01091 /// prototype. If 'inType' is true then we are parsing a FunctionType. 01092 /// ::= '(' ArgTypeListI ')' 01093 /// ArgTypeListI 01094 /// ::= /*empty*/ 01095 /// ::= '...' 01096 /// ::= ArgTypeList ',' '...' 01097 /// ::= ArgType (',' ArgType)* 01098 /// 01099 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList, 01100 bool &isVarArg, bool inType) { 01101 isVarArg = false; 01102 assert(Lex.getKind() == lltok::lparen); 01103 Lex.Lex(); // eat the (. 01104 01105 if (Lex.getKind() == lltok::rparen) { 01106 // empty 01107 } else if (Lex.getKind() == lltok::dotdotdot) { 01108 isVarArg = true; 01109 Lex.Lex(); 01110 } else { 01111 LocTy TypeLoc = Lex.getLoc(); 01112 PATypeHolder ArgTy(Type::VoidTy); 01113 unsigned Attrs; 01114 std::string Name; 01115 01116 // If we're parsing a type, use ParseTypeRec, because we allow recursive 01117 // types (such as a function returning a pointer to itself). If parsing a 01118 // function prototype, we require fully resolved types. 01119 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || 01120 ParseOptionalAttrs(Attrs, 0)) return true; 01121 01122 if (Lex.getKind() == lltok::LocalVar || 01123 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 01124 Name = Lex.getStrVal(); 01125 Lex.Lex(); 01126 } 01127 01128 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) 01129 return Error(TypeLoc, "invalid type for function argument"); 01130 01131 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 01132 01133 while (EatIfPresent(lltok::comma)) { 01134 // Handle ... at end of arg list. 01135 if (EatIfPresent(lltok::dotdotdot)) { 01136 isVarArg = true; 01137 break; 01138 } 01139 01140 // Otherwise must be an argument type. 01141 TypeLoc = Lex.getLoc(); 01142 if (ParseTypeRec(ArgTy) || 01143 ParseOptionalAttrs(Attrs, 0)) return true; 01144 01145 if (Lex.getKind() == lltok::LocalVar || 01146 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 01147 Name = Lex.getStrVal(); 01148 Lex.Lex(); 01149 } else { 01150 Name = ""; 01151 } 01152 01153 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) 01154 return Error(TypeLoc, "invalid type for function argument"); 01155 01156 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); 01157 } 01158 } 01159 01160 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 01161 } 01162 01163 /// ParseFunctionType 01164 /// ::= Type ArgumentList OptionalAttrs 01165 bool LLParser::ParseFunctionType(PATypeHolder &Result) { 01166 assert(Lex.getKind() == lltok::lparen); 01167 01168 if (!FunctionType::isValidReturnType(Result)) 01169 return TokError("invalid function return type"); 01170 01171 std::vector<ArgInfo> ArgList; 01172 bool isVarArg; 01173 unsigned Attrs; 01174 if (ParseArgumentList(ArgList, isVarArg, true) || 01175 // FIXME: Allow, but ignore attributes on function types! 01176 // FIXME: Remove in LLVM 3.0 01177 ParseOptionalAttrs(Attrs, 2)) 01178 return true; 01179 01180 // Reject names on the arguments lists. 01181 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 01182 if (!ArgList[i].Name.empty()) 01183 return Error(ArgList[i].Loc, "argument name invalid in function type"); 01184 if (!ArgList[i].Attrs != 0) { 01185 // Allow but ignore attributes on function types; this permits 01186 // auto-upgrade. 01187 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0 01188 } 01189 } 01190 01191 std::vector<const Type*> ArgListTy; 01192 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 01193 ArgListTy.push_back(ArgList[i].Type); 01194 01195 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg)); 01196 return false; 01197 } 01198 01199 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 01200 /// TypeRec 01201 /// ::= '{' '}' 01202 /// ::= '{' TypeRec (',' TypeRec)* '}' 01203 /// ::= '<' '{' '}' '>' 01204 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>' 01205 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { 01206 assert(Lex.getKind() == lltok::lbrace); 01207 Lex.Lex(); // Consume the '{' 01208 01209 if (EatIfPresent(lltok::rbrace)) { 01210 Result = StructType::get(std::vector<const Type*>(), Packed); 01211 return false; 01212 } 01213 01214 std::vector<PATypeHolder> ParamsList; 01215 if (ParseTypeRec(Result)) return true; 01216 ParamsList.push_back(Result); 01217 01218 while (EatIfPresent(lltok::comma)) { 01219 if (ParseTypeRec(Result)) return true; 01220 ParamsList.push_back(Result); 01221 } 01222 01223 if (ParseToken(lltok::rbrace, "expected '}' at end of struct")) 01224 return true; 01225 01226 std::vector<const Type*> ParamsListTy; 01227 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i) 01228 ParamsListTy.push_back(ParamsList[i].get()); 01229 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed)); 01230 return false; 01231 } 01232 01233 /// ParseArrayVectorType - Parse an array or vector type, assuming the first 01234 /// token has already been consumed. 01235 /// TypeRec 01236 /// ::= '[' APSINTVAL 'x' Types ']' 01237 /// ::= '<' APSINTVAL 'x' Types '>' 01238 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) { 01239 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 01240 Lex.getAPSIntVal().getBitWidth() > 64) 01241 return TokError("expected number in address space"); 01242 01243 LocTy SizeLoc = Lex.getLoc(); 01244 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 01245 Lex.Lex(); 01246 01247 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 01248 return true; 01249 01250 LocTy TypeLoc = Lex.getLoc(); 01251 PATypeHolder EltTy(Type::VoidTy); 01252 if (ParseTypeRec(EltTy)) return true; 01253 01254 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 01255 "expected end of sequential type")) 01256 return true; 01257 01258 if (isVector) { 01259 if ((unsigned)Size != Size) 01260 return Error(SizeLoc, "size too large for vector"); 01261 if (!EltTy->isFloatingPoint() && !EltTy->isInteger()) 01262 return Error(TypeLoc, "vector element type must be fp or integer"); 01263 Result = VectorType::get(EltTy, unsigned(Size)); 01264 } else { 01265 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy)) 01266 return Error(TypeLoc, "invalid array element type"); 01267 Result = HandleUpRefs(ArrayType::get(EltTy, Size)); 01268 } 01269 return false; 01270 } 01271 01272 //===----------------------------------------------------------------------===// 01273 // Function Semantic Analysis. 01274 //===----------------------------------------------------------------------===// 01275 01276 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f) 01277 : P(p), F(f) { 01278 01279 // Insert unnamed arguments into the NumberedVals list. 01280 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 01281 AI != E; ++AI) 01282 if (!AI->hasName()) 01283 NumberedVals.push_back(AI); 01284 } 01285 01286 LLParser::PerFunctionState::~PerFunctionState() { 01287 // If there were any forward referenced non-basicblock values, delete them. 01288 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator 01289 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I) 01290 if (!isa<BasicBlock>(I->second.first)) { 01291 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first 01292 ->getType())); 01293 delete I->second.first; 01294 I->second.first = 0; 01295 } 01296 01297 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator 01298 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) 01299 if (!isa<BasicBlock>(I->second.first)) { 01300 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first 01301 ->getType())); 01302 delete I->second.first; 01303 I->second.first = 0; 01304 } 01305 } 01306 01307 bool LLParser::PerFunctionState::VerifyFunctionComplete() { 01308 if (!ForwardRefVals.empty()) 01309 return P.Error(ForwardRefVals.begin()->second.second, 01310 "use of undefined value '%" + ForwardRefVals.begin()->first + 01311 "'"); 01312 if (!ForwardRefValIDs.empty()) 01313 return P.Error(ForwardRefValIDs.begin()->second.second, 01314 "use of undefined value '%" + 01315 utostr(ForwardRefValIDs.begin()->first) + "'"); 01316 return false; 01317 } 01318 01319 01320 /// GetVal - Get a value with the specified name or ID, creating a 01321 /// forward reference record if needed. This can return null if the value 01322 /// exists but does not have the right type. 01323 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, 01324 const Type *Ty, LocTy Loc) { 01325 // Look this name up in the normal function symbol table. 01326 Value *Val = F.getValueSymbolTable().lookup(Name); 01327 01328 // If this is a forward reference for the value, see if we already created a 01329 // forward ref record. 01330 if (Val == 0) { 01331 std::map<std::string, std::pair<Value*, LocTy> >::iterator 01332 I = ForwardRefVals.find(Name); 01333 if (I != ForwardRefVals.end()) 01334 Val = I->second.first; 01335 } 01336 01337 // If we have the value in the symbol table or fwd-ref table, return it. 01338 if (Val) { 01339 if (Val->getType() == Ty) return Val; 01340 if (Ty == Type::LabelTy) 01341 P.Error(Loc, "'%" + Name + "' is not a basic block"); 01342 else 01343 P.Error(Loc, "'%" + Name + "' defined with type '" + 01344 Val->getType()->getDescription() + "'"); 01345 return 0; 01346 } 01347 01348 // Don't make placeholders with invalid type. 01349 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { 01350 P.Error(Loc, "invalid use of a non-first-class type"); 01351 return 0; 01352 } 01353 01354 // Otherwise, create a new forward reference for this value and remember it. 01355 Value *FwdVal; 01356 if (Ty == Type::LabelTy) 01357 FwdVal = BasicBlock::Create(Name, &F); 01358 else 01359 FwdVal = new Argument(Ty, Name); 01360 01361 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 01362 return FwdVal; 01363 } 01364 01365 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, 01366 LocTy Loc) { 01367 // Look this name up in the normal function symbol table. 01368 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; 01369 01370 // If this is a forward reference for the value, see if we already created a 01371 // forward ref record. 01372 if (Val == 0) { 01373 std::map<unsigned, std::pair<Value*, LocTy> >::iterator 01374 I = ForwardRefValIDs.find(ID); 01375 if (I != ForwardRefValIDs.end()) 01376 Val = I->second.first; 01377 } 01378 01379 // If we have the value in the symbol table or fwd-ref table, return it. 01380 if (Val) { 01381 if (Val->getType() == Ty) return Val; 01382 if (Ty == Type::LabelTy) 01383 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block"); 01384 else 01385 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" + 01386 Val->getType()->getDescription() + "'"); 01387 return 0; 01388 } 01389 01390 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) { 01391 P.Error(Loc, "invalid use of a non-first-class type"); 01392 return 0; 01393 } 01394 01395 // Otherwise, create a new forward reference for this value and remember it. 01396 Value *FwdVal; 01397 if (Ty == Type::LabelTy) 01398 FwdVal = BasicBlock::Create("", &F); 01399 else 01400 FwdVal = new Argument(Ty); 01401 01402 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 01403 return FwdVal; 01404 } 01405 01406 /// SetInstName - After an instruction is parsed and inserted into its 01407 /// basic block, this installs its name. 01408 bool LLParser::PerFunctionState::SetInstName(int NameID, 01409 const std::string &NameStr, 01410 LocTy NameLoc, Instruction *Inst) { 01411 // If this instruction has void type, it cannot have a name or ID specified. 01412 if (Inst->getType() == Type::VoidTy) { 01413 if (NameID != -1 || !NameStr.empty()) 01414 return P.Error(NameLoc, "instructions returning void cannot have a name"); 01415 return false; 01416 } 01417 01418 // If this was a numbered instruction, verify that the instruction is the 01419 // expected value and resolve any forward references. 01420 if (NameStr.empty()) { 01421 // If neither a name nor an ID was specified, just use the next ID. 01422 if (NameID == -1) 01423 NameID = NumberedVals.size(); 01424 01425 if (unsigned(NameID) != NumberedVals.size()) 01426 return P.Error(NameLoc, "instruction expected to be numbered '%" + 01427 utostr(NumberedVals.size()) + "'"); 01428 01429 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI = 01430 ForwardRefValIDs.find(NameID); 01431 if (FI != ForwardRefValIDs.end()) { 01432 if (FI->second.first->getType() != Inst->getType()) 01433 return P.Error(NameLoc, "instruction forward referenced with type '" + 01434 FI->second.first->getType()->getDescription() + "'"); 01435 FI->second.first->replaceAllUsesWith(Inst); 01436 ForwardRefValIDs.erase(FI); 01437 } 01438 01439 NumberedVals.push_back(Inst); 01440 return false; 01441 } 01442 01443 // Otherwise, the instruction had a name. Resolve forward refs and set it. 01444 std::map<std::string, std::pair<Value*, LocTy> >::iterator 01445 FI = ForwardRefVals.find(NameStr); 01446 if (FI != ForwardRefVals.end()) { 01447 if (FI->second.first->getType() != Inst->getType()) 01448 return P.Error(NameLoc, "instruction forward referenced with type '" + 01449 FI->second.first->getType()->getDescription() + "'"); 01450 FI->second.first->replaceAllUsesWith(Inst); 01451 ForwardRefVals.erase(FI); 01452 } 01453 01454 // Set the name on the instruction. 01455 Inst->setName(NameStr); 01456 01457 if (Inst->getNameStr() != NameStr) 01458 return P.Error(NameLoc, "multiple definition of local value named '" + 01459 NameStr + "'"); 01460 return false; 01461 } 01462 01463 /// GetBB - Get a basic block with the specified name or ID, creating a 01464 /// forward reference record if needed. 01465 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 01466 LocTy Loc) { 01467 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc)); 01468 } 01469 01470 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 01471 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc)); 01472 } 01473 01474 /// DefineBB - Define the specified basic block, which is either named or 01475 /// unnamed. If there is an error, this returns null otherwise it returns 01476 /// the block being defined. 01477 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 01478 LocTy Loc) { 01479 BasicBlock *BB; 01480 if (Name.empty()) 01481 BB = GetBB(NumberedVals.size(), Loc); 01482 else 01483 BB = GetBB(Name, Loc); 01484 if (BB == 0) return 0; // Already diagnosed error. 01485 01486 // Move the block to the end of the function. Forward ref'd blocks are 01487 // inserted wherever they happen to be referenced. 01488 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 01489 01490 // Remove the block from forward ref sets. 01491 if (Name.empty()) { 01492 ForwardRefValIDs.erase(NumberedVals.size()); 01493 NumberedVals.push_back(BB); 01494 } else { 01495 // BB forward references are already in the function symbol table. 01496 ForwardRefVals.erase(Name); 01497 } 01498 01499 return BB; 01500 } 01501 01502 //===----------------------------------------------------------------------===// 01503 // Constants. 01504 //===----------------------------------------------------------------------===// 01505 01506 /// ParseValID - Parse an abstract value that doesn't necessarily have a 01507 /// type implied. For example, if we parse "4" we don't know what integer type 01508 /// it has. The value will later be combined with its type and checked for 01509 /// sanity. 01510 bool LLParser::ParseValID(ValID &ID) { 01511 ID.Loc = Lex.getLoc(); 01512 switch (Lex.getKind()) { 01513 default: return TokError("expected value token"); 01514 case lltok::GlobalID: // @42 01515 ID.UIntVal = Lex.getUIntVal(); 01516 ID.Kind = ValID::t_GlobalID; 01517 break; 01518 case lltok::GlobalVar: // @foo 01519 ID.StrVal = Lex.getStrVal(); 01520 ID.Kind = ValID::t_GlobalName; 01521 break; 01522 case lltok::LocalVarID: // %42 01523 ID.UIntVal = Lex.getUIntVal(); 01524 ID.Kind = ValID::t_LocalID; 01525 break; 01526 case lltok::LocalVar: // %foo 01527 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0 01528 ID.StrVal = Lex.getStrVal(); 01529 ID.Kind = ValID::t_LocalName; 01530 break; 01531 case lltok::APSInt: 01532 ID.APSIntVal = Lex.getAPSIntVal(); 01533 ID.Kind = ValID::t_APSInt; 01534 break; 01535 case lltok::APFloat: 01536 ID.APFloatVal = Lex.getAPFloatVal(); 01537 ID.Kind = ValID::t_APFloat; 01538 break; 01539 case lltok::kw_true: 01540 ID.ConstantVal = ConstantInt::getTrue(); 01541 ID.Kind = ValID::t_Constant; 01542 break; 01543 case lltok::kw_false: 01544 ID.ConstantVal = ConstantInt::getFalse(); 01545 ID.Kind = ValID::t_Constant; 01546 break; 01547 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 01548 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 01549 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 01550 01551 case lltok::lbrace: { 01552 // ValID ::= '{' ConstVector '}' 01553 Lex.Lex(); 01554 SmallVector<Constant*, 16> Elts; 01555 if (ParseGlobalValueVector(Elts) || 01556 ParseToken(lltok::rbrace, "expected end of struct constant")) 01557 return true; 01558 01559 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false); 01560 ID.Kind = ValID::t_Constant; 01561 return false; 01562 } 01563 case lltok::less: { 01564 // ValID ::= '<' ConstVector '>' --> Vector. 01565 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 01566 Lex.Lex(); 01567 bool isPackedStruct = EatIfPresent(lltok::lbrace); 01568 01569 SmallVector<Constant*, 16> Elts; 01570 LocTy FirstEltLoc = Lex.getLoc(); 01571 if (ParseGlobalValueVector(Elts) || 01572 (isPackedStruct && 01573 ParseToken(lltok::rbrace, "expected end of packed struct")) || 01574 ParseToken(lltok::greater, "expected end of constant")) 01575 return true; 01576 01577 if (isPackedStruct) { 01578 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true); 01579 ID.Kind = ValID::t_Constant; 01580 return false; 01581 } 01582 01583 if (Elts.empty()) 01584 return Error(ID.Loc, "constant vector must not be empty"); 01585 01586 if (!Elts[0]->getType()->isInteger() && 01587 !Elts[0]->getType()->isFloatingPoint()) 01588 return Error(FirstEltLoc, 01589 "vector elements must have integer or floating point type"); 01590 01591 // Verify that all the vector elements have the same type. 01592 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 01593 if (Elts[i]->getType() != Elts[0]->getType()) 01594 return Error(FirstEltLoc, 01595 "vector element #" + utostr(i) + 01596 " is not of type '" + Elts[0]->getType()->getDescription()); 01597 01598 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size()); 01599 ID.Kind = ValID::t_Constant; 01600 return false; 01601 } 01602 case lltok::lsquare: { // Array Constant 01603 Lex.Lex(); 01604 SmallVector<Constant*, 16> Elts; 01605 LocTy FirstEltLoc = Lex.getLoc(); 01606 if (ParseGlobalValueVector(Elts) || 01607 ParseToken(lltok::rsquare, "expected end of array constant")) 01608 return true; 01609 01610 // Handle empty element. 01611 if (Elts.empty()) { 01612 // Use undef instead of an array because it's inconvenient to determine 01613 // the element type at this point, there being no elements to examine. 01614 ID.Kind = ValID::t_EmptyArray; 01615 return false; 01616 } 01617 01618 if (!Elts[0]->getType()->isFirstClassType()) 01619 return Error(FirstEltLoc, "invalid array element type: " + 01620 Elts[0]->getType()->getDescription()); 01621 01622 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 01623 01624 // Verify all elements are correct type! 01625 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 01626 if (Elts[i]->getType() != Elts[0]->getType()) 01627 return Error(FirstEltLoc, 01628 "array element #" + utostr(i) + 01629 " is not of type '" +Elts[0]->getType()->getDescription()); 01630 } 01631 01632 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size()); 01633 ID.Kind = ValID::t_Constant; 01634 return false; 01635 } 01636 case lltok::kw_c: // c "foo" 01637 Lex.Lex(); 01638 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false); 01639 if (ParseToken(lltok::StringConstant, "expected string")) return true; 01640 ID.Kind = ValID::t_Constant; 01641 return false; 01642 01643 case lltok::kw_asm: { 01644 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT 01645 bool HasSideEffect; 01646 Lex.Lex(); 01647 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 01648 ParseStringConstant(ID.StrVal) || 01649 ParseToken(lltok::comma, "expected comma in inline asm expression") || 01650 ParseToken(lltok::StringConstant, "expected constraint string")) 01651 return true; 01652 ID.StrVal2 = Lex.getStrVal(); 01653 ID.UIntVal = HasSideEffect; 01654 ID.Kind = ValID::t_InlineAsm; 01655 return false; 01656 } 01657 01658 case lltok::kw_trunc: 01659 case lltok::kw_zext: 01660 case lltok::kw_sext: 01661 case lltok::kw_fptrunc: 01662 case lltok::kw_fpext: 01663 case lltok::kw_bitcast: 01664 case lltok::kw_uitofp: 01665 case lltok::kw_sitofp: 01666 case lltok::kw_fptoui: 01667 case lltok::kw_fptosi: 01668 case lltok::kw_inttoptr: 01669 case lltok::kw_ptrtoint: { 01670 unsigned Opc = Lex.getUIntVal(); 01671 PATypeHolder DestTy(Type::VoidTy); 01672 Constant *SrcVal; 01673 Lex.Lex(); 01674 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 01675 ParseGlobalTypeAndValue(SrcVal) || 01676 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") || 01677 ParseType(DestTy) || 01678 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 01679 return true; 01680 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 01681 return Error(ID.Loc, "invalid cast opcode for cast from '" + 01682 SrcVal->getType()->getDescription() + "' to '" + 01683 DestTy->getDescription() + "'"); 01684 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal, 01685 DestTy); 01686 ID.Kind = ValID::t_Constant; 01687 return false; 01688 } 01689 case lltok::kw_extractvalue: { 01690 Lex.Lex(); 01691 Constant *Val; 01692 SmallVector<unsigned, 4> Indices; 01693 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 01694 ParseGlobalTypeAndValue(Val) || 01695 ParseIndexList(Indices) || 01696 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 01697 return true; 01698 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 01699 return Error(ID.Loc, "extractvalue operand must be array or struct"); 01700 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(), 01701 Indices.end())) 01702 return Error(ID.Loc, "invalid indices for extractvalue"); 01703 ID.ConstantVal = ConstantExpr::getExtractValue(Val, 01704 &Indices[0], Indices.size()); 01705 ID.Kind = ValID::t_Constant; 01706 return false; 01707 } 01708 case lltok::kw_insertvalue: { 01709 Lex.Lex(); 01710 Constant *Val0, *Val1; 01711 SmallVector<unsigned, 4> Indices; 01712 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 01713 ParseGlobalTypeAndValue(Val0) || 01714 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 01715 ParseGlobalTypeAndValue(Val1) || 01716 ParseIndexList(Indices) || 01717 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 01718 return true; 01719 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType())) 01720 return Error(ID.Loc, "extractvalue operand must be array or struct"); 01721 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), 01722 Indices.end())) 01723 return Error(ID.Loc, "invalid indices for insertvalue"); 01724 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, 01725 &Indices[0], Indices.size()); 01726 ID.Kind = ValID::t_Constant; 01727 return false; 01728 } 01729 case lltok::kw_icmp: 01730 case lltok::kw_fcmp: 01731 case lltok::kw_vicmp: 01732 case lltok::kw_vfcmp: { 01733 unsigned PredVal, Opc = Lex.getUIntVal(); 01734 Constant *Val0, *Val1; 01735 Lex.Lex(); 01736 if (ParseCmpPredicate(PredVal, Opc) || 01737 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 01738 ParseGlobalTypeAndValue(Val0) || 01739 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 01740 ParseGlobalTypeAndValue(Val1) || 01741 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 01742 return true; 01743 01744 if (Val0->getType() != Val1->getType()) 01745 return Error(ID.Loc, "compare operands must have the same type"); 01746 01747 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 01748 01749 if (Opc == Instruction::FCmp) { 01750 if (!Val0->getType()->isFPOrFPVector()) 01751 return Error(ID.Loc, "fcmp requires floating point operands"); 01752 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 01753 } else if (Opc == Instruction::ICmp) { 01754 if (!Val0->getType()->isIntOrIntVector() && 01755 !isa<PointerType>(Val0->getType())) 01756 return Error(ID.Loc, "icmp requires pointer or integer operands"); 01757 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 01758 } else if (Opc == Instruction::VFCmp) { 01759 // FIXME: REMOVE VFCMP Support 01760 if (!Val0->getType()->isFPOrFPVector() || 01761 !isa<VectorType>(Val0->getType())) 01762 return Error(ID.Loc, "vfcmp requires vector floating point operands"); 01763 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1); 01764 } else if (Opc == Instruction::VICmp) { 01765 // FIXME: REMOVE VICMP Support 01766 if (!Val0->getType()->isIntOrIntVector() || 01767 !isa<VectorType>(Val0->getType())) 01768 return Error(ID.Loc, "vicmp requires vector floating point operands"); 01769 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1); 01770 } 01771 ID.Kind = ValID::t_Constant; 01772 return false; 01773 } 01774 01775 // Binary Operators. 01776 case lltok::kw_add: 01777 case lltok::kw_sub: 01778 case lltok::kw_mul: 01779 case lltok::kw_udiv: 01780 case lltok::kw_sdiv: 01781 case lltok::kw_fdiv: 01782 case lltok::kw_urem: 01783 case lltok::kw_srem: 01784 case lltok::kw_frem: { 01785 unsigned Opc = Lex.getUIntVal(); 01786 Constant *Val0, *Val1; 01787 Lex.Lex(); 01788 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 01789 ParseGlobalTypeAndValue(Val0) || 01790 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 01791 ParseGlobalTypeAndValue(Val1) || 01792 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 01793 return true; 01794 if (Val0->getType() != Val1->getType()) 01795 return Error(ID.Loc, "operands of constexpr must have same type"); 01796 if (!Val0->getType()->isIntOrIntVector() && 01797 !Val0->getType()->isFPOrFPVector()) 01798 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands"); 01799 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 01800 ID.Kind = ValID::t_Constant; 01801 return false; 01802 } 01803 01804 // Logical Operations 01805 case lltok::kw_shl: 01806 case lltok::kw_lshr: 01807 case lltok::kw_ashr: 01808 case lltok::kw_and: 01809 case lltok::kw_or: 01810 case lltok::kw_xor: { 01811 unsigned Opc = Lex.getUIntVal(); 01812 Constant *Val0, *Val1; 01813 Lex.Lex(); 01814 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 01815 ParseGlobalTypeAndValue(Val0) || 01816 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 01817 ParseGlobalTypeAndValue(Val1) || 01818 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 01819 return true; 01820 if (Val0->getType() != Val1->getType()) 01821 return Error(ID.Loc, "operands of constexpr must have same type"); 01822 if (!Val0->getType()->isIntOrIntVector()) 01823 return Error(ID.Loc, 01824 "constexpr requires integer or integer vector operands"); 01825 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 01826 ID.Kind = ValID::t_Constant; 01827 return false; 01828 } 01829 01830 case lltok::kw_getelementptr: 01831 case lltok::kw_shufflevector: 01832 case lltok::kw_insertelement: 01833 case lltok::kw_extractelement: 01834 case lltok::kw_select: { 01835 unsigned Opc = Lex.getUIntVal(); 01836 SmallVector<Constant*, 16> Elts; 01837 Lex.Lex(); 01838 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") || 01839 ParseGlobalValueVector(Elts) || 01840 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 01841 return true; 01842 01843 if (Opc == Instruction::GetElementPtr) { 01844 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType())) 01845 return Error(ID.Loc, "getelementptr requires pointer operand"); 01846 01847 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), 01848 (Value**)&Elts[1], Elts.size()-1)) 01849 return Error(ID.Loc, "invalid indices for getelementptr"); 01850 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], 01851 &Elts[1], Elts.size()-1); 01852 } else if (Opc == Instruction::Select) { 01853 if (Elts.size() != 3) 01854 return Error(ID.Loc, "expected three operands to select"); 01855 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 01856 Elts[2])) 01857 return Error(ID.Loc, Reason); 01858 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 01859 } else if (Opc == Instruction::ShuffleVector) { 01860 if (Elts.size() != 3) 01861 return Error(ID.Loc, "expected three operands to shufflevector"); 01862 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 01863 return Error(ID.Loc, "invalid operands to shufflevector"); 01864 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 01865 } else if (Opc == Instruction::ExtractElement) { 01866 if (Elts.size() != 2) 01867 return Error(ID.Loc, "expected two operands to extractelement"); 01868 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 01869 return Error(ID.Loc, "invalid extractelement operands"); 01870 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 01871 } else { 01872 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 01873 if (Elts.size() != 3) 01874 return Error(ID.Loc, "expected three operands to insertelement"); 01875 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 01876 return Error(ID.Loc, "invalid insertelement operands"); 01877 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 01878 } 01879 01880 ID.Kind = ValID::t_Constant; 01881 return false; 01882 } 01883 } 01884 01885 Lex.Lex(); 01886 return false; 01887 } 01888 01889 /// ParseGlobalValue - Parse a global value with the specified type. 01890 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) { 01891 V = 0; 01892 ValID ID; 01893 return ParseValID(ID) || 01894 ConvertGlobalValIDToValue(Ty, ID, V); 01895 } 01896 01897 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved 01898 /// constant. 01899 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, 01900 Constant *&V) { 01901 if (isa<FunctionType>(Ty)) 01902 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 01903 01904 switch (ID.Kind) { 01905 default: assert(0 && "Unknown ValID!"); 01906 case ValID::t_LocalID: 01907 case ValID::t_LocalName: 01908 return Error(ID.Loc, "invalid use of function-local name"); 01909 case ValID::t_InlineAsm: 01910 return Error(ID.Loc, "inline asm can only be an operand of call/invoke"); 01911 case ValID::t_GlobalName: 01912 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 01913 return V == 0; 01914 case ValID::t_GlobalID: 01915 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 01916 return V == 0; 01917 case ValID::t_APSInt: 01918 if (!isa<IntegerType>(Ty)) 01919 return Error(ID.Loc, "integer constant must have integer type"); 01920 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 01921 V = ConstantInt::get(ID.APSIntVal); 01922 return false; 01923 case ValID::t_APFloat: 01924 if (!Ty->isFloatingPoint() || 01925 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 01926 return Error(ID.Loc, "floating point constant invalid for type"); 01927 01928 // The lexer has no type info, so builds all float and double FP constants 01929 // as double. Fix this here. Long double does not need this. 01930 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble && 01931 Ty == Type::FloatTy) { 01932 bool Ignored; 01933 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, 01934 &Ignored); 01935 } 01936 V = ConstantFP::get(ID.APFloatVal); 01937 01938 if (V->getType() != Ty) 01939 return Error(ID.Loc, "floating point constant does not have type '" + 01940 Ty->getDescription() + "'"); 01941 01942 return false; 01943 case ValID::t_Null: 01944 if (!isa<PointerType>(Ty)) 01945 return Error(ID.Loc, "null must be a pointer type"); 01946 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 01947 return false; 01948 case ValID::t_Undef: 01949 // FIXME: LabelTy should not be a first-class type. 01950 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) && 01951 !isa<OpaqueType>(Ty)) 01952 return Error(ID.Loc, "invalid type for undef constant"); 01953 V = UndefValue::get(Ty); 01954 return false; 01955 case ValID::t_EmptyArray: 01956 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0) 01957 return Error(ID.Loc, "invalid empty array initializer"); 01958 V = UndefValue::get(Ty); 01959 return false; 01960 case ValID::t_Zero: 01961 // FIXME: LabelTy should not be a first-class type. 01962 if (!Ty->isFirstClassType() || Ty == Type::LabelTy) 01963 return Error(ID.Loc, "invalid type for null constant"); 01964 V = Constant::getNullValue(Ty); 01965 return false; 01966 case ValID::t_Constant: 01967 if (ID.ConstantVal->getType() != Ty) 01968 return Error(ID.Loc, "constant expression type mismatch"); 01969 V = ID.ConstantVal; 01970 return false; 01971 } 01972 } 01973 01974 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 01975 PATypeHolder Type(Type::VoidTy); 01976 return ParseType(Type) || 01977 ParseGlobalValue(Type, V); 01978 } 01979 01980 /// ParseGlobalValueVector 01981 /// ::= /*empty*/ 01982 /// ::= TypeAndValue (',' TypeAndValue)* 01983 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) { 01984 // Empty list. 01985 if (Lex.getKind() == lltok::rbrace || 01986 Lex.getKind() == lltok::rsquare || 01987 Lex.getKind() == lltok::greater || 01988 Lex.getKind() == lltok::rparen) 01989 return false; 01990 01991 Constant *C; 01992 if (ParseGlobalTypeAndValue(C)) return true; 01993 Elts.push_back(C); 01994 01995 while (EatIfPresent(lltok::comma)) { 01996 if (ParseGlobalTypeAndValue(C)) return true; 01997 Elts.push_back(C); 01998 } 01999 02000 return false; 02001 } 02002 02003 02004 //===----------------------------------------------------------------------===// 02005 // Function Parsing. 02006 //===----------------------------------------------------------------------===// 02007 02008 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V, 02009 PerFunctionState &PFS) { 02010 if (ID.Kind == ValID::t_LocalID) 02011 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); 02012 else if (ID.Kind == ValID::t_LocalName) 02013 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); 02014 else if (ID.Kind == ValID::t_InlineAsm) { 02015 const PointerType *PTy = dyn_cast<PointerType>(Ty); 02016 const FunctionType *FTy = 02017 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0; 02018 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) 02019 return Error(ID.Loc, "invalid type for inline asm constraint string"); 02020 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal); 02021 return false; 02022 } else { 02023 Constant *C; 02024 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; 02025 V = C; 02026 return false; 02027 } 02028 02029 return V == 0; 02030 } 02031 02032 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) { 02033 V = 0; 02034 ValID ID; 02035 return ParseValID(ID) || 02036 ConvertValIDToValue(Ty, ID, V, PFS); 02037 } 02038 02039 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) { 02040 PATypeHolder T(Type::VoidTy); 02041 return ParseType(T) || 02042 ParseValue(T, V, PFS); 02043 } 02044 02045 /// FunctionHeader 02046 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 02047 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 02048 /// OptionalAlign OptGC 02049 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 02050 // Parse the linkage. 02051 LocTy LinkageLoc = Lex.getLoc(); 02052 unsigned Linkage; 02053 02054 unsigned Visibility, CC, RetAttrs; 02055 PATypeHolder RetType(Type::VoidTy); 02056 LocTy RetTypeLoc = Lex.getLoc(); 02057 if (ParseOptionalLinkage(Linkage) || 02058 ParseOptionalVisibility(Visibility) || 02059 ParseOptionalCallingConv(CC) || 02060 ParseOptionalAttrs(RetAttrs, 1) || 02061 ParseType(RetType, RetTypeLoc)) 02062 return true; 02063 02064 // Verify that the linkage is ok. 02065 switch ((GlobalValue::LinkageTypes)Linkage) { 02066 case GlobalValue::ExternalLinkage: 02067 break; // always ok. 02068 case GlobalValue::DLLImportLinkage: 02069 case GlobalValue::ExternalWeakLinkage: 02070 if (isDefine) 02071 return Error(LinkageLoc, "invalid linkage for function definition"); 02072 break; 02073 case GlobalValue::PrivateLinkage: 02074 case GlobalValue::InternalLinkage: 02075 case GlobalValue::LinkOnceLinkage: 02076 case GlobalValue::WeakLinkage: 02077 case GlobalValue::DLLExportLinkage: 02078 if (!isDefine) 02079 return Error(LinkageLoc, "invalid linkage for function declaration"); 02080 break; 02081 case GlobalValue::AppendingLinkage: 02082 case GlobalValue::GhostLinkage: 02083 case GlobalValue::CommonLinkage: 02084 return Error(LinkageLoc, "invalid function linkage type"); 02085 } 02086 02087 if (!FunctionType::isValidReturnType(RetType) || 02088 isa<OpaqueType>(RetType)) 02089 return Error(RetTypeLoc, "invalid function return type"); 02090 02091 if (Lex.getKind() != lltok::GlobalVar) 02092 return TokError("expected function name"); 02093 02094 LocTy NameLoc = Lex.getLoc(); 02095 std::string FunctionName = Lex.getStrVal(); 02096 Lex.Lex(); 02097 02098 if (Lex.getKind() != lltok::lparen) 02099 return TokError("expected '(' in function argument list"); 02100 02101 std::vector<ArgInfo> ArgList; 02102 bool isVarArg; 02103 unsigned FuncAttrs; 02104 std::string Section; 02105 unsigned Alignment; 02106 std::string GC; 02107 02108 if (ParseArgumentList(ArgList, isVarArg, false) || 02109 ParseOptionalAttrs(FuncAttrs, 2) || 02110 (EatIfPresent(lltok::kw_section) && 02111 ParseStringConstant(Section)) || 02112 ParseOptionalAlignment(Alignment) || 02113 (EatIfPresent(lltok::kw_gc) && 02114 ParseStringConstant(GC))) 02115 return true; 02116 02117 // If the alignment was parsed as an attribute, move to the alignment field. 02118 if (FuncAttrs & Attribute::Alignment) { 02119 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs); 02120 FuncAttrs &= ~Attribute::Alignment; 02121 } 02122 02123 // Okay, if we got here, the function is syntactically valid. Convert types 02124 // and do semantic checks. 02125 std::vector<const Type*> ParamTypeList; 02126 SmallVector<AttributeWithIndex, 8> Attrs; 02127 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function 02128 // attributes. 02129 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 02130 if (FuncAttrs & ObsoleteFuncAttrs) { 02131 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs; 02132 FuncAttrs &= ~ObsoleteFuncAttrs; 02133 } 02134 02135 if (RetAttrs != Attribute::None) 02136 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 02137 02138 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 02139 ParamTypeList.push_back(ArgList[i].Type); 02140 if (ArgList[i].Attrs != Attribute::None) 02141 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 02142 } 02143 02144 if (FuncAttrs != Attribute::None) 02145 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs)); 02146 02147 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 02148 02149 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg); 02150 const PointerType *PFT = PointerType::getUnqual(FT); 02151 02152 Fn = 0; 02153 if (!FunctionName.empty()) { 02154 // If this was a definition of a forward reference, remove the definition 02155 // from the forward reference table and fill in the forward ref. 02156 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI = 02157 ForwardRefVals.find(FunctionName); 02158 if (FRVI != ForwardRefVals.end()) { 02159 Fn = M->getFunction(FunctionName); 02160 ForwardRefVals.erase(FRVI); 02161 } else if ((Fn = M->getFunction(FunctionName))) { 02162 // If this function already exists in the symbol table, then it is 02163 // multiply defined. We accept a few cases for old backwards compat. 02164 // FIXME: Remove this stuff for LLVM 3.0. 02165 if (Fn->getType() != PFT || Fn->getAttributes() != PAL || 02166 (!Fn->isDeclaration() && isDefine)) { 02167 // If the redefinition has different type or different attributes, 02168 // reject it. If both have bodies, reject it. 02169 return Error(NameLoc, "invalid redefinition of function '" + 02170 FunctionName + "'"); 02171 } else if (Fn->isDeclaration()) { 02172 // Make sure to strip off any argument names so we can't get conflicts. 02173 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end(); 02174 AI != AE; ++AI) 02175 AI->setName(""); 02176 } 02177 } 02178 02179 } else if (FunctionName.empty()) { 02180 // If this is a definition of a forward referenced function, make sure the 02181 // types agree. 02182 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I 02183 = ForwardRefValIDs.find(NumberedVals.size()); 02184 if (I != ForwardRefValIDs.end()) { 02185 Fn = cast<Function>(I->second.first); 02186 if (Fn->getType() != PFT) 02187 return Error(NameLoc, "type of definition and forward reference of '@" + 02188 utostr(NumberedVals.size()) +"' disagree"); 02189 ForwardRefValIDs.erase(I); 02190 } 02191 } 02192 02193 if (Fn == 0) 02194 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M); 02195 else // Move the forward-reference to the correct spot in the module. 02196 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 02197 02198 if (FunctionName.empty()) 02199 NumberedVals.push_back(Fn); 02200 02201 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 02202 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 02203 Fn->setCallingConv(CC); 02204 Fn->setAttributes(PAL); 02205 Fn->setAlignment(Alignment); 02206 Fn->setSection(Section); 02207 if (!GC.empty()) Fn->setGC(GC.c_str()); 02208 02209 // Add all of the arguments we parsed to the function. 02210 Function::arg_iterator ArgIt = Fn->arg_begin(); 02211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 02212 // If the argument has a name, insert it into the argument symbol table. 02213 if (ArgList[i].Name.empty()) continue; 02214 02215 // Set the name, if it conflicted, it will be auto-renamed. 02216 ArgIt->setName(ArgList[i].Name); 02217 02218 if (ArgIt->getNameStr() != ArgList[i].Name) 02219 return Error(ArgList[i].Loc, "redefinition of argument '%" + 02220 ArgList[i].Name + "'"); 02221 } 02222 02223 return false; 02224 } 02225 02226 02227 /// ParseFunctionBody 02228 /// ::= '{' BasicBlock+ '}' 02229 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0 02230 /// 02231 bool LLParser::ParseFunctionBody(Function &Fn) { 02232 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin) 02233 return TokError("expected '{' in function body"); 02234 Lex.Lex(); // eat the {. 02235 02236 PerFunctionState PFS(*this, Fn); 02237 02238 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end) 02239 if (ParseBasicBlock(PFS)) return true; 02240 02241 // Eat the }. 02242 Lex.Lex(); 02243 02244 // Verify function is ok. 02245 return PFS.VerifyFunctionComplete(); 02246 } 02247 02248 /// ParseBasicBlock 02249 /// ::= LabelStr? Instruction* 02250 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 02251 // If this basic block starts out with a name, remember it. 02252 std::string Name; 02253 LocTy NameLoc = Lex.getLoc(); 02254 if (Lex.getKind() == lltok::LabelStr) { 02255 Name = Lex.getStrVal(); 02256 Lex.Lex(); 02257 } 02258 02259 BasicBlock *BB = PFS.DefineBB(Name, NameLoc); 02260 if (BB == 0) return true; 02261 02262 std::string NameStr; 02263 02264 // Parse the instructions in this block until we get a terminator. 02265 Instruction *Inst; 02266 do { 02267 // This instruction may have three possibilities for a name: a) none 02268 // specified, b) name specified "%foo =", c) number specified: "%4 =". 02269 LocTy NameLoc = Lex.getLoc(); 02270 int NameID = -1; 02271 NameStr = ""; 02272 02273 if (Lex.getKind() == lltok::LocalVarID) { 02274 NameID = Lex.getUIntVal(); 02275 Lex.Lex(); 02276 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 02277 return true; 02278 } else if (Lex.getKind() == lltok::LocalVar || 02279 // FIXME: REMOVE IN LLVM 3.0 02280 Lex.getKind() == lltok::StringConstant) { 02281 NameStr = Lex.getStrVal(); 02282 Lex.Lex(); 02283 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 02284 return true; 02285 } 02286 02287 if (ParseInstruction(Inst, BB, PFS)) return true; 02288 02289 BB->getInstList().push_back(Inst); 02290 02291 // Set the name on the instruction. 02292 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 02293 } while (!isa<TerminatorInst>(Inst)); 02294 02295 return false; 02296 } 02297 02298 //===----------------------------------------------------------------------===// 02299 // Instruction Parsing. 02300 //===----------------------------------------------------------------------===// 02301 02302 /// ParseInstruction - Parse one of the many different instructions. 02303 /// 02304 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 02305 PerFunctionState &PFS) { 02306 lltok::Kind Token = Lex.getKind(); 02307 if (Token == lltok::Eof) 02308 return TokError("found end of file when expecting more instructions"); 02309 LocTy Loc = Lex.getLoc(); 02310 Lex.Lex(); // Eat the keyword. 02311 02312 switch (Token) { 02313 default: return Error(Loc, "expected instruction opcode"); 02314 // Terminator Instructions. 02315 case lltok::kw_unwind: Inst = new UnwindInst(); return false; 02316 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false; 02317 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 02318 case lltok::kw_br: return ParseBr(Inst, PFS); 02319 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 02320 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 02321 // Binary Operators. 02322 case lltok::kw_add: 02323 case lltok::kw_sub: 02324 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0); 02325 02326 case lltok::kw_udiv: 02327 case lltok::kw_sdiv: 02328 case lltok::kw_urem: 02329 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1); 02330 case lltok::kw_fdiv: 02331 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2); 02332 case lltok::kw_shl: 02333 case lltok::kw_lshr: 02334 case lltok::kw_ashr: 02335 case lltok::kw_and: 02336 case lltok::kw_or: 02337 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal()); 02338 case lltok::kw_icmp: 02339 case lltok::kw_fcmp: 02340 case lltok::kw_vicmp: 02341 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal()); 02342 // Casts. 02343 case lltok::kw_trunc: 02344 case lltok::kw_zext: 02345 case lltok::kw_sext: 02346 case lltok::kw_fptrunc: 02347 case lltok::kw_fpext: 02348 case lltok::kw_bitcast: 02349 case lltok::kw_uitofp: 02350 case lltok::kw_sitofp: 02351 case lltok::kw_fptoui: 02352 case lltok::kw_fptosi: 02353 case lltok::kw_inttoptr: 02354 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal()); 02355 // Other. 02356 case lltok::kw_select: return ParseSelect(Inst, PFS); 02357 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 02358 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 02359 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 02360 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 02361 case lltok::kw_phi: return ParsePHI(Inst, PFS); 02362 case lltok::kw_call: return ParseCall(Inst, PFS, false); 02363 case lltok::kw_tail: return ParseCall(Inst, PFS, true); 02364 // Memory. 02365 case lltok::kw_alloca: 02366 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal()); 02367 case lltok::kw_free: return ParseFree(Inst, PFS); 02368 case lltok::kw_load: return ParseLoad(Inst, PFS, false); 02369 case lltok::kw_store: return ParseStore(Inst, PFS, false); 02370 case lltok::kw_volatile: 02371 if (EatIfPresent(lltok::kw_load)) 02372 return ParseLoad(Inst, PFS, true); 02373 else if (EatIfPresent(lltok::kw_store)) 02374 return ParseStore(Inst, PFS, true); 02375 else 02376 return TokError("expected 'load' or 'store'"); 02377 case lltok::kw_getresult: return ParseGetResult(Inst, PFS); 02378 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 02379 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 02380 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 02381 } 02382 } 02383 02384 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 02385 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 02386 // FIXME: REMOVE vicmp/vfcmp! 02387 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) { 02388 switch (Lex.getKind()) { 02389 default: TokError("expected fcmp predicate (e.g. 'oeq')"); 02390 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 02391 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 02392 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 02393 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 02394 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 02395 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 02396 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 02397 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 02398 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 02399 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 02400 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 02401 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 02402 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 02403 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 02404 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 02405 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 02406 } 02407 } else { 02408 switch (Lex.getKind()) { 02409 default: TokError("expected icmp predicate (e.g. 'eq')"); 02410 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 02411 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 02412 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 02413 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 02414 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 02415 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 02416 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 02417 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 02418 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 02419 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 02420 } 02421 } 02422 Lex.Lex(); 02423 return false; 02424 } 02425 02426 //===----------------------------------------------------------------------===// 02427 // Terminator Instructions. 02428 //===----------------------------------------------------------------------===// 02429 02430 /// ParseRet - Parse a return instruction. 02431 /// ::= 'ret' void 02432 /// ::= 'ret' TypeAndValue 02433 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]] 02434 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 02435 PerFunctionState &PFS) { 02436 PATypeHolder Ty(Type::VoidTy); 02437 if (ParseType(Ty)) return true; 02438 02439 if (Ty == Type::VoidTy) { 02440 Inst = ReturnInst::Create(); 02441 return false; 02442 } 02443 02444 Value *RV; 02445 if (ParseValue(Ty, RV, PFS)) return true; 02446 02447 // The normal case is one return value. 02448 if (Lex.getKind() == lltok::comma) { 02449 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use 02450 // of 'ret {i32,i32} {i32 1, i32 2}' 02451 SmallVector<Value*, 8> RVs; 02452 RVs.push_back(RV); 02453 02454 while (EatIfPresent(lltok::comma)) { 02455 if (ParseTypeAndValue(RV, PFS)) return true; 02456 RVs.push_back(RV); 02457 } 02458 02459 RV = UndefValue::get(PFS.getFunction().getReturnType()); 02460 for (unsigned i = 0, e = RVs.size(); i != e; ++i) { 02461 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); 02462 BB->getInstList().push_back(I); 02463 RV = I; 02464 } 02465 } 02466 Inst = ReturnInst::Create(RV); 02467 return false; 02468 } 02469 02470 02471 /// ParseBr 02472 /// ::= 'br' TypeAndValue 02473 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 02474 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 02475 LocTy Loc, Loc2; 02476 Value *Op0, *Op1, *Op2; 02477 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 02478 02479 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 02480 Inst = BranchInst::Create(BB); 02481 return false; 02482 } 02483 02484 if (Op0->getType() != Type::Int1Ty) 02485 return Error(Loc, "branch condition must have 'i1' type"); 02486 02487 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 02488 ParseTypeAndValue(Op1, Loc, PFS) || 02489 ParseToken(lltok::comma, "expected ',' after true destination") || 02490 ParseTypeAndValue(Op2, Loc2, PFS)) 02491 return true; 02492 02493 if (!isa<BasicBlock>(Op1)) 02494 return Error(Loc, "true destination of branch must be a basic block"); 02495 if (!isa<BasicBlock>(Op2)) 02496 return Error(Loc2, "true destination of branch must be a basic block"); 02497 02498 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0); 02499 return false; 02500 } 02501 02502 /// ParseSwitch 02503 /// Instruction 02504 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 02505 /// JumpTable 02506 /// ::= (TypeAndValue ',' TypeAndValue)* 02507 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 02508 LocTy CondLoc, BBLoc; 02509 Value *Cond, *DefaultBB; 02510 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 02511 ParseToken(lltok::comma, "expected ',' after switch condition") || 02512 ParseTypeAndValue(DefaultBB, BBLoc, PFS) || 02513 ParseToken(lltok::lsquare, "expected '[' with switch table")) 02514 return true; 02515 02516 if (!isa<IntegerType>(Cond->getType())) 02517 return Error(CondLoc, "switch condition must have integer type"); 02518 if (!isa<BasicBlock>(DefaultBB)) 02519 return Error(BBLoc, "default destination must be a basic block"); 02520 02521 // Parse the jump table pairs. 02522 SmallPtrSet<Value*, 32> SeenCases; 02523 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 02524 while (Lex.getKind() != lltok::rsquare) { 02525 Value *Constant, *DestBB; 02526 02527 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 02528 ParseToken(lltok::comma, "expected ',' after case value") || 02529 ParseTypeAndValue(DestBB, BBLoc, PFS)) 02530 return true; 02531 02532 if (!SeenCases.insert(Constant)) 02533 return Error(CondLoc, "duplicate case value in switch"); 02534 if (!isa<ConstantInt>(Constant)) 02535 return Error(CondLoc, "case value is not a constant integer"); 02536 if (!isa<BasicBlock>(DestBB)) 02537 return Error(BBLoc, "case destination is not a basic block"); 02538 02539 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), 02540 cast<BasicBlock>(DestBB))); 02541 } 02542 02543 Lex.Lex(); // Eat the ']'. 02544 02545 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB), 02546 Table.size()); 02547 for (unsigned i = 0, e = Table.size(); i != e; ++i) 02548 SI->addCase(Table[i].first, Table[i].second); 02549 Inst = SI; 02550 return false; 02551 } 02552 02553 /// ParseInvoke 02554 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 02555 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 02556 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 02557 LocTy CallLoc = Lex.getLoc(); 02558 unsigned CC, RetAttrs, FnAttrs; 02559 PATypeHolder RetType(Type::VoidTy); 02560 LocTy RetTypeLoc; 02561 ValID CalleeID; 02562 SmallVector<ParamInfo, 16> ArgList; 02563 02564 Value *NormalBB, *UnwindBB; 02565 if (ParseOptionalCallingConv(CC) || 02566 ParseOptionalAttrs(RetAttrs, 1) || 02567 ParseType(RetType, RetTypeLoc) || 02568 ParseValID(CalleeID) || 02569 ParseParameterList(ArgList, PFS) || 02570 ParseOptionalAttrs(FnAttrs, 2) || 02571 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 02572 ParseTypeAndValue(NormalBB, PFS) || 02573 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 02574 ParseTypeAndValue(UnwindBB, PFS)) 02575 return true; 02576 02577 if (!isa<BasicBlock>(NormalBB)) 02578 return Error(CallLoc, "normal destination is not a basic block"); 02579 if (!isa<BasicBlock>(UnwindBB)) 02580 return Error(CallLoc, "unwind destination is not a basic block"); 02581 02582 // If RetType is a non-function pointer type, then this is the short syntax 02583 // for the call, which means that RetType is just the return type. Infer the 02584 // rest of the function argument types from the arguments that are present. 02585 const PointerType *PFTy = 0; 02586 const FunctionType *Ty = 0; 02587 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 02588 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 02589 // Pull out the types of all of the arguments... 02590 std::vector<const Type*> ParamTypes; 02591 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 02592 ParamTypes.push_back(ArgList[i].V->getType()); 02593 02594 if (!FunctionType::isValidReturnType(RetType)) 02595 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 02596 02597 Ty = FunctionType::get(RetType, ParamTypes, false); 02598 PFTy = PointerType::getUnqual(Ty); 02599 } 02600 02601 // Look up the callee. 02602 Value *Callee; 02603 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; 02604 02605 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional 02606 // function attributes. 02607 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 02608 if (FnAttrs & ObsoleteFuncAttrs) { 02609 RetAttrs |= FnAttrs & ObsoleteFuncAttrs; 02610 FnAttrs &= ~ObsoleteFuncAttrs; 02611 } 02612 02613 // Set up the Attributes for the function. 02614 SmallVector<AttributeWithIndex, 8> Attrs; 02615 if (RetAttrs != Attribute::None) 02616 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 02617 02618 SmallVector<Value*, 8> Args; 02619 02620 // Loop through FunctionType's arguments and ensure they are specified 02621 // correctly. Also, gather any parameter attributes. 02622 FunctionType::param_iterator I = Ty->param_begin(); 02623 FunctionType::param_iterator E = Ty->param_end(); 02624 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 02625 const Type *ExpectedTy = 0; 02626 if (I != E) { 02627 ExpectedTy = *I++; 02628 } else if (!Ty->isVarArg()) { 02629 return Error(ArgList[i].Loc, "too many arguments specified"); 02630 } 02631 02632 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 02633 return Error(ArgList[i].Loc, "argument is not of expected type '" + 02634 ExpectedTy->getDescription() + "'"); 02635 Args.push_back(ArgList[i].V); 02636 if (ArgList[i].Attrs != Attribute::None) 02637 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 02638 } 02639 02640 if (I != E) 02641 return Error(CallLoc, "not enough parameters specified for call"); 02642 02643 if (FnAttrs != Attribute::None) 02644 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 02645 02646 // Finish off the Attributes and check them 02647 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 02648 02649 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB), 02650 cast<BasicBlock>(UnwindBB), 02651 Args.begin(), Args.end()); 02652 II->setCallingConv(CC); 02653 II->setAttributes(PAL); 02654 Inst = II; 02655 return false; 02656 } 02657 02658 02659 02660 //===----------------------------------------------------------------------===// 02661 // Binary Operators. 02662 //===----------------------------------------------------------------------===// 02663 02664 /// ParseArithmetic 02665 /// ::= ArithmeticOps TypeAndValue ',' Value 02666 /// 02667 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1, 02668 /// then any integer operand is allowed, if it is 2, any fp operand is allowed. 02669 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 02670 unsigned Opc, unsigned OperandType) { 02671 LocTy Loc; Value *LHS, *RHS; 02672 if (ParseTypeAndValue(LHS, Loc, PFS) || 02673 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 02674 ParseValue(LHS->getType(), RHS, PFS)) 02675 return true; 02676 02677 bool Valid; 02678 switch (OperandType) { 02679 default: assert(0 && "Unknown operand type!"); 02680 case 0: // int or FP. 02681 Valid = LHS->getType()->isIntOrIntVector() || 02682 LHS->getType()->isFPOrFPVector(); 02683 break; 02684 case 1: Valid = LHS->getType()->isIntOrIntVector(); break; 02685 case 2: Valid = LHS->getType()->isFPOrFPVector(); break; 02686 } 02687 02688 if (!Valid) 02689 return Error(Loc, "invalid operand type for instruction"); 02690 02691 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 02692 return false; 02693 } 02694 02695 /// ParseLogical 02696 /// ::= ArithmeticOps TypeAndValue ',' Value { 02697 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 02698 unsigned Opc) { 02699 LocTy Loc; Value *LHS, *RHS; 02700 if (ParseTypeAndValue(LHS, Loc, PFS) || 02701 ParseToken(lltok::comma, "expected ',' in logical operation") || 02702 ParseValue(LHS->getType(), RHS, PFS)) 02703 return true; 02704 02705 if (!LHS->getType()->isIntOrIntVector()) 02706 return Error(Loc,"instruction requires integer or integer vector operands"); 02707 02708 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 02709 return false; 02710 } 02711 02712 02713 /// ParseCompare 02714 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 02715 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 02716 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value 02717 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value 02718 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 02719 unsigned Opc) { 02720 // Parse the integer/fp comparison predicate. 02721 LocTy Loc; 02722 unsigned Pred; 02723 Value *LHS, *RHS; 02724 if (ParseCmpPredicate(Pred, Opc) || 02725 ParseTypeAndValue(LHS, Loc, PFS) || 02726 ParseToken(lltok::comma, "expected ',' after compare value") || 02727 ParseValue(LHS->getType(), RHS, PFS)) 02728 return true; 02729 02730 if (Opc == Instruction::FCmp) { 02731 if (!LHS->getType()->isFPOrFPVector()) 02732 return Error(Loc, "fcmp requires floating point operands"); 02733 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 02734 } else if (Opc == Instruction::ICmp) { 02735 if (!LHS->getType()->isIntOrIntVector() && 02736 !isa<PointerType>(LHS->getType())) 02737 return Error(Loc, "icmp requires integer operands"); 02738 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 02739 } else if (Opc == Instruction::VFCmp) { 02740 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType())) 02741 return Error(Loc, "vfcmp requires vector floating point operands"); 02742 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 02743 } else if (Opc == Instruction::VICmp) { 02744 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType())) 02745 return Error(Loc, "vicmp requires vector floating point operands"); 02746 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 02747 } 02748 return false; 02749 } 02750 02751 //===----------------------------------------------------------------------===// 02752 // Other Instructions. 02753 //===----------------------------------------------------------------------===// 02754 02755 02756 /// ParseCast 02757 /// ::= CastOpc TypeAndValue 'to' Type 02758 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 02759 unsigned Opc) { 02760 LocTy Loc; Value *Op; 02761 PATypeHolder DestTy(Type::VoidTy); 02762 if (ParseTypeAndValue(Op, Loc, PFS) || 02763 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 02764 ParseType(DestTy)) 02765 return true; 02766 02767 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) 02768 return Error(Loc, "invalid cast opcode for cast from '" + 02769 Op->getType()->getDescription() + "' to '" + 02770 DestTy->getDescription() + "'"); 02771 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 02772 return false; 02773 } 02774 02775 /// ParseSelect 02776 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 02777 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 02778 LocTy Loc; 02779 Value *Op0, *Op1, *Op2; 02780 if (ParseTypeAndValue(Op0, Loc, PFS) || 02781 ParseToken(lltok::comma, "expected ',' after select condition") || 02782 ParseTypeAndValue(Op1, PFS) || 02783 ParseToken(lltok::comma, "expected ',' after select value") || 02784 ParseTypeAndValue(Op2, PFS)) 02785 return true; 02786 02787 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 02788 return Error(Loc, Reason); 02789 02790 Inst = SelectInst::Create(Op0, Op1, Op2); 02791 return false; 02792 } 02793 02794 /// ParseVA_Arg 02795 /// ::= 'va_arg' TypeAndValue ',' Type 02796 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 02797 Value *Op; 02798 PATypeHolder EltTy(Type::VoidTy); 02799 LocTy TypeLoc; 02800 if (ParseTypeAndValue(Op, PFS) || 02801 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 02802 ParseType(EltTy, TypeLoc)) 02803 return true; 02804 02805 if (!EltTy->isFirstClassType()) 02806 return Error(TypeLoc, "va_arg requires operand with first class type"); 02807 02808 Inst = new VAArgInst(Op, EltTy); 02809 return false; 02810 } 02811 02812 /// ParseExtractElement 02813 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 02814 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 02815 LocTy Loc; 02816 Value *Op0, *Op1; 02817 if (ParseTypeAndValue(Op0, Loc, PFS) || 02818 ParseToken(lltok::comma, "expected ',' after extract value") || 02819 ParseTypeAndValue(Op1, PFS)) 02820 return true; 02821 02822 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 02823 return Error(Loc, "invalid extractelement operands"); 02824 02825 Inst = new ExtractElementInst(Op0, Op1); 02826 return false; 02827 } 02828 02829 /// ParseInsertElement 02830 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 02831 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 02832 LocTy Loc; 02833 Value *Op0, *Op1, *Op2; 02834 if (ParseTypeAndValue(Op0, Loc, PFS) || 02835 ParseToken(lltok::comma, "expected ',' after insertelement value") || 02836 ParseTypeAndValue(Op1, PFS) || 02837 ParseToken(lltok::comma, "expected ',' after insertelement value") || 02838 ParseTypeAndValue(Op2, PFS)) 02839 return true; 02840 02841 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 02842 return Error(Loc, "invalid extractelement operands"); 02843 02844 Inst = InsertElementInst::Create(Op0, Op1, Op2); 02845 return false; 02846 } 02847 02848 /// ParseShuffleVector 02849 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 02850 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 02851 LocTy Loc; 02852 Value *Op0, *Op1, *Op2; 02853 if (ParseTypeAndValue(Op0, Loc, PFS) || 02854 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 02855 ParseTypeAndValue(Op1, PFS) || 02856 ParseToken(lltok::comma, "expected ',' after shuffle value") || 02857 ParseTypeAndValue(Op2, PFS)) 02858 return true; 02859 02860 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 02861 return Error(Loc, "invalid extractelement operands"); 02862 02863 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 02864 return false; 02865 } 02866 02867 /// ParsePHI 02868 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')* 02869 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 02870 PATypeHolder Ty(Type::VoidTy); 02871 Value *Op0, *Op1; 02872 LocTy TypeLoc = Lex.getLoc(); 02873 02874 if (ParseType(Ty) || 02875 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 02876 ParseValue(Ty, Op0, PFS) || 02877 ParseToken(lltok::comma, "expected ',' after insertelement value") || 02878 ParseValue(Type::LabelTy, Op1, PFS) || 02879 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 02880 return true; 02881 02882 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 02883 while (1) { 02884 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 02885 02886 if (!EatIfPresent(lltok::comma)) 02887 break; 02888 02889 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 02890 ParseValue(Ty, Op0, PFS) || 02891 ParseToken(lltok::comma, "expected ',' after insertelement value") || 02892 ParseValue(Type::LabelTy, Op1, PFS) || 02893 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 02894 return true; 02895 } 02896 02897 if (!Ty->isFirstClassType()) 02898 return Error(TypeLoc, "phi node must have first class type"); 02899 02900 PHINode *PN = PHINode::Create(Ty); 02901 PN->reserveOperandSpace(PHIVals.size()); 02902 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 02903 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 02904 Inst = PN; 02905 return false; 02906 } 02907 02908 /// ParseCall 02909 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value 02910 /// ParameterList OptionalAttrs 02911 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 02912 bool isTail) { 02913 unsigned CC, RetAttrs, FnAttrs; 02914 PATypeHolder RetType(Type::VoidTy); 02915 LocTy RetTypeLoc; 02916 ValID CalleeID; 02917 SmallVector<ParamInfo, 16> ArgList; 02918 LocTy CallLoc = Lex.getLoc(); 02919 02920 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || 02921 ParseOptionalCallingConv(CC) || 02922 ParseOptionalAttrs(RetAttrs, 1) || 02923 ParseType(RetType, RetTypeLoc) || 02924 ParseValID(CalleeID) || 02925 ParseParameterList(ArgList, PFS) || 02926 ParseOptionalAttrs(FnAttrs, 2)) 02927 return true; 02928 02929 // If RetType is a non-function pointer type, then this is the short syntax 02930 // for the call, which means that RetType is just the return type. Infer the 02931 // rest of the function argument types from the arguments that are present. 02932 const PointerType *PFTy = 0; 02933 const FunctionType *Ty = 0; 02934 if (!(PFTy = dyn_cast<PointerType>(RetType)) || 02935 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) { 02936 // Pull out the types of all of the arguments... 02937 std::vector<const Type*> ParamTypes; 02938 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 02939 ParamTypes.push_back(ArgList[i].V->getType()); 02940 02941 if (!FunctionType::isValidReturnType(RetType)) 02942 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 02943 02944 Ty = FunctionType::get(RetType, ParamTypes, false); 02945 PFTy = PointerType::getUnqual(Ty); 02946 } 02947 02948 // Look up the callee. 02949 Value *Callee; 02950 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; 02951 02952 // Check for call to invalid intrinsic to avoid crashing later. 02953 if (Function *F = dyn_cast<Function>(Callee)) { 02954 if (F->hasName() && F->getNameLen() >= 5 && 02955 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) && 02956 !F->getIntrinsicID(true)) 02957 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" + 02958 F->getNameStr() + "'"); 02959 } 02960 02961 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional 02962 // function attributes. 02963 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; 02964 if (FnAttrs & ObsoleteFuncAttrs) { 02965 RetAttrs |= FnAttrs & ObsoleteFuncAttrs; 02966 FnAttrs &= ~ObsoleteFuncAttrs; 02967 } 02968 02969 // Set up the Attributes for the function. 02970 SmallVector<AttributeWithIndex, 8> Attrs; 02971 if (RetAttrs != Attribute::None) 02972 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); 02973 02974 SmallVector<Value*, 8> Args; 02975 02976 // Loop through FunctionType's arguments and ensure they are specified 02977 // correctly. Also, gather any parameter attributes. 02978 FunctionType::param_iterator I = Ty->param_begin(); 02979 FunctionType::param_iterator E = Ty->param_end(); 02980 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 02981 const Type *ExpectedTy = 0; 02982 if (I != E) { 02983 ExpectedTy = *I++; 02984 } else if (!Ty->isVarArg()) { 02985 return Error(ArgList[i].Loc, "too many arguments specified"); 02986 } 02987 02988 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 02989 return Error(ArgList[i].Loc, "argument is not of expected type '" + 02990 ExpectedTy->getDescription() + "'"); 02991 Args.push_back(ArgList[i].V); 02992 if (ArgList[i].Attrs != Attribute::None) 02993 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); 02994 } 02995 02996 if (I != E) 02997 return Error(CallLoc, "not enough parameters specified for call"); 02998 02999 if (FnAttrs != Attribute::None) 03000 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); 03001 03002 // Finish off the Attributes and check them 03003 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); 03004 03005 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end()); 03006 CI->setTailCall(isTail); 03007 CI->setCallingConv(CC); 03008 CI->setAttributes(PAL); 03009 Inst = CI; 03010 return false; 03011 } 03012 03013 //===----------------------------------------------------------------------===// 03014 // Memory Instructions. 03015 //===----------------------------------------------------------------------===// 03016 03017 /// ParseAlloc 03018 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)? 03019 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)? 03020 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, 03021 unsigned Opc) { 03022 PATypeHolder Ty(Type::VoidTy); 03023 Value *Size = 0; 03024 LocTy SizeLoc = 0; 03025 unsigned Alignment = 0; 03026 if (ParseType(Ty)) return true; 03027 03028 if (EatIfPresent(lltok::comma)) { 03029 if (Lex.getKind() == lltok::kw_align) { 03030 if (ParseOptionalAlignment(Alignment)) return true; 03031 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) || 03032 ParseOptionalCommaAlignment(Alignment)) { 03033 return true; 03034 } 03035 } 03036 03037 if (Size && Size->getType() != Type::Int32Ty) 03038 return Error(SizeLoc, "element count must be i32"); 03039 03040 if (Opc == Instruction::Malloc) 03041 Inst = new MallocInst(Ty, Size, Alignment); 03042 else 03043 Inst = new AllocaInst(Ty, Size, Alignment); 03044 return false; 03045 } 03046 03047 /// ParseFree 03048 /// ::= 'free' TypeAndValue 03049 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) { 03050 Value *Val; LocTy Loc; 03051 if (ParseTypeAndValue(Val, Loc, PFS)) return true; 03052 if (!isa<PointerType>(Val->getType())) 03053 return Error(Loc, "operand to free must be a pointer"); 03054 Inst = new FreeInst(Val); 03055 return false; 03056 } 03057 03058 /// ParseLoad 03059 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)? 03060 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, 03061 bool isVolatile) { 03062 Value *Val; LocTy Loc; 03063 unsigned Alignment; 03064 if (ParseTypeAndValue(Val, Loc, PFS) || 03065 ParseOptionalCommaAlignment(Alignment)) 03066 return true; 03067 03068 if (!isa<PointerType>(Val->getType()) || 03069 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType()) 03070 return Error(Loc, "load operand must be a pointer to a first class type"); 03071 03072 Inst = new LoadInst(Val, "", isVolatile, Alignment); 03073 return false; 03074 } 03075 03076 /// ParseStore 03077 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)? 03078 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, 03079 bool isVolatile) { 03080 Value *Val, *Ptr; LocTy Loc, PtrLoc; 03081 unsigned Alignment; 03082 if (ParseTypeAndValue(Val, Loc, PFS) || 03083 ParseToken(lltok::comma, "expected ',' after store operand") || 03084 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 03085 ParseOptionalCommaAlignment(Alignment)) 03086 return true; 03087 03088 if (!isa<PointerType>(Ptr->getType())) 03089 return Error(PtrLoc, "store operand must be a pointer"); 03090 if (!Val->getType()->isFirstClassType()) 03091 return Error(Loc, "store operand must be a first class value"); 03092 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 03093 return Error(Loc, "stored value and pointer type do not match"); 03094 03095 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment); 03096 return false; 03097 } 03098 03099 /// ParseGetResult 03100 /// ::= 'getresult' TypeAndValue ',' uint 03101 /// FIXME: Remove support for getresult in LLVM 3.0 03102 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) { 03103 Value *Val; LocTy ValLoc, EltLoc; 03104 unsigned Element; 03105 if (ParseTypeAndValue(Val, ValLoc, PFS) || 03106 ParseToken(lltok::comma, "expected ',' after getresult operand") || 03107 ParseUInt32(Element, EltLoc)) 03108 return true; 03109 03110 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 03111 return Error(ValLoc, "getresult inst requires an aggregate operand"); 03112 if (!ExtractValueInst::getIndexedType(Val->getType(), Element)) 03113 return Error(EltLoc, "invalid getresult index for value"); 03114 Inst = ExtractValueInst::Create(Val, Element); 03115 return false; 03116 } 03117 03118 /// ParseGetElementPtr 03119 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)* 03120 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 03121 Value *Ptr, *Val; LocTy Loc, EltLoc; 03122 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; 03123 03124 if (!isa<PointerType>(Ptr->getType())) 03125 return Error(Loc, "base of getelementptr must be a pointer"); 03126 03127 SmallVector<Value*, 16> Indices; 03128 while (EatIfPresent(lltok::comma)) { 03129 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 03130 if (!isa<IntegerType>(Val->getType())) 03131 return Error(EltLoc, "getelementptr index must be an integer"); 03132 Indices.push_back(Val); 03133 } 03134 03135 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), 03136 Indices.begin(), Indices.end())) 03137 return Error(Loc, "invalid getelementptr indices"); 03138 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end()); 03139 return false; 03140 } 03141 03142 /// ParseExtractValue 03143 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 03144 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 03145 Value *Val; LocTy Loc; 03146 SmallVector<unsigned, 4> Indices; 03147 if (ParseTypeAndValue(Val, Loc, PFS) || 03148 ParseIndexList(Indices)) 03149 return true; 03150 03151 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType())) 03152 return Error(Loc, "extractvalue operand must be array or struct"); 03153 03154 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(), 03155 Indices.end())) 03156 return Error(Loc, "invalid indices for extractvalue"); 03157 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end()); 03158 return false; 03159 } 03160 03161 /// ParseInsertValue 03162 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 03163 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 03164 Value *Val0, *Val1; LocTy Loc0, Loc1; 03165 SmallVector<unsigned, 4> Indices; 03166 if (ParseTypeAndValue(Val0, Loc0, PFS) || 03167 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 03168 ParseTypeAndValue(Val1, Loc1, PFS) || 03169 ParseIndexList(Indices)) 03170 return true; 03171 03172 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType())) 03173 return Error(Loc0, "extractvalue operand must be array or struct"); 03174 03175 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), 03176 Indices.end())) 03177 return Error(Loc0, "invalid indices for insertvalue"); 03178 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end()); 03179 return false; 03180 }