blob: 401dc39ca539c977d2abeca0c046c43f8cb23ef8 [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"
21#include "llvm/Module.h"
22#include "llvm/ValueSymbolTable.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
Chris Lattnerdf986172009-01-02 07:01:27 +000028namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000033 struct ValID {
34 enum {
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000039 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000040 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
42 } Kind;
43
44 LLParser::LocTy Loc;
45 unsigned UIntVal;
46 std::string StrVal, StrVal2;
47 APSInt APSIntVal;
48 APFloat APFloatVal;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
51 };
52}
53
Chris Lattner3ed88ef2009-01-02 08:05:26 +000054/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000055bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000056 // Prime the lexer.
57 Lex.Lex();
58
Chris Lattnerad7d1e22009-01-04 20:44:11 +000059 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000061}
62
63/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64/// module.
65bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
74
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
78 "'");
79
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
84
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
88
89 return false;
90}
91
92//===----------------------------------------------------------------------===//
93// Top-Level Entities
94//===----------------------------------------------------------------------===//
95
96bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000097 while (1) {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
111
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000116 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
119 case lltok::kw_linkonce: // OptionalLinkage
120 case lltok::kw_appending: // OptionalLinkage
121 case lltok::kw_dllexport: // OptionalLinkage
122 case lltok::kw_common: // OptionalLinkage
123 case lltok::kw_dllimport: // OptionalLinkage
124 case lltok::kw_extern_weak: // OptionalLinkage
125 case lltok::kw_external: { // OptionalLinkage
126 unsigned Linkage, Visibility;
127 if (ParseOptionalLinkage(Linkage) ||
128 ParseOptionalVisibility(Visibility) ||
129 ParseGlobal("", 0, Linkage, true, Visibility))
130 return true;
131 break;
132 }
133 case lltok::kw_default: // OptionalVisibility
134 case lltok::kw_hidden: // OptionalVisibility
135 case lltok::kw_protected: { // OptionalVisibility
136 unsigned Visibility;
137 if (ParseOptionalVisibility(Visibility) ||
138 ParseGlobal("", 0, 0, false, Visibility))
139 return true;
140 break;
141 }
142
143 case lltok::kw_thread_local: // OptionalThreadLocal
144 case lltok::kw_addrspace: // OptionalAddrSpace
145 case lltok::kw_constant: // GlobalType
146 case lltok::kw_global: // GlobalType
147 if (ParseGlobal("", 0, 0, false, 0)) return true;
148 break;
149 }
150 }
151}
152
153
154/// toplevelentity
155/// ::= 'module' 'asm' STRINGCONSTANT
156bool LLParser::ParseModuleAsm() {
157 assert(Lex.getKind() == lltok::kw_module);
158 Lex.Lex();
159
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000160 std::string AsmStr;
161 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
162 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000163
164 const std::string &AsmSoFar = M->getModuleInlineAsm();
165 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000166 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000168 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 return false;
170}
171
172/// toplevelentity
173/// ::= 'target' 'triple' '=' STRINGCONSTANT
174/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
175bool LLParser::ParseTargetDefinition() {
176 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000177 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000178 switch (Lex.Lex()) {
179 default: return TokError("unknown target property");
180 case lltok::kw_triple:
181 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
183 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000184 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 return false;
187 case lltok::kw_datalayout:
188 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000189 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
190 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000192 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000193 return false;
194 }
195}
196
197/// toplevelentity
198/// ::= 'deplibs' '=' '[' ']'
199/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
200bool LLParser::ParseDepLibs() {
201 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000203 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
204 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
205 return true;
206
207 if (EatIfPresent(lltok::rsquare))
208 return false;
209
210 std::string Str;
211 if (ParseStringConstant(Str)) return true;
212 M->addLibrary(Str);
213
214 while (EatIfPresent(lltok::comma)) {
215 if (ParseStringConstant(Str)) return true;
216 M->addLibrary(Str);
217 }
218
219 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000220}
221
222/// toplevelentity
223/// ::= 'type' type
224bool LLParser::ParseUnnamedType() {
225 assert(Lex.getKind() == lltok::kw_type);
226 LocTy TypeLoc = Lex.getLoc();
227 Lex.Lex(); // eat kw_type
228
229 PATypeHolder Ty(Type::VoidTy);
230 if (ParseType(Ty)) return true;
231
232 unsigned TypeID = NumberedTypes.size();
233
234 // We don't allow assigning names to void type
235 if (Ty == Type::VoidTy)
236 return Error(TypeLoc, "can't assign name to the void type");
237
238 // See if this type was previously referenced.
239 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
240 FI = ForwardRefTypeIDs.find(TypeID);
241 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000242 if (FI->second.first.get() == Ty)
243 return Error(TypeLoc, "self referential type is invalid");
244
Chris Lattnerdf986172009-01-02 07:01:27 +0000245 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
246 Ty = FI->second.first.get();
247 ForwardRefTypeIDs.erase(FI);
248 }
249
250 NumberedTypes.push_back(Ty);
251
252 return false;
253}
254
255/// toplevelentity
256/// ::= LocalVar '=' 'type' type
257bool LLParser::ParseNamedType() {
258 std::string Name = Lex.getStrVal();
259 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000260 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000261
262 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263
264 if (ParseToken(lltok::equal, "expected '=' after name") ||
265 ParseToken(lltok::kw_type, "expected 'type' after name") ||
266 ParseType(Ty))
267 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000268
269 // We don't allow assigning names to void type
270 if (Ty == Type::VoidTy)
271 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
272
273 // Set the type name, checking for conflicts as we do so.
274 bool AlreadyExists = M->addTypeName(Name, Ty);
275 if (!AlreadyExists) return false;
276
277 // See if this type is a forward reference. We need to eagerly resolve
278 // types to allow recursive type redefinitions below.
279 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
280 FI = ForwardRefTypes.find(Name);
281 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000282 if (FI->second.first.get() == Ty)
283 return Error(NameLoc, "self referential type is invalid");
284
Chris Lattnerdf986172009-01-02 07:01:27 +0000285 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
286 Ty = FI->second.first.get();
287 ForwardRefTypes.erase(FI);
288 }
289
290 // Inserting a name that is already defined, get the existing name.
291 const Type *Existing = M->getTypeByName(Name);
292 assert(Existing && "Conflict but no matching type?!");
293
294 // Otherwise, this is an attempt to redefine a type. That's okay if
295 // the redefinition is identical to the original.
296 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
297 if (Existing == Ty) return false;
298
299 // Any other kind of (non-equivalent) redefinition is an error.
300 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
301 Ty->getDescription() + "'");
302}
303
304
305/// toplevelentity
306/// ::= 'declare' FunctionHeader
307bool LLParser::ParseDeclare() {
308 assert(Lex.getKind() == lltok::kw_declare);
309 Lex.Lex();
310
311 Function *F;
312 return ParseFunctionHeader(F, false);
313}
314
315/// toplevelentity
316/// ::= 'define' FunctionHeader '{' ...
317bool LLParser::ParseDefine() {
318 assert(Lex.getKind() == lltok::kw_define);
319 Lex.Lex();
320
321 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000322 return ParseFunctionHeader(F, true) ||
323 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000324}
325
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000326/// ParseGlobalType
327/// ::= 'constant'
328/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000329bool LLParser::ParseGlobalType(bool &IsConstant) {
330 if (Lex.getKind() == lltok::kw_constant)
331 IsConstant = true;
332 else if (Lex.getKind() == lltok::kw_global)
333 IsConstant = false;
334 else
335 return TokError("expected 'global' or 'constant'");
336 Lex.Lex();
337 return false;
338}
339
340/// ParseNamedGlobal:
341/// GlobalVar '=' OptionalVisibility ALIAS ...
342/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
343bool LLParser::ParseNamedGlobal() {
344 assert(Lex.getKind() == lltok::GlobalVar);
345 LocTy NameLoc = Lex.getLoc();
346 std::string Name = Lex.getStrVal();
347 Lex.Lex();
348
349 bool HasLinkage;
350 unsigned Linkage, Visibility;
351 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
352 ParseOptionalLinkage(Linkage, HasLinkage) ||
353 ParseOptionalVisibility(Visibility))
354 return true;
355
356 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
357 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
358 return ParseAlias(Name, NameLoc, Visibility);
359}
360
361/// ParseAlias:
362/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
363/// Aliasee
364/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
365///
366/// Everything through visibility has already been parsed.
367///
368bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
369 unsigned Visibility) {
370 assert(Lex.getKind() == lltok::kw_alias);
371 Lex.Lex();
372 unsigned Linkage;
373 LocTy LinkageLoc = Lex.getLoc();
374 if (ParseOptionalLinkage(Linkage))
375 return true;
376
377 if (Linkage != GlobalValue::ExternalLinkage &&
378 Linkage != GlobalValue::WeakLinkage &&
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();
385 if (Lex.getKind() != lltok::kw_bitcast) {
386 if (ParseGlobalTypeAndValue(Aliasee)) return true;
387 } else {
388 // The bitcast dest type is not present, it is implied by the dest type.
389 ValID ID;
390 if (ParseValID(ID)) return true;
391 if (ID.Kind != ValID::t_Constant)
392 return Error(AliaseeLoc, "invalid aliasee");
393 Aliasee = ID.ConstantVal;
394 }
395
396 if (!isa<PointerType>(Aliasee->getType()))
397 return Error(AliaseeLoc, "alias must have pointer type");
398
399 // Okay, create the alias but do not insert it into the module yet.
400 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
401 (GlobalValue::LinkageTypes)Linkage, Name,
402 Aliasee);
403 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
404
405 // See if this value already exists in the symbol table. If so, it is either
406 // a redefinition or a definition of a forward reference.
407 if (GlobalValue *Val =
408 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
409 // See if this was a redefinition. If so, there is no entry in
410 // ForwardRefVals.
411 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
412 I = ForwardRefVals.find(Name);
413 if (I == ForwardRefVals.end())
414 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
415
416 // Otherwise, this was a definition of forward ref. Verify that types
417 // agree.
418 if (Val->getType() != GA->getType())
419 return Error(NameLoc,
420 "forward reference and definition of alias have different types");
421
422 // If they agree, just RAUW the old value with the alias and remove the
423 // forward ref info.
424 Val->replaceAllUsesWith(GA);
425 Val->eraseFromParent();
426 ForwardRefVals.erase(I);
427 }
428
429 // Insert into the module, we know its name won't collide now.
430 M->getAliasList().push_back(GA);
431 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
432
433 return false;
434}
435
436/// ParseGlobal
437/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
438/// OptionalAddrSpace GlobalType Type Const
439/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
440/// OptionalAddrSpace GlobalType Type Const
441///
442/// Everything through visibility has been parsed already.
443///
444bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
445 unsigned Linkage, bool HasLinkage,
446 unsigned Visibility) {
447 unsigned AddrSpace;
448 bool ThreadLocal, IsConstant;
449 LocTy TyLoc;
450
451 PATypeHolder Ty(Type::VoidTy);
452 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
453 ParseOptionalAddrSpace(AddrSpace) ||
454 ParseGlobalType(IsConstant) ||
455 ParseType(Ty, TyLoc))
456 return true;
457
458 // If the linkage is specified and is external, then no initializer is
459 // present.
460 Constant *Init = 0;
461 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
462 Linkage != GlobalValue::ExternalWeakLinkage &&
463 Linkage != GlobalValue::ExternalLinkage)) {
464 if (ParseGlobalValue(Ty, Init))
465 return true;
466 }
467
468 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
469 return Error(TyLoc, "invald type for global variable");
470
471 GlobalVariable *GV = 0;
472
473 // See if the global was forward referenced, if so, use the global.
474 if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
475 if (!ForwardRefVals.erase(Name))
476 return Error(NameLoc, "redefinition of global '@" + Name + "'");
477 } else {
478 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
479 I = ForwardRefValIDs.find(NumberedVals.size());
480 if (I != ForwardRefValIDs.end()) {
481 GV = cast<GlobalVariable>(I->second.first);
482 ForwardRefValIDs.erase(I);
483 }
484 }
485
486 if (GV == 0) {
487 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
488 M, false, AddrSpace);
489 } else {
490 if (GV->getType()->getElementType() != Ty)
491 return Error(TyLoc,
492 "forward reference and definition of global have different types");
493
494 // Move the forward-reference to the correct spot in the module.
495 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
496 }
497
498 if (Name.empty())
499 NumberedVals.push_back(GV);
500
501 // Set the parsed properties on the global.
502 if (Init)
503 GV->setInitializer(Init);
504 GV->setConstant(IsConstant);
505 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
506 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
507 GV->setThreadLocal(ThreadLocal);
508
509 // Parse attributes on the global.
510 while (Lex.getKind() == lltok::comma) {
511 Lex.Lex();
512
513 if (Lex.getKind() == lltok::kw_section) {
514 Lex.Lex();
515 GV->setSection(Lex.getStrVal());
516 if (ParseToken(lltok::StringConstant, "expected global section string"))
517 return true;
518 } else if (Lex.getKind() == lltok::kw_align) {
519 unsigned Alignment;
520 if (ParseOptionalAlignment(Alignment)) return true;
521 GV->setAlignment(Alignment);
522 } else {
523 TokError("unknown global variable property!");
524 }
525 }
526
527 return false;
528}
529
530
531//===----------------------------------------------------------------------===//
532// GlobalValue Reference/Resolution Routines.
533//===----------------------------------------------------------------------===//
534
535/// GetGlobalVal - Get a value with the specified name or ID, creating a
536/// forward reference record if needed. This can return null if the value
537/// exists but does not have the right type.
538GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
539 LocTy Loc) {
540 const PointerType *PTy = dyn_cast<PointerType>(Ty);
541 if (PTy == 0) {
542 Error(Loc, "global variable reference must have pointer type");
543 return 0;
544 }
545
546 // Look this name up in the normal function symbol table.
547 GlobalValue *Val =
548 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
549
550 // If this is a forward reference for the value, see if we already created a
551 // forward ref record.
552 if (Val == 0) {
553 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
554 I = ForwardRefVals.find(Name);
555 if (I != ForwardRefVals.end())
556 Val = I->second.first;
557 }
558
559 // If we have the value in the symbol table or fwd-ref table, return it.
560 if (Val) {
561 if (Val->getType() == Ty) return Val;
562 Error(Loc, "'@" + Name + "' defined with type '" +
563 Val->getType()->getDescription() + "'");
564 return 0;
565 }
566
567 // Otherwise, create a new forward reference for this value and remember it.
568 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000569 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
570 // Function types can return opaque but functions can't.
571 if (isa<OpaqueType>(FT->getReturnType())) {
572 Error(Loc, "function may not return opaque type");
573 return 0;
574 }
575
Chris Lattnerdf986172009-01-02 07:01:27 +0000576 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000577 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000578 FwdVal = new GlobalVariable(PTy->getElementType(), false,
579 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000580 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000581
582 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
583 return FwdVal;
584}
585
586GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
587 const PointerType *PTy = dyn_cast<PointerType>(Ty);
588 if (PTy == 0) {
589 Error(Loc, "global variable reference must have pointer type");
590 return 0;
591 }
592
593 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
594
595 // If this is a forward reference for the value, see if we already created a
596 // forward ref record.
597 if (Val == 0) {
598 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
599 I = ForwardRefValIDs.find(ID);
600 if (I != ForwardRefValIDs.end())
601 Val = I->second.first;
602 }
603
604 // If we have the value in the symbol table or fwd-ref table, return it.
605 if (Val) {
606 if (Val->getType() == Ty) return Val;
607 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
608 Val->getType()->getDescription() + "'");
609 return 0;
610 }
611
612 // Otherwise, create a new forward reference for this value and remember it.
613 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000614 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
615 // Function types can return opaque but functions can't.
616 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000617 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000618 return 0;
619 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000621 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000622 FwdVal = new GlobalVariable(PTy->getElementType(), false,
623 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000624 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000625
626 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
627 return FwdVal;
628}
629
630
631//===----------------------------------------------------------------------===//
632// Helper Routines.
633//===----------------------------------------------------------------------===//
634
635/// ParseToken - If the current token has the specified kind, eat it and return
636/// success. Otherwise, emit the specified error and return failure.
637bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
638 if (Lex.getKind() != T)
639 return TokError(ErrMsg);
640 Lex.Lex();
641 return false;
642}
643
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000644/// ParseStringConstant
645/// ::= StringConstant
646bool LLParser::ParseStringConstant(std::string &Result) {
647 if (Lex.getKind() != lltok::StringConstant)
648 return TokError("expected string constant");
649 Result = Lex.getStrVal();
650 Lex.Lex();
651 return false;
652}
653
654/// ParseUInt32
655/// ::= uint32
656bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
658 return TokError("expected integer");
659 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
660 if (Val64 != unsigned(Val64))
661 return TokError("expected 32-bit integer (too large)");
662 Val = Val64;
663 Lex.Lex();
664 return false;
665}
666
667
668/// ParseOptionalAddrSpace
669/// := /*empty*/
670/// := 'addrspace' '(' uint32 ')'
671bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
672 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000673 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000674 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000676 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 ParseToken(lltok::rparen, "expected ')' in address space");
678}
679
680/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
681/// indicates what kind of attribute list this is: 0: function arg, 1: result,
682/// 2: function attr.
683bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
684 Attrs = Attribute::None;
685 LocTy AttrLoc = Lex.getLoc();
686
687 while (1) {
688 switch (Lex.getKind()) {
689 case lltok::kw_sext:
690 case lltok::kw_zext:
691 // Treat these as signext/zeroext unless they are function attrs.
692 // FIXME: REMOVE THIS IN LLVM 3.0
693 if (AttrKind != 2) {
694 if (Lex.getKind() == lltok::kw_sext)
695 Attrs |= Attribute::SExt;
696 else
697 Attrs |= Attribute::ZExt;
698 break;
699 }
700 // FALL THROUGH.
701 default: // End of attributes.
702 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
703 return Error(AttrLoc, "invalid use of function-only attribute");
704
705 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
706 return Error(AttrLoc, "invalid use of parameter-only attribute");
707
708 return false;
709 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
710 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
711 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
712 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
713 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
714 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
715 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
716 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
717
718 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
719 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
720 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
721 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
722 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
723 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
724 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
725 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
726 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
727
728
729 case lltok::kw_align: {
730 unsigned Alignment;
731 if (ParseOptionalAlignment(Alignment))
732 return true;
733 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
734 continue;
735 }
736 }
737 Lex.Lex();
738 }
739}
740
741/// ParseOptionalLinkage
742/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000743/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000744/// ::= 'internal'
745/// ::= 'weak'
746/// ::= 'linkonce'
747/// ::= 'appending'
748/// ::= 'dllexport'
749/// ::= 'common'
750/// ::= 'dllimport'
751/// ::= 'extern_weak'
752/// ::= 'external'
753bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
754 HasLinkage = false;
755 switch (Lex.getKind()) {
756 default: Res = GlobalValue::ExternalLinkage; return false;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000757 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
759 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
760 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
761 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
762 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
763 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
764 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
765 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
766 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
767 }
768 Lex.Lex();
769 HasLinkage = true;
770 return false;
771}
772
773/// ParseOptionalVisibility
774/// ::= /*empty*/
775/// ::= 'default'
776/// ::= 'hidden'
777/// ::= 'protected'
778///
779bool LLParser::ParseOptionalVisibility(unsigned &Res) {
780 switch (Lex.getKind()) {
781 default: Res = GlobalValue::DefaultVisibility; return false;
782 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
783 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
784 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
785 }
786 Lex.Lex();
787 return false;
788}
789
790/// ParseOptionalCallingConv
791/// ::= /*empty*/
792/// ::= 'ccc'
793/// ::= 'fastcc'
794/// ::= 'coldcc'
795/// ::= 'x86_stdcallcc'
796/// ::= 'x86_fastcallcc'
797/// ::= 'cc' UINT
798///
799bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
800 switch (Lex.getKind()) {
801 default: CC = CallingConv::C; return false;
802 case lltok::kw_ccc: CC = CallingConv::C; break;
803 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
804 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
805 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
806 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000807 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 }
809 Lex.Lex();
810 return false;
811}
812
813/// ParseOptionalAlignment
814/// ::= /* empty */
815/// ::= 'align' 4
816bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
817 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000818 if (!EatIfPresent(lltok::kw_align))
819 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000820 LocTy AlignLoc = Lex.getLoc();
821 if (ParseUInt32(Alignment)) return true;
822 if (!isPowerOf2_32(Alignment))
823 return Error(AlignLoc, "alignment is not a power of two");
824 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000825}
826
827/// ParseOptionalCommaAlignment
828/// ::= /* empty */
829/// ::= ',' 'align' 4
830bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
831 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000832 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000833 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000834 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000835 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000836}
837
838/// ParseIndexList
839/// ::= (',' uint32)+
840bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
841 if (Lex.getKind() != lltok::comma)
842 return TokError("expected ',' as start of index list");
843
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000844 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000845 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000846 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000847 Indices.push_back(Idx);
848 }
849
850 return false;
851}
852
853//===----------------------------------------------------------------------===//
854// Type Parsing.
855//===----------------------------------------------------------------------===//
856
857/// ParseType - Parse and resolve a full type.
858bool LLParser::ParseType(PATypeHolder &Result) {
859 if (ParseTypeRec(Result)) return true;
860
861 // Verify no unresolved uprefs.
862 if (!UpRefs.empty())
863 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000864
865 return false;
866}
867
868/// HandleUpRefs - Every time we finish a new layer of types, this function is
869/// called. It loops through the UpRefs vector, which is a list of the
870/// currently active types. For each type, if the up-reference is contained in
871/// the newly completed type, we decrement the level count. When the level
872/// count reaches zero, the up-referenced type is the type that is passed in:
873/// thus we can complete the cycle.
874///
875PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
876 // If Ty isn't abstract, or if there are no up-references in it, then there is
877 // nothing to resolve here.
878 if (!ty->isAbstract() || UpRefs.empty()) return ty;
879
880 PATypeHolder Ty(ty);
881#if 0
882 errs() << "Type '" << Ty->getDescription()
883 << "' newly formed. Resolving upreferences.\n"
884 << UpRefs.size() << " upreferences active!\n";
885#endif
886
887 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
888 // to zero), we resolve them all together before we resolve them to Ty. At
889 // the end of the loop, if there is anything to resolve to Ty, it will be in
890 // this variable.
891 OpaqueType *TypeToResolve = 0;
892
893 for (unsigned i = 0; i != UpRefs.size(); ++i) {
894 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
895 bool ContainsType =
896 std::find(Ty->subtype_begin(), Ty->subtype_end(),
897 UpRefs[i].LastContainedTy) != Ty->subtype_end();
898
899#if 0
900 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
901 << UpRefs[i].LastContainedTy->getDescription() << ") = "
902 << (ContainsType ? "true" : "false")
903 << " level=" << UpRefs[i].NestingLevel << "\n";
904#endif
905 if (!ContainsType)
906 continue;
907
908 // Decrement level of upreference
909 unsigned Level = --UpRefs[i].NestingLevel;
910 UpRefs[i].LastContainedTy = Ty;
911
912 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
913 if (Level != 0)
914 continue;
915
916#if 0
917 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
918#endif
919 if (!TypeToResolve)
920 TypeToResolve = UpRefs[i].UpRefTy;
921 else
922 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
923 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
924 --i; // Do not skip the next element.
925 }
926
927 if (TypeToResolve)
928 TypeToResolve->refineAbstractTypeTo(Ty);
929
930 return Ty;
931}
932
933
934/// ParseTypeRec - The recursive function used to process the internal
935/// implementation details of types.
936bool LLParser::ParseTypeRec(PATypeHolder &Result) {
937 switch (Lex.getKind()) {
938 default:
939 return TokError("expected type");
940 case lltok::Type:
941 // TypeRec ::= 'float' | 'void' (etc)
942 Result = Lex.getTyVal();
943 Lex.Lex();
944 break;
945 case lltok::kw_opaque:
946 // TypeRec ::= 'opaque'
947 Result = OpaqueType::get();
948 Lex.Lex();
949 break;
950 case lltok::lbrace:
951 // TypeRec ::= '{' ... '}'
952 if (ParseStructType(Result, false))
953 return true;
954 break;
955 case lltok::lsquare:
956 // TypeRec ::= '[' ... ']'
957 Lex.Lex(); // eat the lsquare.
958 if (ParseArrayVectorType(Result, false))
959 return true;
960 break;
961 case lltok::less: // Either vector or packed struct.
962 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000963 Lex.Lex();
964 if (Lex.getKind() == lltok::lbrace) {
965 if (ParseStructType(Result, true) ||
966 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000967 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 } else if (ParseArrayVectorType(Result, true))
969 return true;
970 break;
971 case lltok::LocalVar:
972 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
973 // TypeRec ::= %foo
974 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
975 Result = T;
976 } else {
977 Result = OpaqueType::get();
978 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
979 std::make_pair(Result,
980 Lex.getLoc())));
981 M->addTypeName(Lex.getStrVal(), Result.get());
982 }
983 Lex.Lex();
984 break;
985
986 case lltok::LocalVarID:
987 // TypeRec ::= %4
988 if (Lex.getUIntVal() < NumberedTypes.size())
989 Result = NumberedTypes[Lex.getUIntVal()];
990 else {
991 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
992 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
993 if (I != ForwardRefTypeIDs.end())
994 Result = I->second.first;
995 else {
996 Result = OpaqueType::get();
997 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
998 std::make_pair(Result,
999 Lex.getLoc())));
1000 }
1001 }
1002 Lex.Lex();
1003 break;
1004 case lltok::backslash: {
1005 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001006 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001007 unsigned Val;
1008 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001009 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1010 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1011 Result = OT;
1012 break;
1013 }
1014 }
1015
1016 // Parse the type suffixes.
1017 while (1) {
1018 switch (Lex.getKind()) {
1019 // End of type.
1020 default: return false;
1021
1022 // TypeRec ::= TypeRec '*'
1023 case lltok::star:
1024 if (Result.get() == Type::LabelTy)
1025 return TokError("basic block pointers are invalid");
1026 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1027 Lex.Lex();
1028 break;
1029
1030 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1031 case lltok::kw_addrspace: {
1032 if (Result.get() == Type::LabelTy)
1033 return TokError("basic block pointers are invalid");
1034 unsigned AddrSpace;
1035 if (ParseOptionalAddrSpace(AddrSpace) ||
1036 ParseToken(lltok::star, "expected '*' in address space"))
1037 return true;
1038
1039 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1040 break;
1041 }
1042
1043 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1044 case lltok::lparen:
1045 if (ParseFunctionType(Result))
1046 return true;
1047 break;
1048 }
1049 }
1050}
1051
1052/// ParseParameterList
1053/// ::= '(' ')'
1054/// ::= '(' Arg (',' Arg)* ')'
1055/// Arg
1056/// ::= Type OptionalAttributes Value OptionalAttributes
1057bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1058 PerFunctionState &PFS) {
1059 if (ParseToken(lltok::lparen, "expected '(' in call"))
1060 return true;
1061
1062 while (Lex.getKind() != lltok::rparen) {
1063 // If this isn't the first argument, we need a comma.
1064 if (!ArgList.empty() &&
1065 ParseToken(lltok::comma, "expected ',' in argument list"))
1066 return true;
1067
1068 // Parse the argument.
1069 LocTy ArgLoc;
1070 PATypeHolder ArgTy(Type::VoidTy);
1071 unsigned ArgAttrs1, ArgAttrs2;
1072 Value *V;
1073 if (ParseType(ArgTy, ArgLoc) ||
1074 ParseOptionalAttrs(ArgAttrs1, 0) ||
1075 ParseValue(ArgTy, V, PFS) ||
1076 // FIXME: Should not allow attributes after the argument, remove this in
1077 // LLVM 3.0.
1078 ParseOptionalAttrs(ArgAttrs2, 0))
1079 return true;
1080 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1081 }
1082
1083 Lex.Lex(); // Lex the ')'.
1084 return false;
1085}
1086
1087
1088
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001089/// ParseArgumentList - Parse the argument list for a function type or function
1090/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001091/// ::= '(' ArgTypeListI ')'
1092/// ArgTypeListI
1093/// ::= /*empty*/
1094/// ::= '...'
1095/// ::= ArgTypeList ',' '...'
1096/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001097///
Chris Lattnerdf986172009-01-02 07:01:27 +00001098bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001099 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001100 isVarArg = false;
1101 assert(Lex.getKind() == lltok::lparen);
1102 Lex.Lex(); // eat the (.
1103
1104 if (Lex.getKind() == lltok::rparen) {
1105 // empty
1106 } else if (Lex.getKind() == lltok::dotdotdot) {
1107 isVarArg = true;
1108 Lex.Lex();
1109 } else {
1110 LocTy TypeLoc = Lex.getLoc();
1111 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001113 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001114
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001115 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1116 // types (such as a function returning a pointer to itself). If parsing a
1117 // function prototype, we require fully resolved types.
1118 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001119 ParseOptionalAttrs(Attrs, 0)) return true;
1120
Chris Lattnerdf986172009-01-02 07:01:27 +00001121 if (Lex.getKind() == lltok::LocalVar ||
1122 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1123 Name = Lex.getStrVal();
1124 Lex.Lex();
1125 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001126
1127 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1128 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001129
1130 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1131
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001132 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001133 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001134 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001135 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001136 break;
1137 }
1138
1139 // Otherwise must be an argument type.
1140 TypeLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001141 if (ParseTypeRec(ArgTy) ||
1142 ParseOptionalAttrs(Attrs, 0)) return true;
1143
Chris Lattnerdf986172009-01-02 07:01:27 +00001144 if (Lex.getKind() == lltok::LocalVar ||
1145 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1146 Name = Lex.getStrVal();
1147 Lex.Lex();
1148 } else {
1149 Name = "";
1150 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001151
1152 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1153 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001154
1155 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1156 }
1157 }
1158
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001159 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001160}
1161
1162/// ParseFunctionType
1163/// ::= Type ArgumentList OptionalAttrs
1164bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1165 assert(Lex.getKind() == lltok::lparen);
1166
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001167 if (!FunctionType::isValidReturnType(Result))
1168 return TokError("invalid function return type");
1169
Chris Lattnerdf986172009-01-02 07:01:27 +00001170 std::vector<ArgInfo> ArgList;
1171 bool isVarArg;
1172 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001173 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 // FIXME: Allow, but ignore attributes on function types!
1175 // FIXME: Remove in LLVM 3.0
1176 ParseOptionalAttrs(Attrs, 2))
1177 return true;
1178
1179 // Reject names on the arguments lists.
1180 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1181 if (!ArgList[i].Name.empty())
1182 return Error(ArgList[i].Loc, "argument name invalid in function type");
1183 if (!ArgList[i].Attrs != 0) {
1184 // Allow but ignore attributes on function types; this permits
1185 // auto-upgrade.
1186 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1187 }
1188 }
1189
1190 std::vector<const Type*> ArgListTy;
1191 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1192 ArgListTy.push_back(ArgList[i].Type);
1193
1194 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1195 return false;
1196}
1197
1198/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1199/// TypeRec
1200/// ::= '{' '}'
1201/// ::= '{' TypeRec (',' TypeRec)* '}'
1202/// ::= '<' '{' '}' '>'
1203/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1204bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1205 assert(Lex.getKind() == lltok::lbrace);
1206 Lex.Lex(); // Consume the '{'
1207
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001208 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001209 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001210 return false;
1211 }
1212
1213 std::vector<PATypeHolder> ParamsList;
1214 if (ParseTypeRec(Result)) return true;
1215 ParamsList.push_back(Result);
1216
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001217 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 if (ParseTypeRec(Result)) return true;
1219 ParamsList.push_back(Result);
1220 }
1221
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001222 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1223 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001224
1225 std::vector<const Type*> ParamsListTy;
1226 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1227 ParamsListTy.push_back(ParamsList[i].get());
1228 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1229 return false;
1230}
1231
1232/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1233/// token has already been consumed.
1234/// TypeRec
1235/// ::= '[' APSINTVAL 'x' Types ']'
1236/// ::= '<' APSINTVAL 'x' Types '>'
1237bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1238 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1239 Lex.getAPSIntVal().getBitWidth() > 64)
1240 return TokError("expected number in address space");
1241
1242 LocTy SizeLoc = Lex.getLoc();
1243 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001244 Lex.Lex();
1245
1246 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1247 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001248
1249 LocTy TypeLoc = Lex.getLoc();
1250 PATypeHolder EltTy(Type::VoidTy);
1251 if (ParseTypeRec(EltTy)) return true;
1252
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001253 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1254 "expected end of sequential type"))
1255 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001256
1257 if (isVector) {
1258 if ((unsigned)Size != Size)
1259 return Error(SizeLoc, "size too large for vector");
1260 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1261 return Error(TypeLoc, "vector element type must be fp or integer");
1262 Result = VectorType::get(EltTy, unsigned(Size));
1263 } else {
1264 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1265 return Error(TypeLoc, "invalid array element type");
1266 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1267 }
1268 return false;
1269}
1270
1271//===----------------------------------------------------------------------===//
1272// Function Semantic Analysis.
1273//===----------------------------------------------------------------------===//
1274
1275LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1276 : P(p), F(f) {
1277
1278 // Insert unnamed arguments into the NumberedVals list.
1279 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1280 AI != E; ++AI)
1281 if (!AI->hasName())
1282 NumberedVals.push_back(AI);
1283}
1284
1285LLParser::PerFunctionState::~PerFunctionState() {
1286 // If there were any forward referenced non-basicblock values, delete them.
1287 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1288 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1289 if (!isa<BasicBlock>(I->second.first)) {
1290 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1291 ->getType()));
1292 delete I->second.first;
1293 I->second.first = 0;
1294 }
1295
1296 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1297 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1298 if (!isa<BasicBlock>(I->second.first)) {
1299 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1300 ->getType()));
1301 delete I->second.first;
1302 I->second.first = 0;
1303 }
1304}
1305
1306bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1307 if (!ForwardRefVals.empty())
1308 return P.Error(ForwardRefVals.begin()->second.second,
1309 "use of undefined value '%" + ForwardRefVals.begin()->first +
1310 "'");
1311 if (!ForwardRefValIDs.empty())
1312 return P.Error(ForwardRefValIDs.begin()->second.second,
1313 "use of undefined value '%" +
1314 utostr(ForwardRefValIDs.begin()->first) + "'");
1315 return false;
1316}
1317
1318
1319/// GetVal - Get a value with the specified name or ID, creating a
1320/// forward reference record if needed. This can return null if the value
1321/// exists but does not have the right type.
1322Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1323 const Type *Ty, LocTy Loc) {
1324 // Look this name up in the normal function symbol table.
1325 Value *Val = F.getValueSymbolTable().lookup(Name);
1326
1327 // If this is a forward reference for the value, see if we already created a
1328 // forward ref record.
1329 if (Val == 0) {
1330 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1331 I = ForwardRefVals.find(Name);
1332 if (I != ForwardRefVals.end())
1333 Val = I->second.first;
1334 }
1335
1336 // If we have the value in the symbol table or fwd-ref table, return it.
1337 if (Val) {
1338 if (Val->getType() == Ty) return Val;
1339 if (Ty == Type::LabelTy)
1340 P.Error(Loc, "'%" + Name + "' is not a basic block");
1341 else
1342 P.Error(Loc, "'%" + Name + "' defined with type '" +
1343 Val->getType()->getDescription() + "'");
1344 return 0;
1345 }
1346
1347 // Don't make placeholders with invalid type.
1348 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1349 P.Error(Loc, "invalid use of a non-first-class type");
1350 return 0;
1351 }
1352
1353 // Otherwise, create a new forward reference for this value and remember it.
1354 Value *FwdVal;
1355 if (Ty == Type::LabelTy)
1356 FwdVal = BasicBlock::Create(Name, &F);
1357 else
1358 FwdVal = new Argument(Ty, Name);
1359
1360 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1361 return FwdVal;
1362}
1363
1364Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1365 LocTy Loc) {
1366 // Look this name up in the normal function symbol table.
1367 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1368
1369 // If this is a forward reference for the value, see if we already created a
1370 // forward ref record.
1371 if (Val == 0) {
1372 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1373 I = ForwardRefValIDs.find(ID);
1374 if (I != ForwardRefValIDs.end())
1375 Val = I->second.first;
1376 }
1377
1378 // If we have the value in the symbol table or fwd-ref table, return it.
1379 if (Val) {
1380 if (Val->getType() == Ty) return Val;
1381 if (Ty == Type::LabelTy)
1382 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1383 else
1384 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1385 Val->getType()->getDescription() + "'");
1386 return 0;
1387 }
1388
1389 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1390 P.Error(Loc, "invalid use of a non-first-class type");
1391 return 0;
1392 }
1393
1394 // Otherwise, create a new forward reference for this value and remember it.
1395 Value *FwdVal;
1396 if (Ty == Type::LabelTy)
1397 FwdVal = BasicBlock::Create("", &F);
1398 else
1399 FwdVal = new Argument(Ty);
1400
1401 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1402 return FwdVal;
1403}
1404
1405/// SetInstName - After an instruction is parsed and inserted into its
1406/// basic block, this installs its name.
1407bool LLParser::PerFunctionState::SetInstName(int NameID,
1408 const std::string &NameStr,
1409 LocTy NameLoc, Instruction *Inst) {
1410 // If this instruction has void type, it cannot have a name or ID specified.
1411 if (Inst->getType() == Type::VoidTy) {
1412 if (NameID != -1 || !NameStr.empty())
1413 return P.Error(NameLoc, "instructions returning void cannot have a name");
1414 return false;
1415 }
1416
1417 // If this was a numbered instruction, verify that the instruction is the
1418 // expected value and resolve any forward references.
1419 if (NameStr.empty()) {
1420 // If neither a name nor an ID was specified, just use the next ID.
1421 if (NameID == -1)
1422 NameID = NumberedVals.size();
1423
1424 if (unsigned(NameID) != NumberedVals.size())
1425 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1426 utostr(NumberedVals.size()) + "'");
1427
1428 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1429 ForwardRefValIDs.find(NameID);
1430 if (FI != ForwardRefValIDs.end()) {
1431 if (FI->second.first->getType() != Inst->getType())
1432 return P.Error(NameLoc, "instruction forward referenced with type '" +
1433 FI->second.first->getType()->getDescription() + "'");
1434 FI->second.first->replaceAllUsesWith(Inst);
1435 ForwardRefValIDs.erase(FI);
1436 }
1437
1438 NumberedVals.push_back(Inst);
1439 return false;
1440 }
1441
1442 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1443 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1444 FI = ForwardRefVals.find(NameStr);
1445 if (FI != ForwardRefVals.end()) {
1446 if (FI->second.first->getType() != Inst->getType())
1447 return P.Error(NameLoc, "instruction forward referenced with type '" +
1448 FI->second.first->getType()->getDescription() + "'");
1449 FI->second.first->replaceAllUsesWith(Inst);
1450 ForwardRefVals.erase(FI);
1451 }
1452
1453 // Set the name on the instruction.
1454 Inst->setName(NameStr);
1455
1456 if (Inst->getNameStr() != NameStr)
1457 return P.Error(NameLoc, "multiple definition of local value named '" +
1458 NameStr + "'");
1459 return false;
1460}
1461
1462/// GetBB - Get a basic block with the specified name or ID, creating a
1463/// forward reference record if needed.
1464BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1465 LocTy Loc) {
1466 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1467}
1468
1469BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1470 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1471}
1472
1473/// DefineBB - Define the specified basic block, which is either named or
1474/// unnamed. If there is an error, this returns null otherwise it returns
1475/// the block being defined.
1476BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1477 LocTy Loc) {
1478 BasicBlock *BB;
1479 if (Name.empty())
1480 BB = GetBB(NumberedVals.size(), Loc);
1481 else
1482 BB = GetBB(Name, Loc);
1483 if (BB == 0) return 0; // Already diagnosed error.
1484
1485 // Move the block to the end of the function. Forward ref'd blocks are
1486 // inserted wherever they happen to be referenced.
1487 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1488
1489 // Remove the block from forward ref sets.
1490 if (Name.empty()) {
1491 ForwardRefValIDs.erase(NumberedVals.size());
1492 NumberedVals.push_back(BB);
1493 } else {
1494 // BB forward references are already in the function symbol table.
1495 ForwardRefVals.erase(Name);
1496 }
1497
1498 return BB;
1499}
1500
1501//===----------------------------------------------------------------------===//
1502// Constants.
1503//===----------------------------------------------------------------------===//
1504
1505/// ParseValID - Parse an abstract value that doesn't necessarily have a
1506/// type implied. For example, if we parse "4" we don't know what integer type
1507/// it has. The value will later be combined with its type and checked for
1508/// sanity.
1509bool LLParser::ParseValID(ValID &ID) {
1510 ID.Loc = Lex.getLoc();
1511 switch (Lex.getKind()) {
1512 default: return TokError("expected value token");
1513 case lltok::GlobalID: // @42
1514 ID.UIntVal = Lex.getUIntVal();
1515 ID.Kind = ValID::t_GlobalID;
1516 break;
1517 case lltok::GlobalVar: // @foo
1518 ID.StrVal = Lex.getStrVal();
1519 ID.Kind = ValID::t_GlobalName;
1520 break;
1521 case lltok::LocalVarID: // %42
1522 ID.UIntVal = Lex.getUIntVal();
1523 ID.Kind = ValID::t_LocalID;
1524 break;
1525 case lltok::LocalVar: // %foo
1526 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1527 ID.StrVal = Lex.getStrVal();
1528 ID.Kind = ValID::t_LocalName;
1529 break;
1530 case lltok::APSInt:
1531 ID.APSIntVal = Lex.getAPSIntVal();
1532 ID.Kind = ValID::t_APSInt;
1533 break;
1534 case lltok::APFloat:
1535 ID.APFloatVal = Lex.getAPFloatVal();
1536 ID.Kind = ValID::t_APFloat;
1537 break;
1538 case lltok::kw_true:
1539 ID.ConstantVal = ConstantInt::getTrue();
1540 ID.Kind = ValID::t_Constant;
1541 break;
1542 case lltok::kw_false:
1543 ID.ConstantVal = ConstantInt::getFalse();
1544 ID.Kind = ValID::t_Constant;
1545 break;
1546 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1547 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1548 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1549
1550 case lltok::lbrace: {
1551 // ValID ::= '{' ConstVector '}'
1552 Lex.Lex();
1553 SmallVector<Constant*, 16> Elts;
1554 if (ParseGlobalValueVector(Elts) ||
1555 ParseToken(lltok::rbrace, "expected end of struct constant"))
1556 return true;
1557
1558 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1559 ID.Kind = ValID::t_Constant;
1560 return false;
1561 }
1562 case lltok::less: {
1563 // ValID ::= '<' ConstVector '>' --> Vector.
1564 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1565 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001566 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001567
1568 SmallVector<Constant*, 16> Elts;
1569 LocTy FirstEltLoc = Lex.getLoc();
1570 if (ParseGlobalValueVector(Elts) ||
1571 (isPackedStruct &&
1572 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1573 ParseToken(lltok::greater, "expected end of constant"))
1574 return true;
1575
1576 if (isPackedStruct) {
1577 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1578 ID.Kind = ValID::t_Constant;
1579 return false;
1580 }
1581
1582 if (Elts.empty())
1583 return Error(ID.Loc, "constant vector must not be empty");
1584
1585 if (!Elts[0]->getType()->isInteger() &&
1586 !Elts[0]->getType()->isFloatingPoint())
1587 return Error(FirstEltLoc,
1588 "vector elements must have integer or floating point type");
1589
1590 // Verify that all the vector elements have the same type.
1591 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1592 if (Elts[i]->getType() != Elts[0]->getType())
1593 return Error(FirstEltLoc,
1594 "vector element #" + utostr(i) +
1595 " is not of type '" + Elts[0]->getType()->getDescription());
1596
1597 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1598 ID.Kind = ValID::t_Constant;
1599 return false;
1600 }
1601 case lltok::lsquare: { // Array Constant
1602 Lex.Lex();
1603 SmallVector<Constant*, 16> Elts;
1604 LocTy FirstEltLoc = Lex.getLoc();
1605 if (ParseGlobalValueVector(Elts) ||
1606 ParseToken(lltok::rsquare, "expected end of array constant"))
1607 return true;
1608
1609 // Handle empty element.
1610 if (Elts.empty()) {
1611 // Use undef instead of an array because it's inconvenient to determine
1612 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001613 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001614 return false;
1615 }
1616
1617 if (!Elts[0]->getType()->isFirstClassType())
1618 return Error(FirstEltLoc, "invalid array element type: " +
1619 Elts[0]->getType()->getDescription());
1620
1621 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1622
1623 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001624 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 if (Elts[i]->getType() != Elts[0]->getType())
1626 return Error(FirstEltLoc,
1627 "array element #" + utostr(i) +
1628 " is not of type '" +Elts[0]->getType()->getDescription());
1629 }
1630
1631 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1632 ID.Kind = ValID::t_Constant;
1633 return false;
1634 }
1635 case lltok::kw_c: // c "foo"
1636 Lex.Lex();
1637 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1638 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1639 ID.Kind = ValID::t_Constant;
1640 return false;
1641
1642 case lltok::kw_asm: {
1643 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1644 bool HasSideEffect;
1645 Lex.Lex();
1646 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001647 ParseStringConstant(ID.StrVal) ||
1648 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 ParseToken(lltok::StringConstant, "expected constraint string"))
1650 return true;
1651 ID.StrVal2 = Lex.getStrVal();
1652 ID.UIntVal = HasSideEffect;
1653 ID.Kind = ValID::t_InlineAsm;
1654 return false;
1655 }
1656
1657 case lltok::kw_trunc:
1658 case lltok::kw_zext:
1659 case lltok::kw_sext:
1660 case lltok::kw_fptrunc:
1661 case lltok::kw_fpext:
1662 case lltok::kw_bitcast:
1663 case lltok::kw_uitofp:
1664 case lltok::kw_sitofp:
1665 case lltok::kw_fptoui:
1666 case lltok::kw_fptosi:
1667 case lltok::kw_inttoptr:
1668 case lltok::kw_ptrtoint: {
1669 unsigned Opc = Lex.getUIntVal();
1670 PATypeHolder DestTy(Type::VoidTy);
1671 Constant *SrcVal;
1672 Lex.Lex();
1673 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1674 ParseGlobalTypeAndValue(SrcVal) ||
1675 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1676 ParseType(DestTy) ||
1677 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1678 return true;
1679 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1680 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1681 SrcVal->getType()->getDescription() + "' to '" +
1682 DestTy->getDescription() + "'");
1683 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1684 DestTy);
1685 ID.Kind = ValID::t_Constant;
1686 return false;
1687 }
1688 case lltok::kw_extractvalue: {
1689 Lex.Lex();
1690 Constant *Val;
1691 SmallVector<unsigned, 4> Indices;
1692 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1693 ParseGlobalTypeAndValue(Val) ||
1694 ParseIndexList(Indices) ||
1695 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1696 return true;
1697 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1698 return Error(ID.Loc, "extractvalue operand must be array or struct");
1699 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1700 Indices.end()))
1701 return Error(ID.Loc, "invalid indices for extractvalue");
1702 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1703 &Indices[0], Indices.size());
1704 ID.Kind = ValID::t_Constant;
1705 return false;
1706 }
1707 case lltok::kw_insertvalue: {
1708 Lex.Lex();
1709 Constant *Val0, *Val1;
1710 SmallVector<unsigned, 4> Indices;
1711 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1712 ParseGlobalTypeAndValue(Val0) ||
1713 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1714 ParseGlobalTypeAndValue(Val1) ||
1715 ParseIndexList(Indices) ||
1716 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1717 return true;
1718 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1719 return Error(ID.Loc, "extractvalue operand must be array or struct");
1720 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1721 Indices.end()))
1722 return Error(ID.Loc, "invalid indices for insertvalue");
1723 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1724 &Indices[0], Indices.size());
1725 ID.Kind = ValID::t_Constant;
1726 return false;
1727 }
1728 case lltok::kw_icmp:
1729 case lltok::kw_fcmp:
1730 case lltok::kw_vicmp:
1731 case lltok::kw_vfcmp: {
1732 unsigned PredVal, Opc = Lex.getUIntVal();
1733 Constant *Val0, *Val1;
1734 Lex.Lex();
1735 if (ParseCmpPredicate(PredVal, Opc) ||
1736 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1737 ParseGlobalTypeAndValue(Val0) ||
1738 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1739 ParseGlobalTypeAndValue(Val1) ||
1740 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1741 return true;
1742
1743 if (Val0->getType() != Val1->getType())
1744 return Error(ID.Loc, "compare operands must have the same type");
1745
1746 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1747
1748 if (Opc == Instruction::FCmp) {
1749 if (!Val0->getType()->isFPOrFPVector())
1750 return Error(ID.Loc, "fcmp requires floating point operands");
1751 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1752 } else if (Opc == Instruction::ICmp) {
1753 if (!Val0->getType()->isIntOrIntVector() &&
1754 !isa<PointerType>(Val0->getType()))
1755 return Error(ID.Loc, "icmp requires pointer or integer operands");
1756 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1757 } else if (Opc == Instruction::VFCmp) {
1758 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001759 if (!Val0->getType()->isFPOrFPVector() ||
1760 !isa<VectorType>(Val0->getType()))
1761 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1763 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001764 // FIXME: REMOVE VICMP Support
1765 if (!Val0->getType()->isIntOrIntVector() ||
1766 !isa<VectorType>(Val0->getType()))
1767 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1769 }
1770 ID.Kind = ValID::t_Constant;
1771 return false;
1772 }
1773
1774 // Binary Operators.
1775 case lltok::kw_add:
1776 case lltok::kw_sub:
1777 case lltok::kw_mul:
1778 case lltok::kw_udiv:
1779 case lltok::kw_sdiv:
1780 case lltok::kw_fdiv:
1781 case lltok::kw_urem:
1782 case lltok::kw_srem:
1783 case lltok::kw_frem: {
1784 unsigned Opc = Lex.getUIntVal();
1785 Constant *Val0, *Val1;
1786 Lex.Lex();
1787 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1788 ParseGlobalTypeAndValue(Val0) ||
1789 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1790 ParseGlobalTypeAndValue(Val1) ||
1791 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1792 return true;
1793 if (Val0->getType() != Val1->getType())
1794 return Error(ID.Loc, "operands of constexpr must have same type");
1795 if (!Val0->getType()->isIntOrIntVector() &&
1796 !Val0->getType()->isFPOrFPVector())
1797 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1798 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1799 ID.Kind = ValID::t_Constant;
1800 return false;
1801 }
1802
1803 // Logical Operations
1804 case lltok::kw_shl:
1805 case lltok::kw_lshr:
1806 case lltok::kw_ashr:
1807 case lltok::kw_and:
1808 case lltok::kw_or:
1809 case lltok::kw_xor: {
1810 unsigned Opc = Lex.getUIntVal();
1811 Constant *Val0, *Val1;
1812 Lex.Lex();
1813 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1814 ParseGlobalTypeAndValue(Val0) ||
1815 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1816 ParseGlobalTypeAndValue(Val1) ||
1817 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1818 return true;
1819 if (Val0->getType() != Val1->getType())
1820 return Error(ID.Loc, "operands of constexpr must have same type");
1821 if (!Val0->getType()->isIntOrIntVector())
1822 return Error(ID.Loc,
1823 "constexpr requires integer or integer vector operands");
1824 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1825 ID.Kind = ValID::t_Constant;
1826 return false;
1827 }
1828
1829 case lltok::kw_getelementptr:
1830 case lltok::kw_shufflevector:
1831 case lltok::kw_insertelement:
1832 case lltok::kw_extractelement:
1833 case lltok::kw_select: {
1834 unsigned Opc = Lex.getUIntVal();
1835 SmallVector<Constant*, 16> Elts;
1836 Lex.Lex();
1837 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1838 ParseGlobalValueVector(Elts) ||
1839 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1840 return true;
1841
1842 if (Opc == Instruction::GetElementPtr) {
1843 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1844 return Error(ID.Loc, "getelementptr requires pointer operand");
1845
1846 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1847 (Value**)&Elts[1], Elts.size()-1))
1848 return Error(ID.Loc, "invalid indices for getelementptr");
1849 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1850 &Elts[1], Elts.size()-1);
1851 } else if (Opc == Instruction::Select) {
1852 if (Elts.size() != 3)
1853 return Error(ID.Loc, "expected three operands to select");
1854 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1855 Elts[2]))
1856 return Error(ID.Loc, Reason);
1857 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1858 } else if (Opc == Instruction::ShuffleVector) {
1859 if (Elts.size() != 3)
1860 return Error(ID.Loc, "expected three operands to shufflevector");
1861 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1862 return Error(ID.Loc, "invalid operands to shufflevector");
1863 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1864 } else if (Opc == Instruction::ExtractElement) {
1865 if (Elts.size() != 2)
1866 return Error(ID.Loc, "expected two operands to extractelement");
1867 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1868 return Error(ID.Loc, "invalid extractelement operands");
1869 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1870 } else {
1871 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1872 if (Elts.size() != 3)
1873 return Error(ID.Loc, "expected three operands to insertelement");
1874 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1875 return Error(ID.Loc, "invalid insertelement operands");
1876 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1877 }
1878
1879 ID.Kind = ValID::t_Constant;
1880 return false;
1881 }
1882 }
1883
1884 Lex.Lex();
1885 return false;
1886}
1887
1888/// ParseGlobalValue - Parse a global value with the specified type.
1889bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1890 V = 0;
1891 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001892 return ParseValID(ID) ||
1893 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001894}
1895
1896/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1897/// constant.
1898bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1899 Constant *&V) {
1900 if (isa<FunctionType>(Ty))
1901 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1902
1903 switch (ID.Kind) {
1904 default: assert(0 && "Unknown ValID!");
1905 case ValID::t_LocalID:
1906 case ValID::t_LocalName:
1907 return Error(ID.Loc, "invalid use of function-local name");
1908 case ValID::t_InlineAsm:
1909 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1910 case ValID::t_GlobalName:
1911 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1912 return V == 0;
1913 case ValID::t_GlobalID:
1914 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1915 return V == 0;
1916 case ValID::t_APSInt:
1917 if (!isa<IntegerType>(Ty))
1918 return Error(ID.Loc, "integer constant must have integer type");
1919 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1920 V = ConstantInt::get(ID.APSIntVal);
1921 return false;
1922 case ValID::t_APFloat:
1923 if (!Ty->isFloatingPoint() ||
1924 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1925 return Error(ID.Loc, "floating point constant invalid for type");
1926
1927 // The lexer has no type info, so builds all float and double FP constants
1928 // as double. Fix this here. Long double does not need this.
1929 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1930 Ty == Type::FloatTy) {
1931 bool Ignored;
1932 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1933 &Ignored);
1934 }
1935 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001936
1937 if (V->getType() != Ty)
1938 return Error(ID.Loc, "floating point constant does not have type '" +
1939 Ty->getDescription() + "'");
1940
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 return false;
1942 case ValID::t_Null:
1943 if (!isa<PointerType>(Ty))
1944 return Error(ID.Loc, "null must be a pointer type");
1945 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1946 return false;
1947 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001948 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00001949 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1950 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001951 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00001952 V = UndefValue::get(Ty);
1953 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00001954 case ValID::t_EmptyArray:
1955 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1956 return Error(ID.Loc, "invalid empty array initializer");
1957 V = UndefValue::get(Ty);
1958 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001960 // FIXME: LabelTy should not be a first-class type.
1961 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00001962 return Error(ID.Loc, "invalid type for null constant");
1963 V = Constant::getNullValue(Ty);
1964 return false;
1965 case ValID::t_Constant:
1966 if (ID.ConstantVal->getType() != Ty)
1967 return Error(ID.Loc, "constant expression type mismatch");
1968 V = ID.ConstantVal;
1969 return false;
1970 }
1971}
1972
1973bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1974 PATypeHolder Type(Type::VoidTy);
1975 return ParseType(Type) ||
1976 ParseGlobalValue(Type, V);
1977}
1978
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001979/// ParseGlobalValueVector
1980/// ::= /*empty*/
1981/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00001982bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1983 // Empty list.
1984 if (Lex.getKind() == lltok::rbrace ||
1985 Lex.getKind() == lltok::rsquare ||
1986 Lex.getKind() == lltok::greater ||
1987 Lex.getKind() == lltok::rparen)
1988 return false;
1989
1990 Constant *C;
1991 if (ParseGlobalTypeAndValue(C)) return true;
1992 Elts.push_back(C);
1993
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001994 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 if (ParseGlobalTypeAndValue(C)) return true;
1996 Elts.push_back(C);
1997 }
1998
1999 return false;
2000}
2001
2002
2003//===----------------------------------------------------------------------===//
2004// Function Parsing.
2005//===----------------------------------------------------------------------===//
2006
2007bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2008 PerFunctionState &PFS) {
2009 if (ID.Kind == ValID::t_LocalID)
2010 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2011 else if (ID.Kind == ValID::t_LocalName)
2012 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002013 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002014 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2015 const FunctionType *FTy =
2016 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2017 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2018 return Error(ID.Loc, "invalid type for inline asm constraint string");
2019 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2020 return false;
2021 } else {
2022 Constant *C;
2023 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2024 V = C;
2025 return false;
2026 }
2027
2028 return V == 0;
2029}
2030
2031bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2032 V = 0;
2033 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002034 return ParseValID(ID) ||
2035 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002036}
2037
2038bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2039 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002040 return ParseType(T) ||
2041 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002042}
2043
2044/// FunctionHeader
2045/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2046/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2047/// OptionalAlign OptGC
2048bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2049 // Parse the linkage.
2050 LocTy LinkageLoc = Lex.getLoc();
2051 unsigned Linkage;
2052
2053 unsigned Visibility, CC, RetAttrs;
2054 PATypeHolder RetType(Type::VoidTy);
2055 LocTy RetTypeLoc = Lex.getLoc();
2056 if (ParseOptionalLinkage(Linkage) ||
2057 ParseOptionalVisibility(Visibility) ||
2058 ParseOptionalCallingConv(CC) ||
2059 ParseOptionalAttrs(RetAttrs, 1) ||
2060 ParseType(RetType, RetTypeLoc))
2061 return true;
2062
2063 // Verify that the linkage is ok.
2064 switch ((GlobalValue::LinkageTypes)Linkage) {
2065 case GlobalValue::ExternalLinkage:
2066 break; // always ok.
2067 case GlobalValue::DLLImportLinkage:
2068 case GlobalValue::ExternalWeakLinkage:
2069 if (isDefine)
2070 return Error(LinkageLoc, "invalid linkage for function definition");
2071 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002072 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 case GlobalValue::InternalLinkage:
2074 case GlobalValue::LinkOnceLinkage:
2075 case GlobalValue::WeakLinkage:
2076 case GlobalValue::DLLExportLinkage:
2077 if (!isDefine)
2078 return Error(LinkageLoc, "invalid linkage for function declaration");
2079 break;
2080 case GlobalValue::AppendingLinkage:
2081 case GlobalValue::GhostLinkage:
2082 case GlobalValue::CommonLinkage:
2083 return Error(LinkageLoc, "invalid function linkage type");
2084 }
2085
Chris Lattner99bb3152009-01-05 08:00:30 +00002086 if (!FunctionType::isValidReturnType(RetType) ||
2087 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 return Error(RetTypeLoc, "invalid function return type");
2089
2090 if (Lex.getKind() != lltok::GlobalVar)
2091 return TokError("expected function name");
2092
2093 LocTy NameLoc = Lex.getLoc();
2094 std::string FunctionName = Lex.getStrVal();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002095 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002096
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002097 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 return TokError("expected '(' in function argument list");
2099
2100 std::vector<ArgInfo> ArgList;
2101 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002105 std::string GC;
2106
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002107 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002108 ParseOptionalAttrs(FuncAttrs, 2) ||
2109 (EatIfPresent(lltok::kw_section) &&
2110 ParseStringConstant(Section)) ||
2111 ParseOptionalAlignment(Alignment) ||
2112 (EatIfPresent(lltok::kw_gc) &&
2113 ParseStringConstant(GC)))
2114 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002115
2116 // If the alignment was parsed as an attribute, move to the alignment field.
2117 if (FuncAttrs & Attribute::Alignment) {
2118 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2119 FuncAttrs &= ~Attribute::Alignment;
2120 }
2121
Chris Lattnerdf986172009-01-02 07:01:27 +00002122 // Okay, if we got here, the function is syntactically valid. Convert types
2123 // and do semantic checks.
2124 std::vector<const Type*> ParamTypeList;
2125 SmallVector<AttributeWithIndex, 8> Attrs;
2126 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2127 // attributes.
2128 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2129 if (FuncAttrs & ObsoleteFuncAttrs) {
2130 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2131 FuncAttrs &= ~ObsoleteFuncAttrs;
2132 }
2133
2134 if (RetAttrs != Attribute::None)
2135 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2136
2137 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2138 ParamTypeList.push_back(ArgList[i].Type);
2139 if (ArgList[i].Attrs != Attribute::None)
2140 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2141 }
2142
2143 if (FuncAttrs != Attribute::None)
2144 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2145
2146 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2147
2148 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2149 const PointerType *PFT = PointerType::getUnqual(FT);
2150
2151 Fn = 0;
2152 if (!FunctionName.empty()) {
2153 // If this was a definition of a forward reference, remove the definition
2154 // from the forward reference table and fill in the forward ref.
2155 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2156 ForwardRefVals.find(FunctionName);
2157 if (FRVI != ForwardRefVals.end()) {
2158 Fn = M->getFunction(FunctionName);
2159 ForwardRefVals.erase(FRVI);
2160 } else if ((Fn = M->getFunction(FunctionName))) {
2161 // If this function already exists in the symbol table, then it is
2162 // multiply defined. We accept a few cases for old backwards compat.
2163 // FIXME: Remove this stuff for LLVM 3.0.
2164 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2165 (!Fn->isDeclaration() && isDefine)) {
2166 // If the redefinition has different type or different attributes,
2167 // reject it. If both have bodies, reject it.
2168 return Error(NameLoc, "invalid redefinition of function '" +
2169 FunctionName + "'");
2170 } else if (Fn->isDeclaration()) {
2171 // Make sure to strip off any argument names so we can't get conflicts.
2172 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2173 AI != AE; ++AI)
2174 AI->setName("");
2175 }
2176 }
2177
2178 } else if (FunctionName.empty()) {
2179 // If this is a definition of a forward referenced function, make sure the
2180 // types agree.
2181 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2182 = ForwardRefValIDs.find(NumberedVals.size());
2183 if (I != ForwardRefValIDs.end()) {
2184 Fn = cast<Function>(I->second.first);
2185 if (Fn->getType() != PFT)
2186 return Error(NameLoc, "type of definition and forward reference of '@" +
2187 utostr(NumberedVals.size()) +"' disagree");
2188 ForwardRefValIDs.erase(I);
2189 }
2190 }
2191
2192 if (Fn == 0)
2193 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2194 else // Move the forward-reference to the correct spot in the module.
2195 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2196
2197 if (FunctionName.empty())
2198 NumberedVals.push_back(Fn);
2199
2200 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2201 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2202 Fn->setCallingConv(CC);
2203 Fn->setAttributes(PAL);
2204 Fn->setAlignment(Alignment);
2205 Fn->setSection(Section);
2206 if (!GC.empty()) Fn->setGC(GC.c_str());
2207
2208 // Add all of the arguments we parsed to the function.
2209 Function::arg_iterator ArgIt = Fn->arg_begin();
2210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2211 // If the argument has a name, insert it into the argument symbol table.
2212 if (ArgList[i].Name.empty()) continue;
2213
2214 // Set the name, if it conflicted, it will be auto-renamed.
2215 ArgIt->setName(ArgList[i].Name);
2216
2217 if (ArgIt->getNameStr() != ArgList[i].Name)
2218 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2219 ArgList[i].Name + "'");
2220 }
2221
2222 return false;
2223}
2224
2225
2226/// ParseFunctionBody
2227/// ::= '{' BasicBlock+ '}'
2228/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2229///
2230bool LLParser::ParseFunctionBody(Function &Fn) {
2231 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2232 return TokError("expected '{' in function body");
2233 Lex.Lex(); // eat the {.
2234
2235 PerFunctionState PFS(*this, Fn);
2236
2237 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2238 if (ParseBasicBlock(PFS)) return true;
2239
2240 // Eat the }.
2241 Lex.Lex();
2242
2243 // Verify function is ok.
2244 return PFS.VerifyFunctionComplete();
2245}
2246
2247/// ParseBasicBlock
2248/// ::= LabelStr? Instruction*
2249bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2250 // If this basic block starts out with a name, remember it.
2251 std::string Name;
2252 LocTy NameLoc = Lex.getLoc();
2253 if (Lex.getKind() == lltok::LabelStr) {
2254 Name = Lex.getStrVal();
2255 Lex.Lex();
2256 }
2257
2258 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2259 if (BB == 0) return true;
2260
2261 std::string NameStr;
2262
2263 // Parse the instructions in this block until we get a terminator.
2264 Instruction *Inst;
2265 do {
2266 // This instruction may have three possibilities for a name: a) none
2267 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2268 LocTy NameLoc = Lex.getLoc();
2269 int NameID = -1;
2270 NameStr = "";
2271
2272 if (Lex.getKind() == lltok::LocalVarID) {
2273 NameID = Lex.getUIntVal();
2274 Lex.Lex();
2275 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2276 return true;
2277 } else if (Lex.getKind() == lltok::LocalVar ||
2278 // FIXME: REMOVE IN LLVM 3.0
2279 Lex.getKind() == lltok::StringConstant) {
2280 NameStr = Lex.getStrVal();
2281 Lex.Lex();
2282 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2283 return true;
2284 }
2285
2286 if (ParseInstruction(Inst, BB, PFS)) return true;
2287
2288 BB->getInstList().push_back(Inst);
2289
2290 // Set the name on the instruction.
2291 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2292 } while (!isa<TerminatorInst>(Inst));
2293
2294 return false;
2295}
2296
2297//===----------------------------------------------------------------------===//
2298// Instruction Parsing.
2299//===----------------------------------------------------------------------===//
2300
2301/// ParseInstruction - Parse one of the many different instructions.
2302///
2303bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2304 PerFunctionState &PFS) {
2305 lltok::Kind Token = Lex.getKind();
2306 if (Token == lltok::Eof)
2307 return TokError("found end of file when expecting more instructions");
2308 LocTy Loc = Lex.getLoc();
2309 Lex.Lex(); // Eat the keyword.
2310
2311 switch (Token) {
2312 default: return Error(Loc, "expected instruction opcode");
2313 // Terminator Instructions.
2314 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2315 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2316 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2317 case lltok::kw_br: return ParseBr(Inst, PFS);
2318 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2319 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2320 // Binary Operators.
2321 case lltok::kw_add:
2322 case lltok::kw_sub:
Chris Lattnere914b592009-01-05 08:24:46 +00002323 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2324
Chris Lattnerdf986172009-01-02 07:01:27 +00002325 case lltok::kw_udiv:
2326 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 case lltok::kw_urem:
Chris Lattnere914b592009-01-05 08:24:46 +00002328 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2329 case lltok::kw_fdiv:
2330 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 case lltok::kw_shl:
2332 case lltok::kw_lshr:
2333 case lltok::kw_ashr:
2334 case lltok::kw_and:
2335 case lltok::kw_or:
2336 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2337 case lltok::kw_icmp:
2338 case lltok::kw_fcmp:
2339 case lltok::kw_vicmp:
2340 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2341 // Casts.
2342 case lltok::kw_trunc:
2343 case lltok::kw_zext:
2344 case lltok::kw_sext:
2345 case lltok::kw_fptrunc:
2346 case lltok::kw_fpext:
2347 case lltok::kw_bitcast:
2348 case lltok::kw_uitofp:
2349 case lltok::kw_sitofp:
2350 case lltok::kw_fptoui:
2351 case lltok::kw_fptosi:
2352 case lltok::kw_inttoptr:
2353 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2354 // Other.
2355 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002356 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002357 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2358 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2359 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2360 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2361 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2362 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2363 // Memory.
2364 case lltok::kw_alloca:
2365 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2366 case lltok::kw_free: return ParseFree(Inst, PFS);
2367 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2368 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2369 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002370 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002371 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002372 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002374 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2377 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2378 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2379 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2380 }
2381}
2382
2383/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2384bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2385 // FIXME: REMOVE vicmp/vfcmp!
2386 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2387 switch (Lex.getKind()) {
2388 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2389 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2390 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2391 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2392 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2393 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2394 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2395 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2396 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2397 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2398 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2399 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2400 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2401 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2402 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2403 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2404 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2405 }
2406 } else {
2407 switch (Lex.getKind()) {
2408 default: TokError("expected icmp predicate (e.g. 'eq')");
2409 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2410 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2411 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2412 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2413 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2414 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2415 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2416 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2417 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2418 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2419 }
2420 }
2421 Lex.Lex();
2422 return false;
2423}
2424
2425//===----------------------------------------------------------------------===//
2426// Terminator Instructions.
2427//===----------------------------------------------------------------------===//
2428
2429/// ParseRet - Parse a return instruction.
2430/// ::= 'ret' void
2431/// ::= 'ret' TypeAndValue
2432/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2433bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2434 PerFunctionState &PFS) {
2435 PATypeHolder Ty(Type::VoidTy);
2436 if (ParseType(Ty)) return true;
2437
2438 if (Ty == Type::VoidTy) {
2439 Inst = ReturnInst::Create();
2440 return false;
2441 }
2442
2443 Value *RV;
2444 if (ParseValue(Ty, RV, PFS)) return true;
2445
2446 // The normal case is one return value.
2447 if (Lex.getKind() == lltok::comma) {
2448 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2449 // of 'ret {i32,i32} {i32 1, i32 2}'
2450 SmallVector<Value*, 8> RVs;
2451 RVs.push_back(RV);
2452
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002453 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 if (ParseTypeAndValue(RV, PFS)) return true;
2455 RVs.push_back(RV);
2456 }
2457
2458 RV = UndefValue::get(PFS.getFunction().getReturnType());
2459 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2460 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2461 BB->getInstList().push_back(I);
2462 RV = I;
2463 }
2464 }
2465 Inst = ReturnInst::Create(RV);
2466 return false;
2467}
2468
2469
2470/// ParseBr
2471/// ::= 'br' TypeAndValue
2472/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2473bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2474 LocTy Loc, Loc2;
2475 Value *Op0, *Op1, *Op2;
2476 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2477
2478 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2479 Inst = BranchInst::Create(BB);
2480 return false;
2481 }
2482
2483 if (Op0->getType() != Type::Int1Ty)
2484 return Error(Loc, "branch condition must have 'i1' type");
2485
2486 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2487 ParseTypeAndValue(Op1, Loc, PFS) ||
2488 ParseToken(lltok::comma, "expected ',' after true destination") ||
2489 ParseTypeAndValue(Op2, Loc2, PFS))
2490 return true;
2491
2492 if (!isa<BasicBlock>(Op1))
2493 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 if (!isa<BasicBlock>(Op2))
2495 return Error(Loc2, "true destination of branch must be a basic block");
2496
2497 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2498 return false;
2499}
2500
2501/// ParseSwitch
2502/// Instruction
2503/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2504/// JumpTable
2505/// ::= (TypeAndValue ',' TypeAndValue)*
2506bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2507 LocTy CondLoc, BBLoc;
2508 Value *Cond, *DefaultBB;
2509 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2510 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2511 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2512 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2513 return true;
2514
2515 if (!isa<IntegerType>(Cond->getType()))
2516 return Error(CondLoc, "switch condition must have integer type");
2517 if (!isa<BasicBlock>(DefaultBB))
2518 return Error(BBLoc, "default destination must be a basic block");
2519
2520 // Parse the jump table pairs.
2521 SmallPtrSet<Value*, 32> SeenCases;
2522 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2523 while (Lex.getKind() != lltok::rsquare) {
2524 Value *Constant, *DestBB;
2525
2526 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2527 ParseToken(lltok::comma, "expected ',' after case value") ||
2528 ParseTypeAndValue(DestBB, BBLoc, PFS))
2529 return true;
2530
2531 if (!SeenCases.insert(Constant))
2532 return Error(CondLoc, "duplicate case value in switch");
2533 if (!isa<ConstantInt>(Constant))
2534 return Error(CondLoc, "case value is not a constant integer");
2535 if (!isa<BasicBlock>(DestBB))
2536 return Error(BBLoc, "case destination is not a basic block");
2537
2538 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2539 cast<BasicBlock>(DestBB)));
2540 }
2541
2542 Lex.Lex(); // Eat the ']'.
2543
2544 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2545 Table.size());
2546 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2547 SI->addCase(Table[i].first, Table[i].second);
2548 Inst = SI;
2549 return false;
2550}
2551
2552/// ParseInvoke
2553/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2554/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2555bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2556 LocTy CallLoc = Lex.getLoc();
2557 unsigned CC, RetAttrs, FnAttrs;
2558 PATypeHolder RetType(Type::VoidTy);
2559 LocTy RetTypeLoc;
2560 ValID CalleeID;
2561 SmallVector<ParamInfo, 16> ArgList;
2562
2563 Value *NormalBB, *UnwindBB;
2564 if (ParseOptionalCallingConv(CC) ||
2565 ParseOptionalAttrs(RetAttrs, 1) ||
2566 ParseType(RetType, RetTypeLoc) ||
2567 ParseValID(CalleeID) ||
2568 ParseParameterList(ArgList, PFS) ||
2569 ParseOptionalAttrs(FnAttrs, 2) ||
2570 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2571 ParseTypeAndValue(NormalBB, PFS) ||
2572 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2573 ParseTypeAndValue(UnwindBB, PFS))
2574 return true;
2575
2576 if (!isa<BasicBlock>(NormalBB))
2577 return Error(CallLoc, "normal destination is not a basic block");
2578 if (!isa<BasicBlock>(UnwindBB))
2579 return Error(CallLoc, "unwind destination is not a basic block");
2580
2581 // If RetType is a non-function pointer type, then this is the short syntax
2582 // for the call, which means that RetType is just the return type. Infer the
2583 // rest of the function argument types from the arguments that are present.
2584 const PointerType *PFTy = 0;
2585 const FunctionType *Ty = 0;
2586 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2587 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2588 // Pull out the types of all of the arguments...
2589 std::vector<const Type*> ParamTypes;
2590 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2591 ParamTypes.push_back(ArgList[i].V->getType());
2592
2593 if (!FunctionType::isValidReturnType(RetType))
2594 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2595
2596 Ty = FunctionType::get(RetType, ParamTypes, false);
2597 PFTy = PointerType::getUnqual(Ty);
2598 }
2599
2600 // Look up the callee.
2601 Value *Callee;
2602 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2603
2604 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2605 // function attributes.
2606 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2607 if (FnAttrs & ObsoleteFuncAttrs) {
2608 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2609 FnAttrs &= ~ObsoleteFuncAttrs;
2610 }
2611
2612 // Set up the Attributes for the function.
2613 SmallVector<AttributeWithIndex, 8> Attrs;
2614 if (RetAttrs != Attribute::None)
2615 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2616
2617 SmallVector<Value*, 8> Args;
2618
2619 // Loop through FunctionType's arguments and ensure they are specified
2620 // correctly. Also, gather any parameter attributes.
2621 FunctionType::param_iterator I = Ty->param_begin();
2622 FunctionType::param_iterator E = Ty->param_end();
2623 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2624 const Type *ExpectedTy = 0;
2625 if (I != E) {
2626 ExpectedTy = *I++;
2627 } else if (!Ty->isVarArg()) {
2628 return Error(ArgList[i].Loc, "too many arguments specified");
2629 }
2630
2631 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2632 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2633 ExpectedTy->getDescription() + "'");
2634 Args.push_back(ArgList[i].V);
2635 if (ArgList[i].Attrs != Attribute::None)
2636 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2637 }
2638
2639 if (I != E)
2640 return Error(CallLoc, "not enough parameters specified for call");
2641
2642 if (FnAttrs != Attribute::None)
2643 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2644
2645 // Finish off the Attributes and check them
2646 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2647
2648 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2649 cast<BasicBlock>(UnwindBB),
2650 Args.begin(), Args.end());
2651 II->setCallingConv(CC);
2652 II->setAttributes(PAL);
2653 Inst = II;
2654 return false;
2655}
2656
2657
2658
2659//===----------------------------------------------------------------------===//
2660// Binary Operators.
2661//===----------------------------------------------------------------------===//
2662
2663/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002664/// ::= ArithmeticOps TypeAndValue ',' Value
2665///
2666/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2667/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002668bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002669 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 LocTy Loc; Value *LHS, *RHS;
2671 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2672 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2673 ParseValue(LHS->getType(), RHS, PFS))
2674 return true;
2675
Chris Lattnere914b592009-01-05 08:24:46 +00002676 bool Valid;
2677 switch (OperandType) {
2678 default: assert(0 && "Unknown operand type!");
2679 case 0: // int or FP.
2680 Valid = LHS->getType()->isIntOrIntVector() ||
2681 LHS->getType()->isFPOrFPVector();
2682 break;
2683 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2684 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2685 }
2686
2687 if (!Valid)
2688 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002689
2690 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2691 return false;
2692}
2693
2694/// ParseLogical
2695/// ::= ArithmeticOps TypeAndValue ',' Value {
2696bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2697 unsigned Opc) {
2698 LocTy Loc; Value *LHS, *RHS;
2699 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2700 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2701 ParseValue(LHS->getType(), RHS, PFS))
2702 return true;
2703
2704 if (!LHS->getType()->isIntOrIntVector())
2705 return Error(Loc,"instruction requires integer or integer vector operands");
2706
2707 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2708 return false;
2709}
2710
2711
2712/// ParseCompare
2713/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2714/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2715/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2716/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2717bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2718 unsigned Opc) {
2719 // Parse the integer/fp comparison predicate.
2720 LocTy Loc;
2721 unsigned Pred;
2722 Value *LHS, *RHS;
2723 if (ParseCmpPredicate(Pred, Opc) ||
2724 ParseTypeAndValue(LHS, Loc, PFS) ||
2725 ParseToken(lltok::comma, "expected ',' after compare value") ||
2726 ParseValue(LHS->getType(), RHS, PFS))
2727 return true;
2728
2729 if (Opc == Instruction::FCmp) {
2730 if (!LHS->getType()->isFPOrFPVector())
2731 return Error(Loc, "fcmp requires floating point operands");
2732 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2733 } else if (Opc == Instruction::ICmp) {
2734 if (!LHS->getType()->isIntOrIntVector() &&
2735 !isa<PointerType>(LHS->getType()))
2736 return Error(Loc, "icmp requires integer operands");
2737 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2738 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002739 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2740 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002741 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2742 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002743 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2744 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2746 }
2747 return false;
2748}
2749
2750//===----------------------------------------------------------------------===//
2751// Other Instructions.
2752//===----------------------------------------------------------------------===//
2753
2754
2755/// ParseCast
2756/// ::= CastOpc TypeAndValue 'to' Type
2757bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2758 unsigned Opc) {
2759 LocTy Loc; Value *Op;
2760 PATypeHolder DestTy(Type::VoidTy);
2761 if (ParseTypeAndValue(Op, Loc, PFS) ||
2762 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2763 ParseType(DestTy))
2764 return true;
2765
2766 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2767 return Error(Loc, "invalid cast opcode for cast from '" +
2768 Op->getType()->getDescription() + "' to '" +
2769 DestTy->getDescription() + "'");
2770 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2771 return false;
2772}
2773
2774/// ParseSelect
2775/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2776bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2777 LocTy Loc;
2778 Value *Op0, *Op1, *Op2;
2779 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2780 ParseToken(lltok::comma, "expected ',' after select condition") ||
2781 ParseTypeAndValue(Op1, PFS) ||
2782 ParseToken(lltok::comma, "expected ',' after select value") ||
2783 ParseTypeAndValue(Op2, PFS))
2784 return true;
2785
2786 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2787 return Error(Loc, Reason);
2788
2789 Inst = SelectInst::Create(Op0, Op1, Op2);
2790 return false;
2791}
2792
Chris Lattner0088a5c2009-01-05 08:18:44 +00002793/// ParseVA_Arg
2794/// ::= 'va_arg' TypeAndValue ',' Type
2795bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 Value *Op;
2797 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002798 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002799 if (ParseTypeAndValue(Op, PFS) ||
2800 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002801 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002803
2804 if (!EltTy->isFirstClassType())
2805 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002806
2807 Inst = new VAArgInst(Op, EltTy);
2808 return false;
2809}
2810
2811/// ParseExtractElement
2812/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2813bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2814 LocTy Loc;
2815 Value *Op0, *Op1;
2816 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2817 ParseToken(lltok::comma, "expected ',' after extract value") ||
2818 ParseTypeAndValue(Op1, PFS))
2819 return true;
2820
2821 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2822 return Error(Loc, "invalid extractelement operands");
2823
2824 Inst = new ExtractElementInst(Op0, Op1);
2825 return false;
2826}
2827
2828/// ParseInsertElement
2829/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2830bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2831 LocTy Loc;
2832 Value *Op0, *Op1, *Op2;
2833 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2834 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2835 ParseTypeAndValue(Op1, PFS) ||
2836 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2837 ParseTypeAndValue(Op2, PFS))
2838 return true;
2839
2840 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2841 return Error(Loc, "invalid extractelement operands");
2842
2843 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2844 return false;
2845}
2846
2847/// ParseShuffleVector
2848/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2849bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2850 LocTy Loc;
2851 Value *Op0, *Op1, *Op2;
2852 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2853 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2854 ParseTypeAndValue(Op1, PFS) ||
2855 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2856 ParseTypeAndValue(Op2, PFS))
2857 return true;
2858
2859 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2860 return Error(Loc, "invalid extractelement operands");
2861
2862 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2863 return false;
2864}
2865
2866/// ParsePHI
2867/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2868bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2869 PATypeHolder Ty(Type::VoidTy);
2870 Value *Op0, *Op1;
2871 LocTy TypeLoc = Lex.getLoc();
2872
2873 if (ParseType(Ty) ||
2874 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2875 ParseValue(Ty, Op0, PFS) ||
2876 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2877 ParseValue(Type::LabelTy, Op1, PFS) ||
2878 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2879 return true;
2880
2881 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2882 while (1) {
2883 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2884
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002885 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002886 break;
2887
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002888 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 ParseValue(Ty, Op0, PFS) ||
2890 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2891 ParseValue(Type::LabelTy, Op1, PFS) ||
2892 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2893 return true;
2894 }
2895
2896 if (!Ty->isFirstClassType())
2897 return Error(TypeLoc, "phi node must have first class type");
2898
2899 PHINode *PN = PHINode::Create(Ty);
2900 PN->reserveOperandSpace(PHIVals.size());
2901 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2902 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2903 Inst = PN;
2904 return false;
2905}
2906
2907/// ParseCall
2908/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2909/// ParameterList OptionalAttrs
2910bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2911 bool isTail) {
2912 unsigned CC, RetAttrs, FnAttrs;
2913 PATypeHolder RetType(Type::VoidTy);
2914 LocTy RetTypeLoc;
2915 ValID CalleeID;
2916 SmallVector<ParamInfo, 16> ArgList;
2917 LocTy CallLoc = Lex.getLoc();
2918
2919 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2920 ParseOptionalCallingConv(CC) ||
2921 ParseOptionalAttrs(RetAttrs, 1) ||
2922 ParseType(RetType, RetTypeLoc) ||
2923 ParseValID(CalleeID) ||
2924 ParseParameterList(ArgList, PFS) ||
2925 ParseOptionalAttrs(FnAttrs, 2))
2926 return true;
2927
2928 // If RetType is a non-function pointer type, then this is the short syntax
2929 // for the call, which means that RetType is just the return type. Infer the
2930 // rest of the function argument types from the arguments that are present.
2931 const PointerType *PFTy = 0;
2932 const FunctionType *Ty = 0;
2933 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2934 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2935 // Pull out the types of all of the arguments...
2936 std::vector<const Type*> ParamTypes;
2937 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2938 ParamTypes.push_back(ArgList[i].V->getType());
2939
2940 if (!FunctionType::isValidReturnType(RetType))
2941 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2942
2943 Ty = FunctionType::get(RetType, ParamTypes, false);
2944 PFTy = PointerType::getUnqual(Ty);
2945 }
2946
2947 // Look up the callee.
2948 Value *Callee;
2949 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2950
2951 // Check for call to invalid intrinsic to avoid crashing later.
2952 if (Function *F = dyn_cast<Function>(Callee)) {
2953 if (F->hasName() && F->getNameLen() >= 5 &&
2954 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2955 !F->getIntrinsicID(true))
2956 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2957 F->getNameStr() + "'");
2958 }
2959
2960 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2961 // function attributes.
2962 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2963 if (FnAttrs & ObsoleteFuncAttrs) {
2964 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2965 FnAttrs &= ~ObsoleteFuncAttrs;
2966 }
2967
2968 // Set up the Attributes for the function.
2969 SmallVector<AttributeWithIndex, 8> Attrs;
2970 if (RetAttrs != Attribute::None)
2971 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2972
2973 SmallVector<Value*, 8> Args;
2974
2975 // Loop through FunctionType's arguments and ensure they are specified
2976 // correctly. Also, gather any parameter attributes.
2977 FunctionType::param_iterator I = Ty->param_begin();
2978 FunctionType::param_iterator E = Ty->param_end();
2979 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2980 const Type *ExpectedTy = 0;
2981 if (I != E) {
2982 ExpectedTy = *I++;
2983 } else if (!Ty->isVarArg()) {
2984 return Error(ArgList[i].Loc, "too many arguments specified");
2985 }
2986
2987 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2988 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2989 ExpectedTy->getDescription() + "'");
2990 Args.push_back(ArgList[i].V);
2991 if (ArgList[i].Attrs != Attribute::None)
2992 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2993 }
2994
2995 if (I != E)
2996 return Error(CallLoc, "not enough parameters specified for call");
2997
2998 if (FnAttrs != Attribute::None)
2999 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3000
3001 // Finish off the Attributes and check them
3002 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3003
3004 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3005 CI->setTailCall(isTail);
3006 CI->setCallingConv(CC);
3007 CI->setAttributes(PAL);
3008 Inst = CI;
3009 return false;
3010}
3011
3012//===----------------------------------------------------------------------===//
3013// Memory Instructions.
3014//===----------------------------------------------------------------------===//
3015
3016/// ParseAlloc
3017/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3018/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3019bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3020 unsigned Opc) {
3021 PATypeHolder Ty(Type::VoidTy);
3022 Value *Size = 0;
3023 LocTy SizeLoc = 0;
3024 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003025 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003026
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003027 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003028 if (Lex.getKind() == lltok::kw_align) {
3029 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003030 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3031 ParseOptionalCommaAlignment(Alignment)) {
3032 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003033 }
3034 }
3035
3036 if (Size && Size->getType() != Type::Int32Ty)
3037 return Error(SizeLoc, "element count must be i32");
3038
3039 if (Opc == Instruction::Malloc)
3040 Inst = new MallocInst(Ty, Size, Alignment);
3041 else
3042 Inst = new AllocaInst(Ty, Size, Alignment);
3043 return false;
3044}
3045
3046/// ParseFree
3047/// ::= 'free' TypeAndValue
3048bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3049 Value *Val; LocTy Loc;
3050 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3051 if (!isa<PointerType>(Val->getType()))
3052 return Error(Loc, "operand to free must be a pointer");
3053 Inst = new FreeInst(Val);
3054 return false;
3055}
3056
3057/// ParseLoad
3058/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3059bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3060 bool isVolatile) {
3061 Value *Val; LocTy Loc;
3062 unsigned Alignment;
3063 if (ParseTypeAndValue(Val, Loc, PFS) ||
3064 ParseOptionalCommaAlignment(Alignment))
3065 return true;
3066
3067 if (!isa<PointerType>(Val->getType()) ||
3068 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3069 return Error(Loc, "load operand must be a pointer to a first class type");
3070
3071 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3072 return false;
3073}
3074
3075/// ParseStore
3076/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3077bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3078 bool isVolatile) {
3079 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3080 unsigned Alignment;
3081 if (ParseTypeAndValue(Val, Loc, PFS) ||
3082 ParseToken(lltok::comma, "expected ',' after store operand") ||
3083 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3084 ParseOptionalCommaAlignment(Alignment))
3085 return true;
3086
3087 if (!isa<PointerType>(Ptr->getType()))
3088 return Error(PtrLoc, "store operand must be a pointer");
3089 if (!Val->getType()->isFirstClassType())
3090 return Error(Loc, "store operand must be a first class value");
3091 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3092 return Error(Loc, "stored value and pointer type do not match");
3093
3094 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3095 return false;
3096}
3097
3098/// ParseGetResult
3099/// ::= 'getresult' TypeAndValue ',' uint
3100/// FIXME: Remove support for getresult in LLVM 3.0
3101bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3102 Value *Val; LocTy ValLoc, EltLoc;
3103 unsigned Element;
3104 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3105 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003106 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 return true;
3108
3109 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3110 return Error(ValLoc, "getresult inst requires an aggregate operand");
3111 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3112 return Error(EltLoc, "invalid getresult index for value");
3113 Inst = ExtractValueInst::Create(Val, Element);
3114 return false;
3115}
3116
3117/// ParseGetElementPtr
3118/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3119bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3120 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003121 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003122
3123 if (!isa<PointerType>(Ptr->getType()))
3124 return Error(Loc, "base of getelementptr must be a pointer");
3125
3126 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003127 while (EatIfPresent(lltok::comma)) {
3128 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003129 if (!isa<IntegerType>(Val->getType()))
3130 return Error(EltLoc, "getelementptr index must be an integer");
3131 Indices.push_back(Val);
3132 }
3133
3134 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3135 Indices.begin(), Indices.end()))
3136 return Error(Loc, "invalid getelementptr indices");
3137 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3138 return false;
3139}
3140
3141/// ParseExtractValue
3142/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3143bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3144 Value *Val; LocTy Loc;
3145 SmallVector<unsigned, 4> Indices;
3146 if (ParseTypeAndValue(Val, Loc, PFS) ||
3147 ParseIndexList(Indices))
3148 return true;
3149
3150 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3151 return Error(Loc, "extractvalue operand must be array or struct");
3152
3153 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3154 Indices.end()))
3155 return Error(Loc, "invalid indices for extractvalue");
3156 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3157 return false;
3158}
3159
3160/// ParseInsertValue
3161/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3162bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3163 Value *Val0, *Val1; LocTy Loc0, Loc1;
3164 SmallVector<unsigned, 4> Indices;
3165 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3166 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3167 ParseTypeAndValue(Val1, Loc1, PFS) ||
3168 ParseIndexList(Indices))
3169 return true;
3170
3171 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3172 return Error(Loc0, "extractvalue operand must be array or struct");
3173
3174 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3175 Indices.end()))
3176 return Error(Loc0, "invalid indices for insertvalue");
3177 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3178 return false;
3179}