blob: e26e0452397eca0c1061f8394022b0d47e58cf67 [file] [log] [blame]
Chris Lattnerdf986172009-01-02 07:01:27 +00001//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
Nick Lewyckycb337992009-05-10 20:57:05 +000021#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000022#include "llvm/Module.h"
23#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattnerdf986172009-01-02 07:01:27 +000029namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030 /// ValID - Represents a reference of a definition of some sort with no type.
31 /// There are several cases where we have to parse the value but where the
32 /// type can depend on later context. This may either be a numeric reference
33 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000034 struct ValID {
35 enum {
36 t_LocalID, t_GlobalID, // ID in UIntVal.
37 t_LocalName, t_GlobalName, // Name in StrVal.
38 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
39 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000040 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000041 t_Constant, // Value in ConstantVal.
42 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
43 } Kind;
44
45 LLParser::LocTy Loc;
46 unsigned UIntVal;
47 std::string StrVal, StrVal2;
48 APSInt APSIntVal;
49 APFloat APFloatVal;
50 Constant *ConstantVal;
51 ValID() : APFloatVal(0.0) {}
52 };
53}
54
Chris Lattner3ed88ef2009-01-02 08:05:26 +000055/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000056bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000057 // Prime the lexer.
58 Lex.Lex();
59
Chris Lattnerad7d1e22009-01-04 20:44:11 +000060 return ParseTopLevelEntities() ||
61 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000062}
63
64/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65/// module.
66bool LLParser::ValidateEndOfModule() {
67 if (!ForwardRefTypes.empty())
68 return Error(ForwardRefTypes.begin()->second.second,
69 "use of undefined type named '" +
70 ForwardRefTypes.begin()->first + "'");
71 if (!ForwardRefTypeIDs.empty())
72 return Error(ForwardRefTypeIDs.begin()->second.second,
73 "use of undefined type '%" +
74 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75
76 if (!ForwardRefVals.empty())
77 return Error(ForwardRefVals.begin()->second.second,
78 "use of undefined value '@" + ForwardRefVals.begin()->first +
79 "'");
80
81 if (!ForwardRefValIDs.empty())
82 return Error(ForwardRefValIDs.begin()->second.second,
83 "use of undefined value '@" +
84 utostr(ForwardRefValIDs.begin()->first) + "'");
85
86 // Look for intrinsic functions and CallInst that need to be upgraded
87 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
88 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
89
90 return false;
91}
92
93//===----------------------------------------------------------------------===//
94// Top-Level Entities
95//===----------------------------------------------------------------------===//
96
97bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000098 while (1) {
99 switch (Lex.getKind()) {
100 default: return TokError("expected top-level entity");
101 case lltok::Eof: return false;
102 //case lltok::kw_define:
103 case lltok::kw_declare: if (ParseDeclare()) return true; break;
104 case lltok::kw_define: if (ParseDefine()) return true; break;
105 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
106 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
107 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
108 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
109 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
110 case lltok::LocalVar: if (ParseNamedType()) return true; break;
111 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112
113 // The Global variable production with no name can have many different
114 // optional leading prefixes, the production is:
115 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
116 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000117 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 case lltok::kw_internal: // OptionalLinkage
119 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000120 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000121 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000122 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::kw_appending: // OptionalLinkage
124 case lltok::kw_dllexport: // OptionalLinkage
125 case lltok::kw_common: // OptionalLinkage
126 case lltok::kw_dllimport: // OptionalLinkage
127 case lltok::kw_extern_weak: // OptionalLinkage
128 case lltok::kw_external: { // OptionalLinkage
129 unsigned Linkage, Visibility;
130 if (ParseOptionalLinkage(Linkage) ||
131 ParseOptionalVisibility(Visibility) ||
132 ParseGlobal("", 0, Linkage, true, Visibility))
133 return true;
134 break;
135 }
136 case lltok::kw_default: // OptionalVisibility
137 case lltok::kw_hidden: // OptionalVisibility
138 case lltok::kw_protected: { // OptionalVisibility
139 unsigned Visibility;
140 if (ParseOptionalVisibility(Visibility) ||
141 ParseGlobal("", 0, 0, false, Visibility))
142 return true;
143 break;
144 }
145
146 case lltok::kw_thread_local: // OptionalThreadLocal
147 case lltok::kw_addrspace: // OptionalAddrSpace
148 case lltok::kw_constant: // GlobalType
149 case lltok::kw_global: // GlobalType
150 if (ParseGlobal("", 0, 0, false, 0)) return true;
151 break;
152 }
153 }
154}
155
156
157/// toplevelentity
158/// ::= 'module' 'asm' STRINGCONSTANT
159bool LLParser::ParseModuleAsm() {
160 assert(Lex.getKind() == lltok::kw_module);
161 Lex.Lex();
162
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000163 std::string AsmStr;
164 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
165 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000166
167 const std::string &AsmSoFar = M->getModuleInlineAsm();
168 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000169 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 return false;
173}
174
175/// toplevelentity
176/// ::= 'target' 'triple' '=' STRINGCONSTANT
177/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
178bool LLParser::ParseTargetDefinition() {
179 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000180 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 switch (Lex.Lex()) {
182 default: return TokError("unknown target property");
183 case lltok::kw_triple:
184 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
186 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000187 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000188 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 return false;
190 case lltok::kw_datalayout:
191 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000192 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
193 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000194 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000195 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return false;
197 }
198}
199
200/// toplevelentity
201/// ::= 'deplibs' '=' '[' ']'
202/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
203bool LLParser::ParseDepLibs() {
204 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
207 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
208 return true;
209
210 if (EatIfPresent(lltok::rsquare))
211 return false;
212
213 std::string Str;
214 if (ParseStringConstant(Str)) return true;
215 M->addLibrary(Str);
216
217 while (EatIfPresent(lltok::comma)) {
218 if (ParseStringConstant(Str)) return true;
219 M->addLibrary(Str);
220 }
221
222 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000223}
224
225/// toplevelentity
226/// ::= 'type' type
227bool LLParser::ParseUnnamedType() {
228 assert(Lex.getKind() == lltok::kw_type);
229 LocTy TypeLoc = Lex.getLoc();
230 Lex.Lex(); // eat kw_type
231
232 PATypeHolder Ty(Type::VoidTy);
233 if (ParseType(Ty)) return true;
234
235 unsigned TypeID = NumberedTypes.size();
236
Chris Lattnerdf986172009-01-02 07:01:27 +0000237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000241 if (FI->second.first.get() == Ty)
242 return Error(TypeLoc, "self referential type is invalid");
243
Chris Lattnerdf986172009-01-02 07:01:27 +0000244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245 Ty = FI->second.first.get();
246 ForwardRefTypeIDs.erase(FI);
247 }
248
249 NumberedTypes.push_back(Ty);
250
251 return false;
252}
253
254/// toplevelentity
255/// ::= LocalVar '=' 'type' type
256bool LLParser::ParseNamedType() {
257 std::string Name = Lex.getStrVal();
258 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000260
261 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262
263 if (ParseToken(lltok::equal, "expected '=' after name") ||
264 ParseToken(lltok::kw_type, "expected 'type' after name") ||
265 ParseType(Ty))
266 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000267
Chris Lattnerdf986172009-01-02 07:01:27 +0000268 // Set the type name, checking for conflicts as we do so.
269 bool AlreadyExists = M->addTypeName(Name, Ty);
270 if (!AlreadyExists) return false;
271
272 // See if this type is a forward reference. We need to eagerly resolve
273 // types to allow recursive type redefinitions below.
274 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
275 FI = ForwardRefTypes.find(Name);
276 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000277 if (FI->second.first.get() == Ty)
278 return Error(NameLoc, "self referential type is invalid");
279
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
281 Ty = FI->second.first.get();
282 ForwardRefTypes.erase(FI);
283 }
284
285 // Inserting a name that is already defined, get the existing name.
286 const Type *Existing = M->getTypeByName(Name);
287 assert(Existing && "Conflict but no matching type?!");
288
289 // Otherwise, this is an attempt to redefine a type. That's okay if
290 // the redefinition is identical to the original.
291 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
292 if (Existing == Ty) return false;
293
294 // Any other kind of (non-equivalent) redefinition is an error.
295 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
296 Ty->getDescription() + "'");
297}
298
299
300/// toplevelentity
301/// ::= 'declare' FunctionHeader
302bool LLParser::ParseDeclare() {
303 assert(Lex.getKind() == lltok::kw_declare);
304 Lex.Lex();
305
306 Function *F;
307 return ParseFunctionHeader(F, false);
308}
309
310/// toplevelentity
311/// ::= 'define' FunctionHeader '{' ...
312bool LLParser::ParseDefine() {
313 assert(Lex.getKind() == lltok::kw_define);
314 Lex.Lex();
315
316 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000317 return ParseFunctionHeader(F, true) ||
318 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000319}
320
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000321/// ParseGlobalType
322/// ::= 'constant'
323/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000324bool LLParser::ParseGlobalType(bool &IsConstant) {
325 if (Lex.getKind() == lltok::kw_constant)
326 IsConstant = true;
327 else if (Lex.getKind() == lltok::kw_global)
328 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000329 else {
330 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000332 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 Lex.Lex();
334 return false;
335}
336
337/// ParseNamedGlobal:
338/// GlobalVar '=' OptionalVisibility ALIAS ...
339/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
340bool LLParser::ParseNamedGlobal() {
341 assert(Lex.getKind() == lltok::GlobalVar);
342 LocTy NameLoc = Lex.getLoc();
343 std::string Name = Lex.getStrVal();
344 Lex.Lex();
345
346 bool HasLinkage;
347 unsigned Linkage, Visibility;
348 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
349 ParseOptionalLinkage(Linkage, HasLinkage) ||
350 ParseOptionalVisibility(Visibility))
351 return true;
352
353 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
354 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
355 return ParseAlias(Name, NameLoc, Visibility);
356}
357
358/// ParseAlias:
359/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000361/// ::= TypeAndValue
362/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
363/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000364///
365/// Everything through visibility has already been parsed.
366///
367bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
370 Lex.Lex();
371 unsigned Linkage;
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
374 return true;
375
376 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000377 Linkage != GlobalValue::WeakAnyLinkage &&
378 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000379 Linkage != GlobalValue::InternalLinkage &&
380 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 return Error(LinkageLoc, "invalid linkage type for alias");
382
383 Constant *Aliasee;
384 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000385 if (Lex.getKind() != lltok::kw_bitcast &&
386 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000387 if (ParseGlobalTypeAndValue(Aliasee)) return true;
388 } else {
389 // The bitcast dest type is not present, it is implied by the dest type.
390 ValID ID;
391 if (ParseValID(ID)) return true;
392 if (ID.Kind != ValID::t_Constant)
393 return Error(AliaseeLoc, "invalid aliasee");
394 Aliasee = ID.ConstantVal;
395 }
396
397 if (!isa<PointerType>(Aliasee->getType()))
398 return Error(AliaseeLoc, "alias must have pointer type");
399
400 // Okay, create the alias but do not insert it into the module yet.
401 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
402 (GlobalValue::LinkageTypes)Linkage, Name,
403 Aliasee);
404 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
405
406 // See if this value already exists in the symbol table. If so, it is either
407 // a redefinition or a definition of a forward reference.
408 if (GlobalValue *Val =
409 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
410 // See if this was a redefinition. If so, there is no entry in
411 // ForwardRefVals.
412 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
413 I = ForwardRefVals.find(Name);
414 if (I == ForwardRefVals.end())
415 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
416
417 // Otherwise, this was a definition of forward ref. Verify that types
418 // agree.
419 if (Val->getType() != GA->getType())
420 return Error(NameLoc,
421 "forward reference and definition of alias have different types");
422
423 // If they agree, just RAUW the old value with the alias and remove the
424 // forward ref info.
425 Val->replaceAllUsesWith(GA);
426 Val->eraseFromParent();
427 ForwardRefVals.erase(I);
428 }
429
430 // Insert into the module, we know its name won't collide now.
431 M->getAliasList().push_back(GA);
432 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
433
434 return false;
435}
436
437/// ParseGlobal
438/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
439/// OptionalAddrSpace GlobalType Type Const
440/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
441/// OptionalAddrSpace GlobalType Type Const
442///
443/// Everything through visibility has been parsed already.
444///
445bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
446 unsigned Linkage, bool HasLinkage,
447 unsigned Visibility) {
448 unsigned AddrSpace;
449 bool ThreadLocal, IsConstant;
450 LocTy TyLoc;
451
452 PATypeHolder Ty(Type::VoidTy);
453 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
454 ParseOptionalAddrSpace(AddrSpace) ||
455 ParseGlobalType(IsConstant) ||
456 ParseType(Ty, TyLoc))
457 return true;
458
459 // If the linkage is specified and is external, then no initializer is
460 // present.
461 Constant *Init = 0;
462 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000463 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000464 Linkage != GlobalValue::ExternalLinkage)) {
465 if (ParseGlobalValue(Ty, Init))
466 return true;
467 }
468
Chris Lattnera9a9e072009-03-09 04:49:14 +0000469 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000470 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000471
472 GlobalVariable *GV = 0;
473
474 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000475 if (!Name.empty()) {
476 if ((GV = M->getGlobalVariable(Name, true)) &&
477 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000478 return Error(NameLoc, "redefinition of global '@" + Name + "'");
479 } else {
480 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
481 I = ForwardRefValIDs.find(NumberedVals.size());
482 if (I != ForwardRefValIDs.end()) {
483 GV = cast<GlobalVariable>(I->second.first);
484 ForwardRefValIDs.erase(I);
485 }
486 }
487
488 if (GV == 0) {
489 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
490 M, false, AddrSpace);
491 } else {
492 if (GV->getType()->getElementType() != Ty)
493 return Error(TyLoc,
494 "forward reference and definition of global have different types");
495
496 // Move the forward-reference to the correct spot in the module.
497 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
498 }
499
500 if (Name.empty())
501 NumberedVals.push_back(GV);
502
503 // Set the parsed properties on the global.
504 if (Init)
505 GV->setInitializer(Init);
506 GV->setConstant(IsConstant);
507 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
508 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
509 GV->setThreadLocal(ThreadLocal);
510
511 // Parse attributes on the global.
512 while (Lex.getKind() == lltok::comma) {
513 Lex.Lex();
514
515 if (Lex.getKind() == lltok::kw_section) {
516 Lex.Lex();
517 GV->setSection(Lex.getStrVal());
518 if (ParseToken(lltok::StringConstant, "expected global section string"))
519 return true;
520 } else if (Lex.getKind() == lltok::kw_align) {
521 unsigned Alignment;
522 if (ParseOptionalAlignment(Alignment)) return true;
523 GV->setAlignment(Alignment);
524 } else {
525 TokError("unknown global variable property!");
526 }
527 }
528
529 return false;
530}
531
532
533//===----------------------------------------------------------------------===//
534// GlobalValue Reference/Resolution Routines.
535//===----------------------------------------------------------------------===//
536
537/// GetGlobalVal - Get a value with the specified name or ID, creating a
538/// forward reference record if needed. This can return null if the value
539/// exists but does not have the right type.
540GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
541 LocTy Loc) {
542 const PointerType *PTy = dyn_cast<PointerType>(Ty);
543 if (PTy == 0) {
544 Error(Loc, "global variable reference must have pointer type");
545 return 0;
546 }
547
548 // Look this name up in the normal function symbol table.
549 GlobalValue *Val =
550 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
551
552 // If this is a forward reference for the value, see if we already created a
553 // forward ref record.
554 if (Val == 0) {
555 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
556 I = ForwardRefVals.find(Name);
557 if (I != ForwardRefVals.end())
558 Val = I->second.first;
559 }
560
561 // If we have the value in the symbol table or fwd-ref table, return it.
562 if (Val) {
563 if (Val->getType() == Ty) return Val;
564 Error(Loc, "'@" + Name + "' defined with type '" +
565 Val->getType()->getDescription() + "'");
566 return 0;
567 }
568
569 // Otherwise, create a new forward reference for this value and remember it.
570 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000571 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
572 // Function types can return opaque but functions can't.
573 if (isa<OpaqueType>(FT->getReturnType())) {
574 Error(Loc, "function may not return opaque type");
575 return 0;
576 }
577
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000578 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000579 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000580 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000581 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000582 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000583
584 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
585 return FwdVal;
586}
587
588GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
589 const PointerType *PTy = dyn_cast<PointerType>(Ty);
590 if (PTy == 0) {
591 Error(Loc, "global variable reference must have pointer type");
592 return 0;
593 }
594
595 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
596
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
599 if (Val == 0) {
600 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
601 I = ForwardRefValIDs.find(ID);
602 if (I != ForwardRefValIDs.end())
603 Val = I->second.first;
604 }
605
606 // If we have the value in the symbol table or fwd-ref table, return it.
607 if (Val) {
608 if (Val->getType() == Ty) return Val;
609 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
610 Val->getType()->getDescription() + "'");
611 return 0;
612 }
613
614 // Otherwise, create a new forward reference for this value and remember it.
615 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000616 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000619 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000620 return 0;
621 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000622 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000623 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000624 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000625 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000626 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000627
628 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629 return FwdVal;
630}
631
632
633//===----------------------------------------------------------------------===//
634// Helper Routines.
635//===----------------------------------------------------------------------===//
636
637/// ParseToken - If the current token has the specified kind, eat it and return
638/// success. Otherwise, emit the specified error and return failure.
639bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
640 if (Lex.getKind() != T)
641 return TokError(ErrMsg);
642 Lex.Lex();
643 return false;
644}
645
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000646/// ParseStringConstant
647/// ::= StringConstant
648bool LLParser::ParseStringConstant(std::string &Result) {
649 if (Lex.getKind() != lltok::StringConstant)
650 return TokError("expected string constant");
651 Result = Lex.getStrVal();
652 Lex.Lex();
653 return false;
654}
655
656/// ParseUInt32
657/// ::= uint32
658bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
660 return TokError("expected integer");
661 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
662 if (Val64 != unsigned(Val64))
663 return TokError("expected 32-bit integer (too large)");
664 Val = Val64;
665 Lex.Lex();
666 return false;
667}
668
669
670/// ParseOptionalAddrSpace
671/// := /*empty*/
672/// := 'addrspace' '(' uint32 ')'
673bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
674 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000675 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000678 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000679 ParseToken(lltok::rparen, "expected ')' in address space");
680}
681
682/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
683/// indicates what kind of attribute list this is: 0: function arg, 1: result,
684/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000685/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000686bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687 Attrs = Attribute::None;
688 LocTy AttrLoc = Lex.getLoc();
689
690 while (1) {
691 switch (Lex.getKind()) {
692 case lltok::kw_sext:
693 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000694 // Treat these as signext/zeroext if they occur in the argument list after
695 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
696 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
697 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000699 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (Lex.getKind() == lltok::kw_sext)
701 Attrs |= Attribute::SExt;
702 else
703 Attrs |= Attribute::ZExt;
704 break;
705 }
706 // FALL THROUGH.
707 default: // End of attributes.
708 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
709 return Error(AttrLoc, "invalid use of function-only attribute");
710
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000711 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 return Error(AttrLoc, "invalid use of parameter-only attribute");
713
714 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000715 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
716 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
717 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
718 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
719 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
720 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
721 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
722 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000723
Devang Patel578efa92009-06-05 21:57:13 +0000724 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
725 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
726 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
727 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
728 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
729 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
730 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
731 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
732 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
733 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
734 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000735
736 case lltok::kw_align: {
737 unsigned Alignment;
738 if (ParseOptionalAlignment(Alignment))
739 return true;
740 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
741 continue;
742 }
743 }
744 Lex.Lex();
745 }
746}
747
748/// ParseOptionalLinkage
749/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000750/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000751/// ::= 'internal'
752/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000753/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000754/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000755/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000756/// ::= 'appending'
757/// ::= 'dllexport'
758/// ::= 'common'
759/// ::= 'dllimport'
760/// ::= 'extern_weak'
761/// ::= 'external'
762bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
763 HasLinkage = false;
764 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000765 default: Res = GlobalValue::ExternalLinkage; return false;
766 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
767 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
768 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
769 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
770 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
771 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000772 case lltok::kw_available_externally:
773 Res = GlobalValue::AvailableExternallyLinkage;
774 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000775 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
776 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000777 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000778 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000779 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000780 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000781 }
782 Lex.Lex();
783 HasLinkage = true;
784 return false;
785}
786
787/// ParseOptionalVisibility
788/// ::= /*empty*/
789/// ::= 'default'
790/// ::= 'hidden'
791/// ::= 'protected'
792///
793bool LLParser::ParseOptionalVisibility(unsigned &Res) {
794 switch (Lex.getKind()) {
795 default: Res = GlobalValue::DefaultVisibility; return false;
796 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
797 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
798 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
799 }
800 Lex.Lex();
801 return false;
802}
803
804/// ParseOptionalCallingConv
805/// ::= /*empty*/
806/// ::= 'ccc'
807/// ::= 'fastcc'
808/// ::= 'coldcc'
809/// ::= 'x86_stdcallcc'
810/// ::= 'x86_fastcallcc'
811/// ::= 'cc' UINT
812///
813bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
814 switch (Lex.getKind()) {
815 default: CC = CallingConv::C; return false;
816 case lltok::kw_ccc: CC = CallingConv::C; break;
817 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
818 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
819 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
820 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000821 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 }
823 Lex.Lex();
824 return false;
825}
826
827/// ParseOptionalAlignment
828/// ::= /* empty */
829/// ::= 'align' 4
830bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
831 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000832 if (!EatIfPresent(lltok::kw_align))
833 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000834 LocTy AlignLoc = Lex.getLoc();
835 if (ParseUInt32(Alignment)) return true;
836 if (!isPowerOf2_32(Alignment))
837 return Error(AlignLoc, "alignment is not a power of two");
838 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000839}
840
841/// ParseOptionalCommaAlignment
842/// ::= /* empty */
843/// ::= ',' 'align' 4
844bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
845 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000846 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000847 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000848 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000849 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000850}
851
852/// ParseIndexList
853/// ::= (',' uint32)+
854bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
855 if (Lex.getKind() != lltok::comma)
856 return TokError("expected ',' as start of index list");
857
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000858 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000860 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000861 Indices.push_back(Idx);
862 }
863
864 return false;
865}
866
867//===----------------------------------------------------------------------===//
868// Type Parsing.
869//===----------------------------------------------------------------------===//
870
871/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000872bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
873 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000874 if (ParseTypeRec(Result)) return true;
875
876 // Verify no unresolved uprefs.
877 if (!UpRefs.empty())
878 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000879
Chris Lattnera9a9e072009-03-09 04:49:14 +0000880 if (!AllowVoid && Result.get() == Type::VoidTy)
881 return Error(TypeLoc, "void type only allowed for function results");
882
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 return false;
884}
885
886/// HandleUpRefs - Every time we finish a new layer of types, this function is
887/// called. It loops through the UpRefs vector, which is a list of the
888/// currently active types. For each type, if the up-reference is contained in
889/// the newly completed type, we decrement the level count. When the level
890/// count reaches zero, the up-referenced type is the type that is passed in:
891/// thus we can complete the cycle.
892///
893PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
894 // If Ty isn't abstract, or if there are no up-references in it, then there is
895 // nothing to resolve here.
896 if (!ty->isAbstract() || UpRefs.empty()) return ty;
897
898 PATypeHolder Ty(ty);
899#if 0
900 errs() << "Type '" << Ty->getDescription()
901 << "' newly formed. Resolving upreferences.\n"
902 << UpRefs.size() << " upreferences active!\n";
903#endif
904
905 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
906 // to zero), we resolve them all together before we resolve them to Ty. At
907 // the end of the loop, if there is anything to resolve to Ty, it will be in
908 // this variable.
909 OpaqueType *TypeToResolve = 0;
910
911 for (unsigned i = 0; i != UpRefs.size(); ++i) {
912 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
913 bool ContainsType =
914 std::find(Ty->subtype_begin(), Ty->subtype_end(),
915 UpRefs[i].LastContainedTy) != Ty->subtype_end();
916
917#if 0
918 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
919 << UpRefs[i].LastContainedTy->getDescription() << ") = "
920 << (ContainsType ? "true" : "false")
921 << " level=" << UpRefs[i].NestingLevel << "\n";
922#endif
923 if (!ContainsType)
924 continue;
925
926 // Decrement level of upreference
927 unsigned Level = --UpRefs[i].NestingLevel;
928 UpRefs[i].LastContainedTy = Ty;
929
930 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
931 if (Level != 0)
932 continue;
933
934#if 0
935 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
936#endif
937 if (!TypeToResolve)
938 TypeToResolve = UpRefs[i].UpRefTy;
939 else
940 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
941 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
942 --i; // Do not skip the next element.
943 }
944
945 if (TypeToResolve)
946 TypeToResolve->refineAbstractTypeTo(Ty);
947
948 return Ty;
949}
950
951
952/// ParseTypeRec - The recursive function used to process the internal
953/// implementation details of types.
954bool LLParser::ParseTypeRec(PATypeHolder &Result) {
955 switch (Lex.getKind()) {
956 default:
957 return TokError("expected type");
958 case lltok::Type:
959 // TypeRec ::= 'float' | 'void' (etc)
960 Result = Lex.getTyVal();
961 Lex.Lex();
962 break;
963 case lltok::kw_opaque:
964 // TypeRec ::= 'opaque'
965 Result = OpaqueType::get();
966 Lex.Lex();
967 break;
968 case lltok::lbrace:
969 // TypeRec ::= '{' ... '}'
970 if (ParseStructType(Result, false))
971 return true;
972 break;
973 case lltok::lsquare:
974 // TypeRec ::= '[' ... ']'
975 Lex.Lex(); // eat the lsquare.
976 if (ParseArrayVectorType(Result, false))
977 return true;
978 break;
979 case lltok::less: // Either vector or packed struct.
980 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000981 Lex.Lex();
982 if (Lex.getKind() == lltok::lbrace) {
983 if (ParseStructType(Result, true) ||
984 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000985 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000986 } else if (ParseArrayVectorType(Result, true))
987 return true;
988 break;
989 case lltok::LocalVar:
990 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
991 // TypeRec ::= %foo
992 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
993 Result = T;
994 } else {
995 Result = OpaqueType::get();
996 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
997 std::make_pair(Result,
998 Lex.getLoc())));
999 M->addTypeName(Lex.getStrVal(), Result.get());
1000 }
1001 Lex.Lex();
1002 break;
1003
1004 case lltok::LocalVarID:
1005 // TypeRec ::= %4
1006 if (Lex.getUIntVal() < NumberedTypes.size())
1007 Result = NumberedTypes[Lex.getUIntVal()];
1008 else {
1009 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1010 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1011 if (I != ForwardRefTypeIDs.end())
1012 Result = I->second.first;
1013 else {
1014 Result = OpaqueType::get();
1015 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1016 std::make_pair(Result,
1017 Lex.getLoc())));
1018 }
1019 }
1020 Lex.Lex();
1021 break;
1022 case lltok::backslash: {
1023 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001024 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001025 unsigned Val;
1026 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1028 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1029 Result = OT;
1030 break;
1031 }
1032 }
1033
1034 // Parse the type suffixes.
1035 while (1) {
1036 switch (Lex.getKind()) {
1037 // End of type.
1038 default: return false;
1039
1040 // TypeRec ::= TypeRec '*'
1041 case lltok::star:
1042 if (Result.get() == Type::LabelTy)
1043 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001044 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001045 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001046 if (!PointerType::isValidElementType(Result.get()))
1047 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001048 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1049 Lex.Lex();
1050 break;
1051
1052 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1053 case lltok::kw_addrspace: {
1054 if (Result.get() == Type::LabelTy)
1055 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001056 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001057 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001058 if (!PointerType::isValidElementType(Result.get()))
1059 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 unsigned AddrSpace;
1061 if (ParseOptionalAddrSpace(AddrSpace) ||
1062 ParseToken(lltok::star, "expected '*' in address space"))
1063 return true;
1064
1065 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1066 break;
1067 }
1068
1069 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1070 case lltok::lparen:
1071 if (ParseFunctionType(Result))
1072 return true;
1073 break;
1074 }
1075 }
1076}
1077
1078/// ParseParameterList
1079/// ::= '(' ')'
1080/// ::= '(' Arg (',' Arg)* ')'
1081/// Arg
1082/// ::= Type OptionalAttributes Value OptionalAttributes
1083bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1084 PerFunctionState &PFS) {
1085 if (ParseToken(lltok::lparen, "expected '(' in call"))
1086 return true;
1087
1088 while (Lex.getKind() != lltok::rparen) {
1089 // If this isn't the first argument, we need a comma.
1090 if (!ArgList.empty() &&
1091 ParseToken(lltok::comma, "expected ',' in argument list"))
1092 return true;
1093
1094 // Parse the argument.
1095 LocTy ArgLoc;
1096 PATypeHolder ArgTy(Type::VoidTy);
1097 unsigned ArgAttrs1, ArgAttrs2;
1098 Value *V;
1099 if (ParseType(ArgTy, ArgLoc) ||
1100 ParseOptionalAttrs(ArgAttrs1, 0) ||
1101 ParseValue(ArgTy, V, PFS) ||
1102 // FIXME: Should not allow attributes after the argument, remove this in
1103 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001104 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001105 return true;
1106 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1107 }
1108
1109 Lex.Lex(); // Lex the ')'.
1110 return false;
1111}
1112
1113
1114
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001115/// ParseArgumentList - Parse the argument list for a function type or function
1116/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001117/// ::= '(' ArgTypeListI ')'
1118/// ArgTypeListI
1119/// ::= /*empty*/
1120/// ::= '...'
1121/// ::= ArgTypeList ',' '...'
1122/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001123///
Chris Lattnerdf986172009-01-02 07:01:27 +00001124bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001125 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001126 isVarArg = false;
1127 assert(Lex.getKind() == lltok::lparen);
1128 Lex.Lex(); // eat the (.
1129
1130 if (Lex.getKind() == lltok::rparen) {
1131 // empty
1132 } else if (Lex.getKind() == lltok::dotdotdot) {
1133 isVarArg = true;
1134 Lex.Lex();
1135 } else {
1136 LocTy TypeLoc = Lex.getLoc();
1137 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001138 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001139 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001140
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001141 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1142 // types (such as a function returning a pointer to itself). If parsing a
1143 // function prototype, we require fully resolved types.
1144 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001145 ParseOptionalAttrs(Attrs, 0)) return true;
1146
Chris Lattnera9a9e072009-03-09 04:49:14 +00001147 if (ArgTy == Type::VoidTy)
1148 return Error(TypeLoc, "argument can not have void type");
1149
Chris Lattnerdf986172009-01-02 07:01:27 +00001150 if (Lex.getKind() == lltok::LocalVar ||
1151 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1152 Name = Lex.getStrVal();
1153 Lex.Lex();
1154 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001155
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001156 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001157 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001158
1159 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1160
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001161 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001163 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001164 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001165 break;
1166 }
1167
1168 // Otherwise must be an argument type.
1169 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001170 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001171 ParseOptionalAttrs(Attrs, 0)) return true;
1172
Chris Lattnera9a9e072009-03-09 04:49:14 +00001173 if (ArgTy == Type::VoidTy)
1174 return Error(TypeLoc, "argument can not have void type");
1175
Chris Lattnerdf986172009-01-02 07:01:27 +00001176 if (Lex.getKind() == lltok::LocalVar ||
1177 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1178 Name = Lex.getStrVal();
1179 Lex.Lex();
1180 } else {
1181 Name = "";
1182 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001183
1184 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1185 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001186
1187 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1188 }
1189 }
1190
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001191 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001192}
1193
1194/// ParseFunctionType
1195/// ::= Type ArgumentList OptionalAttrs
1196bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1197 assert(Lex.getKind() == lltok::lparen);
1198
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001199 if (!FunctionType::isValidReturnType(Result))
1200 return TokError("invalid function return type");
1201
Chris Lattnerdf986172009-01-02 07:01:27 +00001202 std::vector<ArgInfo> ArgList;
1203 bool isVarArg;
1204 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001205 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001206 // FIXME: Allow, but ignore attributes on function types!
1207 // FIXME: Remove in LLVM 3.0
1208 ParseOptionalAttrs(Attrs, 2))
1209 return true;
1210
1211 // Reject names on the arguments lists.
1212 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1213 if (!ArgList[i].Name.empty())
1214 return Error(ArgList[i].Loc, "argument name invalid in function type");
1215 if (!ArgList[i].Attrs != 0) {
1216 // Allow but ignore attributes on function types; this permits
1217 // auto-upgrade.
1218 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1219 }
1220 }
1221
1222 std::vector<const Type*> ArgListTy;
1223 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1224 ArgListTy.push_back(ArgList[i].Type);
1225
1226 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1227 return false;
1228}
1229
1230/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1231/// TypeRec
1232/// ::= '{' '}'
1233/// ::= '{' TypeRec (',' TypeRec)* '}'
1234/// ::= '<' '{' '}' '>'
1235/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1236bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1237 assert(Lex.getKind() == lltok::lbrace);
1238 Lex.Lex(); // Consume the '{'
1239
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001240 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 return false;
1243 }
1244
1245 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001246 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 if (ParseTypeRec(Result)) return true;
1248 ParamsList.push_back(Result);
1249
Chris Lattnera9a9e072009-03-09 04:49:14 +00001250 if (Result == Type::VoidTy)
1251 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001252 if (!StructType::isValidElementType(Result))
1253 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001254
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001255 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001256 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001257 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001258
1259 if (Result == Type::VoidTy)
1260 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001261 if (!StructType::isValidElementType(Result))
1262 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001263
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 ParamsList.push_back(Result);
1265 }
1266
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001267 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1268 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001269
1270 std::vector<const Type*> ParamsListTy;
1271 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1272 ParamsListTy.push_back(ParamsList[i].get());
1273 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1274 return false;
1275}
1276
1277/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1278/// token has already been consumed.
1279/// TypeRec
1280/// ::= '[' APSINTVAL 'x' Types ']'
1281/// ::= '<' APSINTVAL 'x' Types '>'
1282bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1283 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1284 Lex.getAPSIntVal().getBitWidth() > 64)
1285 return TokError("expected number in address space");
1286
1287 LocTy SizeLoc = Lex.getLoc();
1288 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001289 Lex.Lex();
1290
1291 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1292 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001293
1294 LocTy TypeLoc = Lex.getLoc();
1295 PATypeHolder EltTy(Type::VoidTy);
1296 if (ParseTypeRec(EltTy)) return true;
1297
Chris Lattnera9a9e072009-03-09 04:49:14 +00001298 if (EltTy == Type::VoidTy)
1299 return Error(TypeLoc, "array and vector element type cannot be void");
1300
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001301 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1302 "expected end of sequential type"))
1303 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001304
1305 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001306 if (Size == 0)
1307 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001308 if ((unsigned)Size != Size)
1309 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001310 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 return Error(TypeLoc, "vector element type must be fp or integer");
1312 Result = VectorType::get(EltTy, unsigned(Size));
1313 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001314 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 return Error(TypeLoc, "invalid array element type");
1316 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1317 }
1318 return false;
1319}
1320
1321//===----------------------------------------------------------------------===//
1322// Function Semantic Analysis.
1323//===----------------------------------------------------------------------===//
1324
1325LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1326 : P(p), F(f) {
1327
1328 // Insert unnamed arguments into the NumberedVals list.
1329 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1330 AI != E; ++AI)
1331 if (!AI->hasName())
1332 NumberedVals.push_back(AI);
1333}
1334
1335LLParser::PerFunctionState::~PerFunctionState() {
1336 // If there were any forward referenced non-basicblock values, delete them.
1337 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1338 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1339 if (!isa<BasicBlock>(I->second.first)) {
1340 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1341 ->getType()));
1342 delete I->second.first;
1343 I->second.first = 0;
1344 }
1345
1346 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1347 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1348 if (!isa<BasicBlock>(I->second.first)) {
1349 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1350 ->getType()));
1351 delete I->second.first;
1352 I->second.first = 0;
1353 }
1354}
1355
1356bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1357 if (!ForwardRefVals.empty())
1358 return P.Error(ForwardRefVals.begin()->second.second,
1359 "use of undefined value '%" + ForwardRefVals.begin()->first +
1360 "'");
1361 if (!ForwardRefValIDs.empty())
1362 return P.Error(ForwardRefValIDs.begin()->second.second,
1363 "use of undefined value '%" +
1364 utostr(ForwardRefValIDs.begin()->first) + "'");
1365 return false;
1366}
1367
1368
1369/// GetVal - Get a value with the specified name or ID, creating a
1370/// forward reference record if needed. This can return null if the value
1371/// exists but does not have the right type.
1372Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1373 const Type *Ty, LocTy Loc) {
1374 // Look this name up in the normal function symbol table.
1375 Value *Val = F.getValueSymbolTable().lookup(Name);
1376
1377 // If this is a forward reference for the value, see if we already created a
1378 // forward ref record.
1379 if (Val == 0) {
1380 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1381 I = ForwardRefVals.find(Name);
1382 if (I != ForwardRefVals.end())
1383 Val = I->second.first;
1384 }
1385
1386 // If we have the value in the symbol table or fwd-ref table, return it.
1387 if (Val) {
1388 if (Val->getType() == Ty) return Val;
1389 if (Ty == Type::LabelTy)
1390 P.Error(Loc, "'%" + Name + "' is not a basic block");
1391 else
1392 P.Error(Loc, "'%" + Name + "' defined with type '" +
1393 Val->getType()->getDescription() + "'");
1394 return 0;
1395 }
1396
1397 // Don't make placeholders with invalid type.
1398 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1399 P.Error(Loc, "invalid use of a non-first-class type");
1400 return 0;
1401 }
1402
1403 // Otherwise, create a new forward reference for this value and remember it.
1404 Value *FwdVal;
1405 if (Ty == Type::LabelTy)
1406 FwdVal = BasicBlock::Create(Name, &F);
1407 else
1408 FwdVal = new Argument(Ty, Name);
1409
1410 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1411 return FwdVal;
1412}
1413
1414Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1415 LocTy Loc) {
1416 // Look this name up in the normal function symbol table.
1417 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1418
1419 // If this is a forward reference for the value, see if we already created a
1420 // forward ref record.
1421 if (Val == 0) {
1422 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1423 I = ForwardRefValIDs.find(ID);
1424 if (I != ForwardRefValIDs.end())
1425 Val = I->second.first;
1426 }
1427
1428 // If we have the value in the symbol table or fwd-ref table, return it.
1429 if (Val) {
1430 if (Val->getType() == Ty) return Val;
1431 if (Ty == Type::LabelTy)
1432 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1433 else
1434 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1435 Val->getType()->getDescription() + "'");
1436 return 0;
1437 }
1438
1439 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1440 P.Error(Loc, "invalid use of a non-first-class type");
1441 return 0;
1442 }
1443
1444 // Otherwise, create a new forward reference for this value and remember it.
1445 Value *FwdVal;
1446 if (Ty == Type::LabelTy)
1447 FwdVal = BasicBlock::Create("", &F);
1448 else
1449 FwdVal = new Argument(Ty);
1450
1451 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1452 return FwdVal;
1453}
1454
1455/// SetInstName - After an instruction is parsed and inserted into its
1456/// basic block, this installs its name.
1457bool LLParser::PerFunctionState::SetInstName(int NameID,
1458 const std::string &NameStr,
1459 LocTy NameLoc, Instruction *Inst) {
1460 // If this instruction has void type, it cannot have a name or ID specified.
1461 if (Inst->getType() == Type::VoidTy) {
1462 if (NameID != -1 || !NameStr.empty())
1463 return P.Error(NameLoc, "instructions returning void cannot have a name");
1464 return false;
1465 }
1466
1467 // If this was a numbered instruction, verify that the instruction is the
1468 // expected value and resolve any forward references.
1469 if (NameStr.empty()) {
1470 // If neither a name nor an ID was specified, just use the next ID.
1471 if (NameID == -1)
1472 NameID = NumberedVals.size();
1473
1474 if (unsigned(NameID) != NumberedVals.size())
1475 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1476 utostr(NumberedVals.size()) + "'");
1477
1478 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1479 ForwardRefValIDs.find(NameID);
1480 if (FI != ForwardRefValIDs.end()) {
1481 if (FI->second.first->getType() != Inst->getType())
1482 return P.Error(NameLoc, "instruction forward referenced with type '" +
1483 FI->second.first->getType()->getDescription() + "'");
1484 FI->second.first->replaceAllUsesWith(Inst);
1485 ForwardRefValIDs.erase(FI);
1486 }
1487
1488 NumberedVals.push_back(Inst);
1489 return false;
1490 }
1491
1492 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1493 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1494 FI = ForwardRefVals.find(NameStr);
1495 if (FI != ForwardRefVals.end()) {
1496 if (FI->second.first->getType() != Inst->getType())
1497 return P.Error(NameLoc, "instruction forward referenced with type '" +
1498 FI->second.first->getType()->getDescription() + "'");
1499 FI->second.first->replaceAllUsesWith(Inst);
1500 ForwardRefVals.erase(FI);
1501 }
1502
1503 // Set the name on the instruction.
1504 Inst->setName(NameStr);
1505
1506 if (Inst->getNameStr() != NameStr)
1507 return P.Error(NameLoc, "multiple definition of local value named '" +
1508 NameStr + "'");
1509 return false;
1510}
1511
1512/// GetBB - Get a basic block with the specified name or ID, creating a
1513/// forward reference record if needed.
1514BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1515 LocTy Loc) {
1516 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1517}
1518
1519BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1520 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1521}
1522
1523/// DefineBB - Define the specified basic block, which is either named or
1524/// unnamed. If there is an error, this returns null otherwise it returns
1525/// the block being defined.
1526BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1527 LocTy Loc) {
1528 BasicBlock *BB;
1529 if (Name.empty())
1530 BB = GetBB(NumberedVals.size(), Loc);
1531 else
1532 BB = GetBB(Name, Loc);
1533 if (BB == 0) return 0; // Already diagnosed error.
1534
1535 // Move the block to the end of the function. Forward ref'd blocks are
1536 // inserted wherever they happen to be referenced.
1537 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1538
1539 // Remove the block from forward ref sets.
1540 if (Name.empty()) {
1541 ForwardRefValIDs.erase(NumberedVals.size());
1542 NumberedVals.push_back(BB);
1543 } else {
1544 // BB forward references are already in the function symbol table.
1545 ForwardRefVals.erase(Name);
1546 }
1547
1548 return BB;
1549}
1550
1551//===----------------------------------------------------------------------===//
1552// Constants.
1553//===----------------------------------------------------------------------===//
1554
1555/// ParseValID - Parse an abstract value that doesn't necessarily have a
1556/// type implied. For example, if we parse "4" we don't know what integer type
1557/// it has. The value will later be combined with its type and checked for
1558/// sanity.
1559bool LLParser::ParseValID(ValID &ID) {
1560 ID.Loc = Lex.getLoc();
1561 switch (Lex.getKind()) {
1562 default: return TokError("expected value token");
1563 case lltok::GlobalID: // @42
1564 ID.UIntVal = Lex.getUIntVal();
1565 ID.Kind = ValID::t_GlobalID;
1566 break;
1567 case lltok::GlobalVar: // @foo
1568 ID.StrVal = Lex.getStrVal();
1569 ID.Kind = ValID::t_GlobalName;
1570 break;
1571 case lltok::LocalVarID: // %42
1572 ID.UIntVal = Lex.getUIntVal();
1573 ID.Kind = ValID::t_LocalID;
1574 break;
1575 case lltok::LocalVar: // %foo
1576 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1577 ID.StrVal = Lex.getStrVal();
1578 ID.Kind = ValID::t_LocalName;
1579 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001580 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1581 ID.Kind = ValID::t_Constant;
1582 Lex.Lex();
1583 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001584 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001585 if (ParseMDNodeVector(Elts) ||
1586 ParseToken(lltok::rbrace, "expected end of metadata node"))
1587 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001588
Jay Foade3e51c02009-05-21 09:52:38 +00001589 ID.ConstantVal = MDNode::get(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001590 return false;
1591 }
1592
1593 // MDString:
1594 // ::= '!' STRINGCONSTANT
1595 std::string Str;
1596 if (ParseStringConstant(Str)) return true;
1597
1598 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1599 return false;
1600 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 case lltok::APSInt:
1602 ID.APSIntVal = Lex.getAPSIntVal();
1603 ID.Kind = ValID::t_APSInt;
1604 break;
1605 case lltok::APFloat:
1606 ID.APFloatVal = Lex.getAPFloatVal();
1607 ID.Kind = ValID::t_APFloat;
1608 break;
1609 case lltok::kw_true:
1610 ID.ConstantVal = ConstantInt::getTrue();
1611 ID.Kind = ValID::t_Constant;
1612 break;
1613 case lltok::kw_false:
1614 ID.ConstantVal = ConstantInt::getFalse();
1615 ID.Kind = ValID::t_Constant;
1616 break;
1617 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1618 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1619 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1620
1621 case lltok::lbrace: {
1622 // ValID ::= '{' ConstVector '}'
1623 Lex.Lex();
1624 SmallVector<Constant*, 16> Elts;
1625 if (ParseGlobalValueVector(Elts) ||
1626 ParseToken(lltok::rbrace, "expected end of struct constant"))
1627 return true;
1628
Jay Foade3e51c02009-05-21 09:52:38 +00001629 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 ID.Kind = ValID::t_Constant;
1631 return false;
1632 }
1633 case lltok::less: {
1634 // ValID ::= '<' ConstVector '>' --> Vector.
1635 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1636 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001637 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001638
1639 SmallVector<Constant*, 16> Elts;
1640 LocTy FirstEltLoc = Lex.getLoc();
1641 if (ParseGlobalValueVector(Elts) ||
1642 (isPackedStruct &&
1643 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1644 ParseToken(lltok::greater, "expected end of constant"))
1645 return true;
1646
1647 if (isPackedStruct) {
Jay Foade3e51c02009-05-21 09:52:38 +00001648 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 ID.Kind = ValID::t_Constant;
1650 return false;
1651 }
1652
1653 if (Elts.empty())
1654 return Error(ID.Loc, "constant vector must not be empty");
1655
1656 if (!Elts[0]->getType()->isInteger() &&
1657 !Elts[0]->getType()->isFloatingPoint())
1658 return Error(FirstEltLoc,
1659 "vector elements must have integer or floating point type");
1660
1661 // Verify that all the vector elements have the same type.
1662 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1663 if (Elts[i]->getType() != Elts[0]->getType())
1664 return Error(FirstEltLoc,
1665 "vector element #" + utostr(i) +
1666 " is not of type '" + Elts[0]->getType()->getDescription());
1667
Jay Foade3e51c02009-05-21 09:52:38 +00001668 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001669 ID.Kind = ValID::t_Constant;
1670 return false;
1671 }
1672 case lltok::lsquare: { // Array Constant
1673 Lex.Lex();
1674 SmallVector<Constant*, 16> Elts;
1675 LocTy FirstEltLoc = Lex.getLoc();
1676 if (ParseGlobalValueVector(Elts) ||
1677 ParseToken(lltok::rsquare, "expected end of array constant"))
1678 return true;
1679
1680 // Handle empty element.
1681 if (Elts.empty()) {
1682 // Use undef instead of an array because it's inconvenient to determine
1683 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001684 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 return false;
1686 }
1687
1688 if (!Elts[0]->getType()->isFirstClassType())
1689 return Error(FirstEltLoc, "invalid array element type: " +
1690 Elts[0]->getType()->getDescription());
1691
1692 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1693
1694 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001695 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 if (Elts[i]->getType() != Elts[0]->getType())
1697 return Error(FirstEltLoc,
1698 "array element #" + utostr(i) +
1699 " is not of type '" +Elts[0]->getType()->getDescription());
1700 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001701
Jay Foade3e51c02009-05-21 09:52:38 +00001702 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 ID.Kind = ValID::t_Constant;
1704 return false;
1705 }
1706 case lltok::kw_c: // c "foo"
1707 Lex.Lex();
1708 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1709 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1710 ID.Kind = ValID::t_Constant;
1711 return false;
1712
1713 case lltok::kw_asm: {
1714 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1715 bool HasSideEffect;
1716 Lex.Lex();
1717 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001718 ParseStringConstant(ID.StrVal) ||
1719 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 ParseToken(lltok::StringConstant, "expected constraint string"))
1721 return true;
1722 ID.StrVal2 = Lex.getStrVal();
1723 ID.UIntVal = HasSideEffect;
1724 ID.Kind = ValID::t_InlineAsm;
1725 return false;
1726 }
1727
1728 case lltok::kw_trunc:
1729 case lltok::kw_zext:
1730 case lltok::kw_sext:
1731 case lltok::kw_fptrunc:
1732 case lltok::kw_fpext:
1733 case lltok::kw_bitcast:
1734 case lltok::kw_uitofp:
1735 case lltok::kw_sitofp:
1736 case lltok::kw_fptoui:
1737 case lltok::kw_fptosi:
1738 case lltok::kw_inttoptr:
1739 case lltok::kw_ptrtoint: {
1740 unsigned Opc = Lex.getUIntVal();
1741 PATypeHolder DestTy(Type::VoidTy);
1742 Constant *SrcVal;
1743 Lex.Lex();
1744 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1745 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001746 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 ParseType(DestTy) ||
1748 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1749 return true;
1750 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1751 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1752 SrcVal->getType()->getDescription() + "' to '" +
1753 DestTy->getDescription() + "'");
1754 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1755 DestTy);
1756 ID.Kind = ValID::t_Constant;
1757 return false;
1758 }
1759 case lltok::kw_extractvalue: {
1760 Lex.Lex();
1761 Constant *Val;
1762 SmallVector<unsigned, 4> Indices;
1763 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1764 ParseGlobalTypeAndValue(Val) ||
1765 ParseIndexList(Indices) ||
1766 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1767 return true;
1768 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1769 return Error(ID.Loc, "extractvalue operand must be array or struct");
1770 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1771 Indices.end()))
1772 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001773 ID.ConstantVal =
1774 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001775 ID.Kind = ValID::t_Constant;
1776 return false;
1777 }
1778 case lltok::kw_insertvalue: {
1779 Lex.Lex();
1780 Constant *Val0, *Val1;
1781 SmallVector<unsigned, 4> Indices;
1782 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1783 ParseGlobalTypeAndValue(Val0) ||
1784 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1785 ParseGlobalTypeAndValue(Val1) ||
1786 ParseIndexList(Indices) ||
1787 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1788 return true;
1789 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1790 return Error(ID.Loc, "extractvalue operand must be array or struct");
1791 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1792 Indices.end()))
1793 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001794 ID.ConstantVal =
1795 ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 ID.Kind = ValID::t_Constant;
1797 return false;
1798 }
1799 case lltok::kw_icmp:
1800 case lltok::kw_fcmp:
1801 case lltok::kw_vicmp:
1802 case lltok::kw_vfcmp: {
1803 unsigned PredVal, Opc = Lex.getUIntVal();
1804 Constant *Val0, *Val1;
1805 Lex.Lex();
1806 if (ParseCmpPredicate(PredVal, Opc) ||
1807 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1808 ParseGlobalTypeAndValue(Val0) ||
1809 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1810 ParseGlobalTypeAndValue(Val1) ||
1811 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1812 return true;
1813
1814 if (Val0->getType() != Val1->getType())
1815 return Error(ID.Loc, "compare operands must have the same type");
1816
1817 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1818
1819 if (Opc == Instruction::FCmp) {
1820 if (!Val0->getType()->isFPOrFPVector())
1821 return Error(ID.Loc, "fcmp requires floating point operands");
1822 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1823 } else if (Opc == Instruction::ICmp) {
1824 if (!Val0->getType()->isIntOrIntVector() &&
1825 !isa<PointerType>(Val0->getType()))
1826 return Error(ID.Loc, "icmp requires pointer or integer operands");
1827 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1828 } else if (Opc == Instruction::VFCmp) {
1829 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001830 if (!Val0->getType()->isFPOrFPVector() ||
1831 !isa<VectorType>(Val0->getType()))
1832 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1834 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001835 // FIXME: REMOVE VICMP Support
1836 if (!Val0->getType()->isIntOrIntVector() ||
1837 !isa<VectorType>(Val0->getType()))
1838 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1840 }
1841 ID.Kind = ValID::t_Constant;
1842 return false;
1843 }
1844
1845 // Binary Operators.
1846 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001847 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001849 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001851 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 case lltok::kw_udiv:
1853 case lltok::kw_sdiv:
1854 case lltok::kw_fdiv:
1855 case lltok::kw_urem:
1856 case lltok::kw_srem:
1857 case lltok::kw_frem: {
1858 unsigned Opc = Lex.getUIntVal();
1859 Constant *Val0, *Val1;
1860 Lex.Lex();
1861 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1862 ParseGlobalTypeAndValue(Val0) ||
1863 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1864 ParseGlobalTypeAndValue(Val1) ||
1865 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1866 return true;
1867 if (Val0->getType() != Val1->getType())
1868 return Error(ID.Loc, "operands of constexpr must have same type");
1869 if (!Val0->getType()->isIntOrIntVector() &&
1870 !Val0->getType()->isFPOrFPVector())
1871 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1872 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1873 ID.Kind = ValID::t_Constant;
1874 return false;
1875 }
1876
1877 // Logical Operations
1878 case lltok::kw_shl:
1879 case lltok::kw_lshr:
1880 case lltok::kw_ashr:
1881 case lltok::kw_and:
1882 case lltok::kw_or:
1883 case lltok::kw_xor: {
1884 unsigned Opc = Lex.getUIntVal();
1885 Constant *Val0, *Val1;
1886 Lex.Lex();
1887 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1888 ParseGlobalTypeAndValue(Val0) ||
1889 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1890 ParseGlobalTypeAndValue(Val1) ||
1891 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1892 return true;
1893 if (Val0->getType() != Val1->getType())
1894 return Error(ID.Loc, "operands of constexpr must have same type");
1895 if (!Val0->getType()->isIntOrIntVector())
1896 return Error(ID.Loc,
1897 "constexpr requires integer or integer vector operands");
1898 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1899 ID.Kind = ValID::t_Constant;
1900 return false;
1901 }
1902
1903 case lltok::kw_getelementptr:
1904 case lltok::kw_shufflevector:
1905 case lltok::kw_insertelement:
1906 case lltok::kw_extractelement:
1907 case lltok::kw_select: {
1908 unsigned Opc = Lex.getUIntVal();
1909 SmallVector<Constant*, 16> Elts;
1910 Lex.Lex();
1911 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1912 ParseGlobalValueVector(Elts) ||
1913 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1914 return true;
1915
1916 if (Opc == Instruction::GetElementPtr) {
1917 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1918 return Error(ID.Loc, "getelementptr requires pointer operand");
1919
1920 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1921 (Value**)&Elts[1], Elts.size()-1))
1922 return Error(ID.Loc, "invalid indices for getelementptr");
1923 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1924 &Elts[1], Elts.size()-1);
1925 } else if (Opc == Instruction::Select) {
1926 if (Elts.size() != 3)
1927 return Error(ID.Loc, "expected three operands to select");
1928 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1929 Elts[2]))
1930 return Error(ID.Loc, Reason);
1931 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1932 } else if (Opc == Instruction::ShuffleVector) {
1933 if (Elts.size() != 3)
1934 return Error(ID.Loc, "expected three operands to shufflevector");
1935 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1936 return Error(ID.Loc, "invalid operands to shufflevector");
1937 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1938 } else if (Opc == Instruction::ExtractElement) {
1939 if (Elts.size() != 2)
1940 return Error(ID.Loc, "expected two operands to extractelement");
1941 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1942 return Error(ID.Loc, "invalid extractelement operands");
1943 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1944 } else {
1945 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1946 if (Elts.size() != 3)
1947 return Error(ID.Loc, "expected three operands to insertelement");
1948 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1949 return Error(ID.Loc, "invalid insertelement operands");
1950 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1951 }
1952
1953 ID.Kind = ValID::t_Constant;
1954 return false;
1955 }
1956 }
1957
1958 Lex.Lex();
1959 return false;
1960}
1961
1962/// ParseGlobalValue - Parse a global value with the specified type.
1963bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1964 V = 0;
1965 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001966 return ParseValID(ID) ||
1967 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001968}
1969
1970/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1971/// constant.
1972bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1973 Constant *&V) {
1974 if (isa<FunctionType>(Ty))
1975 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1976
1977 switch (ID.Kind) {
1978 default: assert(0 && "Unknown ValID!");
1979 case ValID::t_LocalID:
1980 case ValID::t_LocalName:
1981 return Error(ID.Loc, "invalid use of function-local name");
1982 case ValID::t_InlineAsm:
1983 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1984 case ValID::t_GlobalName:
1985 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1986 return V == 0;
1987 case ValID::t_GlobalID:
1988 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1989 return V == 0;
1990 case ValID::t_APSInt:
1991 if (!isa<IntegerType>(Ty))
1992 return Error(ID.Loc, "integer constant must have integer type");
1993 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1994 V = ConstantInt::get(ID.APSIntVal);
1995 return false;
1996 case ValID::t_APFloat:
1997 if (!Ty->isFloatingPoint() ||
1998 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1999 return Error(ID.Loc, "floating point constant invalid for type");
2000
2001 // The lexer has no type info, so builds all float and double FP constants
2002 // as double. Fix this here. Long double does not need this.
2003 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2004 Ty == Type::FloatTy) {
2005 bool Ignored;
2006 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2007 &Ignored);
2008 }
2009 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002010
2011 if (V->getType() != Ty)
2012 return Error(ID.Loc, "floating point constant does not have type '" +
2013 Ty->getDescription() + "'");
2014
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 return false;
2016 case ValID::t_Null:
2017 if (!isa<PointerType>(Ty))
2018 return Error(ID.Loc, "null must be a pointer type");
2019 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2020 return false;
2021 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002022 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002023 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2024 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002025 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 V = UndefValue::get(Ty);
2027 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002028 case ValID::t_EmptyArray:
2029 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2030 return Error(ID.Loc, "invalid empty array initializer");
2031 V = UndefValue::get(Ty);
2032 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002034 // FIXME: LabelTy should not be a first-class type.
2035 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 return Error(ID.Loc, "invalid type for null constant");
2037 V = Constant::getNullValue(Ty);
2038 return false;
2039 case ValID::t_Constant:
2040 if (ID.ConstantVal->getType() != Ty)
2041 return Error(ID.Loc, "constant expression type mismatch");
2042 V = ID.ConstantVal;
2043 return false;
2044 }
2045}
2046
2047bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2048 PATypeHolder Type(Type::VoidTy);
2049 return ParseType(Type) ||
2050 ParseGlobalValue(Type, V);
2051}
2052
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002053/// ParseGlobalValueVector
2054/// ::= /*empty*/
2055/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002056bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2057 // Empty list.
2058 if (Lex.getKind() == lltok::rbrace ||
2059 Lex.getKind() == lltok::rsquare ||
2060 Lex.getKind() == lltok::greater ||
2061 Lex.getKind() == lltok::rparen)
2062 return false;
2063
2064 Constant *C;
2065 if (ParseGlobalTypeAndValue(C)) return true;
2066 Elts.push_back(C);
2067
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002068 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002069 if (ParseGlobalTypeAndValue(C)) return true;
2070 Elts.push_back(C);
2071 }
2072
2073 return false;
2074}
2075
2076
2077//===----------------------------------------------------------------------===//
2078// Function Parsing.
2079//===----------------------------------------------------------------------===//
2080
2081bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2082 PerFunctionState &PFS) {
2083 if (ID.Kind == ValID::t_LocalID)
2084 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2085 else if (ID.Kind == ValID::t_LocalName)
2086 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002087 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2089 const FunctionType *FTy =
2090 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2091 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2092 return Error(ID.Loc, "invalid type for inline asm constraint string");
2093 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2094 return false;
2095 } else {
2096 Constant *C;
2097 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2098 V = C;
2099 return false;
2100 }
2101
2102 return V == 0;
2103}
2104
2105bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2106 V = 0;
2107 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002108 return ParseValID(ID) ||
2109 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002110}
2111
2112bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2113 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002114 return ParseType(T) ||
2115 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002116}
2117
2118/// FunctionHeader
2119/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2120/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2121/// OptionalAlign OptGC
2122bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2123 // Parse the linkage.
2124 LocTy LinkageLoc = Lex.getLoc();
2125 unsigned Linkage;
2126
2127 unsigned Visibility, CC, RetAttrs;
2128 PATypeHolder RetType(Type::VoidTy);
2129 LocTy RetTypeLoc = Lex.getLoc();
2130 if (ParseOptionalLinkage(Linkage) ||
2131 ParseOptionalVisibility(Visibility) ||
2132 ParseOptionalCallingConv(CC) ||
2133 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002134 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 return true;
2136
2137 // Verify that the linkage is ok.
2138 switch ((GlobalValue::LinkageTypes)Linkage) {
2139 case GlobalValue::ExternalLinkage:
2140 break; // always ok.
2141 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002142 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002143 if (isDefine)
2144 return Error(LinkageLoc, "invalid linkage for function definition");
2145 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002146 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002148 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002149 case GlobalValue::LinkOnceAnyLinkage:
2150 case GlobalValue::LinkOnceODRLinkage:
2151 case GlobalValue::WeakAnyLinkage:
2152 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 case GlobalValue::DLLExportLinkage:
2154 if (!isDefine)
2155 return Error(LinkageLoc, "invalid linkage for function declaration");
2156 break;
2157 case GlobalValue::AppendingLinkage:
2158 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002159 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 return Error(LinkageLoc, "invalid function linkage type");
2161 }
2162
Chris Lattner99bb3152009-01-05 08:00:30 +00002163 if (!FunctionType::isValidReturnType(RetType) ||
2164 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 return Error(RetTypeLoc, "invalid function return type");
2166
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002168
2169 std::string FunctionName;
2170 if (Lex.getKind() == lltok::GlobalVar) {
2171 FunctionName = Lex.getStrVal();
2172 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2173 unsigned NameID = Lex.getUIntVal();
2174
2175 if (NameID != NumberedVals.size())
2176 return TokError("function expected to be numbered '%" +
2177 utostr(NumberedVals.size()) + "'");
2178 } else {
2179 return TokError("expected function name");
2180 }
2181
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002182 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002183
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002184 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 return TokError("expected '(' in function argument list");
2186
2187 std::vector<ArgInfo> ArgList;
2188 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002191 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002192 std::string GC;
2193
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002194 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002195 ParseOptionalAttrs(FuncAttrs, 2) ||
2196 (EatIfPresent(lltok::kw_section) &&
2197 ParseStringConstant(Section)) ||
2198 ParseOptionalAlignment(Alignment) ||
2199 (EatIfPresent(lltok::kw_gc) &&
2200 ParseStringConstant(GC)))
2201 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002202
2203 // If the alignment was parsed as an attribute, move to the alignment field.
2204 if (FuncAttrs & Attribute::Alignment) {
2205 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2206 FuncAttrs &= ~Attribute::Alignment;
2207 }
2208
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 // Okay, if we got here, the function is syntactically valid. Convert types
2210 // and do semantic checks.
2211 std::vector<const Type*> ParamTypeList;
2212 SmallVector<AttributeWithIndex, 8> Attrs;
2213 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2214 // attributes.
2215 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2216 if (FuncAttrs & ObsoleteFuncAttrs) {
2217 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2218 FuncAttrs &= ~ObsoleteFuncAttrs;
2219 }
2220
2221 if (RetAttrs != Attribute::None)
2222 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2223
2224 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2225 ParamTypeList.push_back(ArgList[i].Type);
2226 if (ArgList[i].Attrs != Attribute::None)
2227 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2228 }
2229
2230 if (FuncAttrs != Attribute::None)
2231 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2232
2233 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2234
Chris Lattnera9a9e072009-03-09 04:49:14 +00002235 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2236 RetType != Type::VoidTy)
2237 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2238
Chris Lattnerdf986172009-01-02 07:01:27 +00002239 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2240 const PointerType *PFT = PointerType::getUnqual(FT);
2241
2242 Fn = 0;
2243 if (!FunctionName.empty()) {
2244 // If this was a definition of a forward reference, remove the definition
2245 // from the forward reference table and fill in the forward ref.
2246 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2247 ForwardRefVals.find(FunctionName);
2248 if (FRVI != ForwardRefVals.end()) {
2249 Fn = M->getFunction(FunctionName);
2250 ForwardRefVals.erase(FRVI);
2251 } else if ((Fn = M->getFunction(FunctionName))) {
2252 // If this function already exists in the symbol table, then it is
2253 // multiply defined. We accept a few cases for old backwards compat.
2254 // FIXME: Remove this stuff for LLVM 3.0.
2255 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2256 (!Fn->isDeclaration() && isDefine)) {
2257 // If the redefinition has different type or different attributes,
2258 // reject it. If both have bodies, reject it.
2259 return Error(NameLoc, "invalid redefinition of function '" +
2260 FunctionName + "'");
2261 } else if (Fn->isDeclaration()) {
2262 // Make sure to strip off any argument names so we can't get conflicts.
2263 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2264 AI != AE; ++AI)
2265 AI->setName("");
2266 }
2267 }
2268
2269 } else if (FunctionName.empty()) {
2270 // If this is a definition of a forward referenced function, make sure the
2271 // types agree.
2272 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2273 = ForwardRefValIDs.find(NumberedVals.size());
2274 if (I != ForwardRefValIDs.end()) {
2275 Fn = cast<Function>(I->second.first);
2276 if (Fn->getType() != PFT)
2277 return Error(NameLoc, "type of definition and forward reference of '@" +
2278 utostr(NumberedVals.size()) +"' disagree");
2279 ForwardRefValIDs.erase(I);
2280 }
2281 }
2282
2283 if (Fn == 0)
2284 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2285 else // Move the forward-reference to the correct spot in the module.
2286 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2287
2288 if (FunctionName.empty())
2289 NumberedVals.push_back(Fn);
2290
2291 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2292 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2293 Fn->setCallingConv(CC);
2294 Fn->setAttributes(PAL);
2295 Fn->setAlignment(Alignment);
2296 Fn->setSection(Section);
2297 if (!GC.empty()) Fn->setGC(GC.c_str());
2298
2299 // Add all of the arguments we parsed to the function.
2300 Function::arg_iterator ArgIt = Fn->arg_begin();
2301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2302 // If the argument has a name, insert it into the argument symbol table.
2303 if (ArgList[i].Name.empty()) continue;
2304
2305 // Set the name, if it conflicted, it will be auto-renamed.
2306 ArgIt->setName(ArgList[i].Name);
2307
2308 if (ArgIt->getNameStr() != ArgList[i].Name)
2309 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2310 ArgList[i].Name + "'");
2311 }
2312
2313 return false;
2314}
2315
2316
2317/// ParseFunctionBody
2318/// ::= '{' BasicBlock+ '}'
2319/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2320///
2321bool LLParser::ParseFunctionBody(Function &Fn) {
2322 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2323 return TokError("expected '{' in function body");
2324 Lex.Lex(); // eat the {.
2325
2326 PerFunctionState PFS(*this, Fn);
2327
2328 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2329 if (ParseBasicBlock(PFS)) return true;
2330
2331 // Eat the }.
2332 Lex.Lex();
2333
2334 // Verify function is ok.
2335 return PFS.VerifyFunctionComplete();
2336}
2337
2338/// ParseBasicBlock
2339/// ::= LabelStr? Instruction*
2340bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2341 // If this basic block starts out with a name, remember it.
2342 std::string Name;
2343 LocTy NameLoc = Lex.getLoc();
2344 if (Lex.getKind() == lltok::LabelStr) {
2345 Name = Lex.getStrVal();
2346 Lex.Lex();
2347 }
2348
2349 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2350 if (BB == 0) return true;
2351
2352 std::string NameStr;
2353
2354 // Parse the instructions in this block until we get a terminator.
2355 Instruction *Inst;
2356 do {
2357 // This instruction may have three possibilities for a name: a) none
2358 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2359 LocTy NameLoc = Lex.getLoc();
2360 int NameID = -1;
2361 NameStr = "";
2362
2363 if (Lex.getKind() == lltok::LocalVarID) {
2364 NameID = Lex.getUIntVal();
2365 Lex.Lex();
2366 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2367 return true;
2368 } else if (Lex.getKind() == lltok::LocalVar ||
2369 // FIXME: REMOVE IN LLVM 3.0
2370 Lex.getKind() == lltok::StringConstant) {
2371 NameStr = Lex.getStrVal();
2372 Lex.Lex();
2373 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2374 return true;
2375 }
2376
2377 if (ParseInstruction(Inst, BB, PFS)) return true;
2378
2379 BB->getInstList().push_back(Inst);
2380
2381 // Set the name on the instruction.
2382 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2383 } while (!isa<TerminatorInst>(Inst));
2384
2385 return false;
2386}
2387
2388//===----------------------------------------------------------------------===//
2389// Instruction Parsing.
2390//===----------------------------------------------------------------------===//
2391
2392/// ParseInstruction - Parse one of the many different instructions.
2393///
2394bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2395 PerFunctionState &PFS) {
2396 lltok::Kind Token = Lex.getKind();
2397 if (Token == lltok::Eof)
2398 return TokError("found end of file when expecting more instructions");
2399 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002400 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 Lex.Lex(); // Eat the keyword.
2402
2403 switch (Token) {
2404 default: return Error(Loc, "expected instruction opcode");
2405 // Terminator Instructions.
2406 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2407 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2408 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2409 case lltok::kw_br: return ParseBr(Inst, PFS);
2410 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2411 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2412 // Binary Operators.
2413 case lltok::kw_add:
2414 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002415 case lltok::kw_mul:
2416 // API compatibility: Accept either integer or floating-point types.
2417 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2418 case lltok::kw_fadd:
2419 case lltok::kw_fsub:
2420 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2421
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 case lltok::kw_udiv:
2423 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002424 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002425 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002426 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002427 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 case lltok::kw_shl:
2429 case lltok::kw_lshr:
2430 case lltok::kw_ashr:
2431 case lltok::kw_and:
2432 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002433 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002434 case lltok::kw_icmp:
2435 case lltok::kw_fcmp:
2436 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002437 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 // Casts.
2439 case lltok::kw_trunc:
2440 case lltok::kw_zext:
2441 case lltok::kw_sext:
2442 case lltok::kw_fptrunc:
2443 case lltok::kw_fpext:
2444 case lltok::kw_bitcast:
2445 case lltok::kw_uitofp:
2446 case lltok::kw_sitofp:
2447 case lltok::kw_fptoui:
2448 case lltok::kw_fptosi:
2449 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002450 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 // Other.
2452 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002453 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2455 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2456 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2457 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2458 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2459 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2460 // Memory.
2461 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002462 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 case lltok::kw_free: return ParseFree(Inst, PFS);
2464 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2465 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2466 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002467 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002469 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002471 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2474 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2475 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2476 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2477 }
2478}
2479
2480/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2481bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2482 // FIXME: REMOVE vicmp/vfcmp!
2483 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2484 switch (Lex.getKind()) {
2485 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2486 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2487 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2488 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2489 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2490 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2491 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2492 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2493 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2494 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2495 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2496 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2497 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2498 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2499 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2500 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2501 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2502 }
2503 } else {
2504 switch (Lex.getKind()) {
2505 default: TokError("expected icmp predicate (e.g. 'eq')");
2506 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2507 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2508 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2509 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2510 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2511 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2512 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2513 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2514 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2515 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2516 }
2517 }
2518 Lex.Lex();
2519 return false;
2520}
2521
2522//===----------------------------------------------------------------------===//
2523// Terminator Instructions.
2524//===----------------------------------------------------------------------===//
2525
2526/// ParseRet - Parse a return instruction.
2527/// ::= 'ret' void
2528/// ::= 'ret' TypeAndValue
2529/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2530bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2531 PerFunctionState &PFS) {
2532 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002533 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002534
2535 if (Ty == Type::VoidTy) {
2536 Inst = ReturnInst::Create();
2537 return false;
2538 }
2539
2540 Value *RV;
2541 if (ParseValue(Ty, RV, PFS)) return true;
2542
2543 // The normal case is one return value.
2544 if (Lex.getKind() == lltok::comma) {
2545 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2546 // of 'ret {i32,i32} {i32 1, i32 2}'
2547 SmallVector<Value*, 8> RVs;
2548 RVs.push_back(RV);
2549
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002550 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 if (ParseTypeAndValue(RV, PFS)) return true;
2552 RVs.push_back(RV);
2553 }
2554
2555 RV = UndefValue::get(PFS.getFunction().getReturnType());
2556 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2557 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2558 BB->getInstList().push_back(I);
2559 RV = I;
2560 }
2561 }
2562 Inst = ReturnInst::Create(RV);
2563 return false;
2564}
2565
2566
2567/// ParseBr
2568/// ::= 'br' TypeAndValue
2569/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2570bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2571 LocTy Loc, Loc2;
2572 Value *Op0, *Op1, *Op2;
2573 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2574
2575 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2576 Inst = BranchInst::Create(BB);
2577 return false;
2578 }
2579
2580 if (Op0->getType() != Type::Int1Ty)
2581 return Error(Loc, "branch condition must have 'i1' type");
2582
2583 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2584 ParseTypeAndValue(Op1, Loc, PFS) ||
2585 ParseToken(lltok::comma, "expected ',' after true destination") ||
2586 ParseTypeAndValue(Op2, Loc2, PFS))
2587 return true;
2588
2589 if (!isa<BasicBlock>(Op1))
2590 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 if (!isa<BasicBlock>(Op2))
2592 return Error(Loc2, "true destination of branch must be a basic block");
2593
2594 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2595 return false;
2596}
2597
2598/// ParseSwitch
2599/// Instruction
2600/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2601/// JumpTable
2602/// ::= (TypeAndValue ',' TypeAndValue)*
2603bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2604 LocTy CondLoc, BBLoc;
2605 Value *Cond, *DefaultBB;
2606 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2607 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2608 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2609 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2610 return true;
2611
2612 if (!isa<IntegerType>(Cond->getType()))
2613 return Error(CondLoc, "switch condition must have integer type");
2614 if (!isa<BasicBlock>(DefaultBB))
2615 return Error(BBLoc, "default destination must be a basic block");
2616
2617 // Parse the jump table pairs.
2618 SmallPtrSet<Value*, 32> SeenCases;
2619 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2620 while (Lex.getKind() != lltok::rsquare) {
2621 Value *Constant, *DestBB;
2622
2623 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2624 ParseToken(lltok::comma, "expected ',' after case value") ||
2625 ParseTypeAndValue(DestBB, BBLoc, PFS))
2626 return true;
2627
2628 if (!SeenCases.insert(Constant))
2629 return Error(CondLoc, "duplicate case value in switch");
2630 if (!isa<ConstantInt>(Constant))
2631 return Error(CondLoc, "case value is not a constant integer");
2632 if (!isa<BasicBlock>(DestBB))
2633 return Error(BBLoc, "case destination is not a basic block");
2634
2635 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2636 cast<BasicBlock>(DestBB)));
2637 }
2638
2639 Lex.Lex(); // Eat the ']'.
2640
2641 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2642 Table.size());
2643 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2644 SI->addCase(Table[i].first, Table[i].second);
2645 Inst = SI;
2646 return false;
2647}
2648
2649/// ParseInvoke
2650/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2651/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2652bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2653 LocTy CallLoc = Lex.getLoc();
2654 unsigned CC, RetAttrs, FnAttrs;
2655 PATypeHolder RetType(Type::VoidTy);
2656 LocTy RetTypeLoc;
2657 ValID CalleeID;
2658 SmallVector<ParamInfo, 16> ArgList;
2659
2660 Value *NormalBB, *UnwindBB;
2661 if (ParseOptionalCallingConv(CC) ||
2662 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002663 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002664 ParseValID(CalleeID) ||
2665 ParseParameterList(ArgList, PFS) ||
2666 ParseOptionalAttrs(FnAttrs, 2) ||
2667 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2668 ParseTypeAndValue(NormalBB, PFS) ||
2669 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2670 ParseTypeAndValue(UnwindBB, PFS))
2671 return true;
2672
2673 if (!isa<BasicBlock>(NormalBB))
2674 return Error(CallLoc, "normal destination is not a basic block");
2675 if (!isa<BasicBlock>(UnwindBB))
2676 return Error(CallLoc, "unwind destination is not a basic block");
2677
2678 // If RetType is a non-function pointer type, then this is the short syntax
2679 // for the call, which means that RetType is just the return type. Infer the
2680 // rest of the function argument types from the arguments that are present.
2681 const PointerType *PFTy = 0;
2682 const FunctionType *Ty = 0;
2683 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2684 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2685 // Pull out the types of all of the arguments...
2686 std::vector<const Type*> ParamTypes;
2687 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2688 ParamTypes.push_back(ArgList[i].V->getType());
2689
2690 if (!FunctionType::isValidReturnType(RetType))
2691 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2692
2693 Ty = FunctionType::get(RetType, ParamTypes, false);
2694 PFTy = PointerType::getUnqual(Ty);
2695 }
2696
2697 // Look up the callee.
2698 Value *Callee;
2699 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2700
2701 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2702 // function attributes.
2703 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2704 if (FnAttrs & ObsoleteFuncAttrs) {
2705 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2706 FnAttrs &= ~ObsoleteFuncAttrs;
2707 }
2708
2709 // Set up the Attributes for the function.
2710 SmallVector<AttributeWithIndex, 8> Attrs;
2711 if (RetAttrs != Attribute::None)
2712 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2713
2714 SmallVector<Value*, 8> Args;
2715
2716 // Loop through FunctionType's arguments and ensure they are specified
2717 // correctly. Also, gather any parameter attributes.
2718 FunctionType::param_iterator I = Ty->param_begin();
2719 FunctionType::param_iterator E = Ty->param_end();
2720 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2721 const Type *ExpectedTy = 0;
2722 if (I != E) {
2723 ExpectedTy = *I++;
2724 } else if (!Ty->isVarArg()) {
2725 return Error(ArgList[i].Loc, "too many arguments specified");
2726 }
2727
2728 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2729 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2730 ExpectedTy->getDescription() + "'");
2731 Args.push_back(ArgList[i].V);
2732 if (ArgList[i].Attrs != Attribute::None)
2733 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2734 }
2735
2736 if (I != E)
2737 return Error(CallLoc, "not enough parameters specified for call");
2738
2739 if (FnAttrs != Attribute::None)
2740 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2741
2742 // Finish off the Attributes and check them
2743 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2744
2745 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2746 cast<BasicBlock>(UnwindBB),
2747 Args.begin(), Args.end());
2748 II->setCallingConv(CC);
2749 II->setAttributes(PAL);
2750 Inst = II;
2751 return false;
2752}
2753
2754
2755
2756//===----------------------------------------------------------------------===//
2757// Binary Operators.
2758//===----------------------------------------------------------------------===//
2759
2760/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002761/// ::= ArithmeticOps TypeAndValue ',' Value
2762///
2763/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2764/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002765bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002766 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 LocTy Loc; Value *LHS, *RHS;
2768 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2769 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2770 ParseValue(LHS->getType(), RHS, PFS))
2771 return true;
2772
Chris Lattnere914b592009-01-05 08:24:46 +00002773 bool Valid;
2774 switch (OperandType) {
2775 default: assert(0 && "Unknown operand type!");
2776 case 0: // int or FP.
2777 Valid = LHS->getType()->isIntOrIntVector() ||
2778 LHS->getType()->isFPOrFPVector();
2779 break;
2780 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2781 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2782 }
2783
2784 if (!Valid)
2785 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002786
2787 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2788 return false;
2789}
2790
2791/// ParseLogical
2792/// ::= ArithmeticOps TypeAndValue ',' Value {
2793bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2794 unsigned Opc) {
2795 LocTy Loc; Value *LHS, *RHS;
2796 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2797 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2798 ParseValue(LHS->getType(), RHS, PFS))
2799 return true;
2800
2801 if (!LHS->getType()->isIntOrIntVector())
2802 return Error(Loc,"instruction requires integer or integer vector operands");
2803
2804 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2805 return false;
2806}
2807
2808
2809/// ParseCompare
2810/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2811/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2812/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2813/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2814bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2815 unsigned Opc) {
2816 // Parse the integer/fp comparison predicate.
2817 LocTy Loc;
2818 unsigned Pred;
2819 Value *LHS, *RHS;
2820 if (ParseCmpPredicate(Pred, Opc) ||
2821 ParseTypeAndValue(LHS, Loc, PFS) ||
2822 ParseToken(lltok::comma, "expected ',' after compare value") ||
2823 ParseValue(LHS->getType(), RHS, PFS))
2824 return true;
2825
2826 if (Opc == Instruction::FCmp) {
2827 if (!LHS->getType()->isFPOrFPVector())
2828 return Error(Loc, "fcmp requires floating point operands");
2829 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2830 } else if (Opc == Instruction::ICmp) {
2831 if (!LHS->getType()->isIntOrIntVector() &&
2832 !isa<PointerType>(LHS->getType()))
2833 return Error(Loc, "icmp requires integer operands");
2834 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2835 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002836 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2837 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002838 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2839 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002840 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2841 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002842 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2843 }
2844 return false;
2845}
2846
2847//===----------------------------------------------------------------------===//
2848// Other Instructions.
2849//===----------------------------------------------------------------------===//
2850
2851
2852/// ParseCast
2853/// ::= CastOpc TypeAndValue 'to' Type
2854bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2855 unsigned Opc) {
2856 LocTy Loc; Value *Op;
2857 PATypeHolder DestTy(Type::VoidTy);
2858 if (ParseTypeAndValue(Op, Loc, PFS) ||
2859 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2860 ParseType(DestTy))
2861 return true;
2862
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002863 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2864 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 return Error(Loc, "invalid cast opcode for cast from '" +
2866 Op->getType()->getDescription() + "' to '" +
2867 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002868 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2870 return false;
2871}
2872
2873/// ParseSelect
2874/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2875bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2876 LocTy Loc;
2877 Value *Op0, *Op1, *Op2;
2878 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2879 ParseToken(lltok::comma, "expected ',' after select condition") ||
2880 ParseTypeAndValue(Op1, PFS) ||
2881 ParseToken(lltok::comma, "expected ',' after select value") ||
2882 ParseTypeAndValue(Op2, PFS))
2883 return true;
2884
2885 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2886 return Error(Loc, Reason);
2887
2888 Inst = SelectInst::Create(Op0, Op1, Op2);
2889 return false;
2890}
2891
Chris Lattner0088a5c2009-01-05 08:18:44 +00002892/// ParseVA_Arg
2893/// ::= 'va_arg' TypeAndValue ',' Type
2894bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 Value *Op;
2896 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002897 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002898 if (ParseTypeAndValue(Op, PFS) ||
2899 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002900 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002901 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002902
2903 if (!EltTy->isFirstClassType())
2904 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002905
2906 Inst = new VAArgInst(Op, EltTy);
2907 return false;
2908}
2909
2910/// ParseExtractElement
2911/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2912bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2913 LocTy Loc;
2914 Value *Op0, *Op1;
2915 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2916 ParseToken(lltok::comma, "expected ',' after extract value") ||
2917 ParseTypeAndValue(Op1, PFS))
2918 return true;
2919
2920 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2921 return Error(Loc, "invalid extractelement operands");
2922
2923 Inst = new ExtractElementInst(Op0, Op1);
2924 return false;
2925}
2926
2927/// ParseInsertElement
2928/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2929bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2930 LocTy Loc;
2931 Value *Op0, *Op1, *Op2;
2932 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2934 ParseTypeAndValue(Op1, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2936 ParseTypeAndValue(Op2, PFS))
2937 return true;
2938
2939 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2940 return Error(Loc, "invalid extractelement operands");
2941
2942 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2943 return false;
2944}
2945
2946/// ParseShuffleVector
2947/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2948bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2949 LocTy Loc;
2950 Value *Op0, *Op1, *Op2;
2951 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2952 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2953 ParseTypeAndValue(Op1, PFS) ||
2954 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2955 ParseTypeAndValue(Op2, PFS))
2956 return true;
2957
2958 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2959 return Error(Loc, "invalid extractelement operands");
2960
2961 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2962 return false;
2963}
2964
2965/// ParsePHI
2966/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2967bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2968 PATypeHolder Ty(Type::VoidTy);
2969 Value *Op0, *Op1;
2970 LocTy TypeLoc = Lex.getLoc();
2971
2972 if (ParseType(Ty) ||
2973 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2974 ParseValue(Ty, Op0, PFS) ||
2975 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2976 ParseValue(Type::LabelTy, Op1, PFS) ||
2977 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2978 return true;
2979
2980 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2981 while (1) {
2982 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2983
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002984 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 break;
2986
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002987 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002988 ParseValue(Ty, Op0, PFS) ||
2989 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2990 ParseValue(Type::LabelTy, Op1, PFS) ||
2991 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2992 return true;
2993 }
2994
2995 if (!Ty->isFirstClassType())
2996 return Error(TypeLoc, "phi node must have first class type");
2997
2998 PHINode *PN = PHINode::Create(Ty);
2999 PN->reserveOperandSpace(PHIVals.size());
3000 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3001 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3002 Inst = PN;
3003 return false;
3004}
3005
3006/// ParseCall
3007/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3008/// ParameterList OptionalAttrs
3009bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3010 bool isTail) {
3011 unsigned CC, RetAttrs, FnAttrs;
3012 PATypeHolder RetType(Type::VoidTy);
3013 LocTy RetTypeLoc;
3014 ValID CalleeID;
3015 SmallVector<ParamInfo, 16> ArgList;
3016 LocTy CallLoc = Lex.getLoc();
3017
3018 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3019 ParseOptionalCallingConv(CC) ||
3020 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003021 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003022 ParseValID(CalleeID) ||
3023 ParseParameterList(ArgList, PFS) ||
3024 ParseOptionalAttrs(FnAttrs, 2))
3025 return true;
3026
3027 // If RetType is a non-function pointer type, then this is the short syntax
3028 // for the call, which means that RetType is just the return type. Infer the
3029 // rest of the function argument types from the arguments that are present.
3030 const PointerType *PFTy = 0;
3031 const FunctionType *Ty = 0;
3032 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3033 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3034 // Pull out the types of all of the arguments...
3035 std::vector<const Type*> ParamTypes;
3036 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3037 ParamTypes.push_back(ArgList[i].V->getType());
3038
3039 if (!FunctionType::isValidReturnType(RetType))
3040 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3041
3042 Ty = FunctionType::get(RetType, ParamTypes, false);
3043 PFTy = PointerType::getUnqual(Ty);
3044 }
3045
3046 // Look up the callee.
3047 Value *Callee;
3048 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3049
Chris Lattnerdf986172009-01-02 07:01:27 +00003050 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3051 // function attributes.
3052 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3053 if (FnAttrs & ObsoleteFuncAttrs) {
3054 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3055 FnAttrs &= ~ObsoleteFuncAttrs;
3056 }
3057
3058 // Set up the Attributes for the function.
3059 SmallVector<AttributeWithIndex, 8> Attrs;
3060 if (RetAttrs != Attribute::None)
3061 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3062
3063 SmallVector<Value*, 8> Args;
3064
3065 // Loop through FunctionType's arguments and ensure they are specified
3066 // correctly. Also, gather any parameter attributes.
3067 FunctionType::param_iterator I = Ty->param_begin();
3068 FunctionType::param_iterator E = Ty->param_end();
3069 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3070 const Type *ExpectedTy = 0;
3071 if (I != E) {
3072 ExpectedTy = *I++;
3073 } else if (!Ty->isVarArg()) {
3074 return Error(ArgList[i].Loc, "too many arguments specified");
3075 }
3076
3077 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3078 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3079 ExpectedTy->getDescription() + "'");
3080 Args.push_back(ArgList[i].V);
3081 if (ArgList[i].Attrs != Attribute::None)
3082 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3083 }
3084
3085 if (I != E)
3086 return Error(CallLoc, "not enough parameters specified for call");
3087
3088 if (FnAttrs != Attribute::None)
3089 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3090
3091 // Finish off the Attributes and check them
3092 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3093
3094 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3095 CI->setTailCall(isTail);
3096 CI->setCallingConv(CC);
3097 CI->setAttributes(PAL);
3098 Inst = CI;
3099 return false;
3100}
3101
3102//===----------------------------------------------------------------------===//
3103// Memory Instructions.
3104//===----------------------------------------------------------------------===//
3105
3106/// ParseAlloc
3107/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3108/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3109bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3110 unsigned Opc) {
3111 PATypeHolder Ty(Type::VoidTy);
3112 Value *Size = 0;
3113 LocTy SizeLoc = 0;
3114 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003115 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003116
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003117 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 if (Lex.getKind() == lltok::kw_align) {
3119 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003120 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3121 ParseOptionalCommaAlignment(Alignment)) {
3122 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 }
3124 }
3125
3126 if (Size && Size->getType() != Type::Int32Ty)
3127 return Error(SizeLoc, "element count must be i32");
3128
3129 if (Opc == Instruction::Malloc)
3130 Inst = new MallocInst(Ty, Size, Alignment);
3131 else
3132 Inst = new AllocaInst(Ty, Size, Alignment);
3133 return false;
3134}
3135
3136/// ParseFree
3137/// ::= 'free' TypeAndValue
3138bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3139 Value *Val; LocTy Loc;
3140 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3141 if (!isa<PointerType>(Val->getType()))
3142 return Error(Loc, "operand to free must be a pointer");
3143 Inst = new FreeInst(Val);
3144 return false;
3145}
3146
3147/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003148/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003149bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3150 bool isVolatile) {
3151 Value *Val; LocTy Loc;
3152 unsigned Alignment;
3153 if (ParseTypeAndValue(Val, Loc, PFS) ||
3154 ParseOptionalCommaAlignment(Alignment))
3155 return true;
3156
3157 if (!isa<PointerType>(Val->getType()) ||
3158 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3159 return Error(Loc, "load operand must be a pointer to a first class type");
3160
3161 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3162 return false;
3163}
3164
3165/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003166/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003167bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3168 bool isVolatile) {
3169 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3170 unsigned Alignment;
3171 if (ParseTypeAndValue(Val, Loc, PFS) ||
3172 ParseToken(lltok::comma, "expected ',' after store operand") ||
3173 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3174 ParseOptionalCommaAlignment(Alignment))
3175 return true;
3176
3177 if (!isa<PointerType>(Ptr->getType()))
3178 return Error(PtrLoc, "store operand must be a pointer");
3179 if (!Val->getType()->isFirstClassType())
3180 return Error(Loc, "store operand must be a first class value");
3181 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3182 return Error(Loc, "stored value and pointer type do not match");
3183
3184 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3185 return false;
3186}
3187
3188/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003189/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003190/// FIXME: Remove support for getresult in LLVM 3.0
3191bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3192 Value *Val; LocTy ValLoc, EltLoc;
3193 unsigned Element;
3194 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3195 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003196 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 return true;
3198
3199 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3200 return Error(ValLoc, "getresult inst requires an aggregate operand");
3201 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3202 return Error(EltLoc, "invalid getresult index for value");
3203 Inst = ExtractValueInst::Create(Val, Element);
3204 return false;
3205}
3206
3207/// ParseGetElementPtr
3208/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3209bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3210 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003211 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003212
3213 if (!isa<PointerType>(Ptr->getType()))
3214 return Error(Loc, "base of getelementptr must be a pointer");
3215
3216 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003217 while (EatIfPresent(lltok::comma)) {
3218 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 if (!isa<IntegerType>(Val->getType()))
3220 return Error(EltLoc, "getelementptr index must be an integer");
3221 Indices.push_back(Val);
3222 }
3223
3224 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3225 Indices.begin(), Indices.end()))
3226 return Error(Loc, "invalid getelementptr indices");
3227 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3228 return false;
3229}
3230
3231/// ParseExtractValue
3232/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3233bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3234 Value *Val; LocTy Loc;
3235 SmallVector<unsigned, 4> Indices;
3236 if (ParseTypeAndValue(Val, Loc, PFS) ||
3237 ParseIndexList(Indices))
3238 return true;
3239
3240 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3241 return Error(Loc, "extractvalue operand must be array or struct");
3242
3243 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3244 Indices.end()))
3245 return Error(Loc, "invalid indices for extractvalue");
3246 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3247 return false;
3248}
3249
3250/// ParseInsertValue
3251/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3252bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3253 Value *Val0, *Val1; LocTy Loc0, Loc1;
3254 SmallVector<unsigned, 4> Indices;
3255 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3256 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3257 ParseTypeAndValue(Val1, Loc1, PFS) ||
3258 ParseIndexList(Indices))
3259 return true;
3260
3261 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3262 return Error(Loc0, "extractvalue operand must be array or struct");
3263
3264 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3265 Indices.end()))
3266 return Error(Loc0, "invalid indices for insertvalue");
3267 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3268 return false;
3269}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003270
3271//===----------------------------------------------------------------------===//
3272// Embedded metadata.
3273//===----------------------------------------------------------------------===//
3274
3275/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003276/// ::= Element (',' Element)*
3277/// Element
3278/// ::= 'null' | TypeAndValue
3279bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003280 assert(Lex.getKind() == lltok::lbrace);
3281 Lex.Lex();
3282 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003283 Value *V;
3284 if (Lex.getKind() == lltok::kw_null) {
3285 Lex.Lex();
3286 V = 0;
3287 } else {
3288 Constant *C;
3289 if (ParseGlobalTypeAndValue(C)) return true;
3290 V = C;
3291 }
3292 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003293 } while (EatIfPresent(lltok::comma));
3294
3295 return false;
3296}