blob: abddc59bde1549586ae6e6342a20248df846ab7b [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;
Duncan Sands35b51072009-02-10 16:24:55 +0000334 else {
335 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000336 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000337 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000338 Lex.Lex();
339 return false;
340}
341
342/// ParseNamedGlobal:
343/// GlobalVar '=' OptionalVisibility ALIAS ...
344/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
345bool LLParser::ParseNamedGlobal() {
346 assert(Lex.getKind() == lltok::GlobalVar);
347 LocTy NameLoc = Lex.getLoc();
348 std::string Name = Lex.getStrVal();
349 Lex.Lex();
350
351 bool HasLinkage;
352 unsigned Linkage, Visibility;
353 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
354 ParseOptionalLinkage(Linkage, HasLinkage) ||
355 ParseOptionalVisibility(Visibility))
356 return true;
357
358 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
359 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
360 return ParseAlias(Name, NameLoc, Visibility);
361}
362
363/// ParseAlias:
364/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
365/// Aliasee
366/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
367///
368/// Everything through visibility has already been parsed.
369///
370bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
371 unsigned Visibility) {
372 assert(Lex.getKind() == lltok::kw_alias);
373 Lex.Lex();
374 unsigned Linkage;
375 LocTy LinkageLoc = Lex.getLoc();
376 if (ParseOptionalLinkage(Linkage))
377 return true;
378
379 if (Linkage != GlobalValue::ExternalLinkage &&
380 Linkage != GlobalValue::WeakLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000381 Linkage != GlobalValue::InternalLinkage &&
382 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000383 return Error(LinkageLoc, "invalid linkage type for alias");
384
385 Constant *Aliasee;
386 LocTy AliaseeLoc = Lex.getLoc();
387 if (Lex.getKind() != lltok::kw_bitcast) {
388 if (ParseGlobalTypeAndValue(Aliasee)) return true;
389 } else {
390 // The bitcast dest type is not present, it is implied by the dest type.
391 ValID ID;
392 if (ParseValID(ID)) return true;
393 if (ID.Kind != ValID::t_Constant)
394 return Error(AliaseeLoc, "invalid aliasee");
395 Aliasee = ID.ConstantVal;
396 }
397
398 if (!isa<PointerType>(Aliasee->getType()))
399 return Error(AliaseeLoc, "alias must have pointer type");
400
401 // Okay, create the alias but do not insert it into the module yet.
402 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
403 (GlobalValue::LinkageTypes)Linkage, Name,
404 Aliasee);
405 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
406
407 // See if this value already exists in the symbol table. If so, it is either
408 // a redefinition or a definition of a forward reference.
409 if (GlobalValue *Val =
410 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
411 // See if this was a redefinition. If so, there is no entry in
412 // ForwardRefVals.
413 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
414 I = ForwardRefVals.find(Name);
415 if (I == ForwardRefVals.end())
416 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
417
418 // Otherwise, this was a definition of forward ref. Verify that types
419 // agree.
420 if (Val->getType() != GA->getType())
421 return Error(NameLoc,
422 "forward reference and definition of alias have different types");
423
424 // If they agree, just RAUW the old value with the alias and remove the
425 // forward ref info.
426 Val->replaceAllUsesWith(GA);
427 Val->eraseFromParent();
428 ForwardRefVals.erase(I);
429 }
430
431 // Insert into the module, we know its name won't collide now.
432 M->getAliasList().push_back(GA);
433 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
434
435 return false;
436}
437
438/// ParseGlobal
439/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
440/// OptionalAddrSpace GlobalType Type Const
441/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
442/// OptionalAddrSpace GlobalType Type Const
443///
444/// Everything through visibility has been parsed already.
445///
446bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
447 unsigned Linkage, bool HasLinkage,
448 unsigned Visibility) {
449 unsigned AddrSpace;
450 bool ThreadLocal, IsConstant;
451 LocTy TyLoc;
452
453 PATypeHolder Ty(Type::VoidTy);
454 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
455 ParseOptionalAddrSpace(AddrSpace) ||
456 ParseGlobalType(IsConstant) ||
457 ParseType(Ty, TyLoc))
458 return true;
459
460 // If the linkage is specified and is external, then no initializer is
461 // present.
462 Constant *Init = 0;
463 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
464 Linkage != GlobalValue::ExternalWeakLinkage &&
465 Linkage != GlobalValue::ExternalLinkage)) {
466 if (ParseGlobalValue(Ty, Init))
467 return true;
468 }
469
Chris Lattnerb4bd16f2009-02-08 19:56:22 +0000470 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || Ty == Type::VoidTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000471 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000472
473 GlobalVariable *GV = 0;
474
475 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000476 if (!Name.empty()) {
477 if ((GV = M->getGlobalVariable(Name, true)) &&
478 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000479 return Error(NameLoc, "redefinition of global '@" + Name + "'");
480 } else {
481 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
482 I = ForwardRefValIDs.find(NumberedVals.size());
483 if (I != ForwardRefValIDs.end()) {
484 GV = cast<GlobalVariable>(I->second.first);
485 ForwardRefValIDs.erase(I);
486 }
487 }
488
489 if (GV == 0) {
490 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
491 M, false, AddrSpace);
492 } else {
493 if (GV->getType()->getElementType() != Ty)
494 return Error(TyLoc,
495 "forward reference and definition of global have different types");
496
497 // Move the forward-reference to the correct spot in the module.
498 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
499 }
500
501 if (Name.empty())
502 NumberedVals.push_back(GV);
503
504 // Set the parsed properties on the global.
505 if (Init)
506 GV->setInitializer(Init);
507 GV->setConstant(IsConstant);
508 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
509 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
510 GV->setThreadLocal(ThreadLocal);
511
512 // Parse attributes on the global.
513 while (Lex.getKind() == lltok::comma) {
514 Lex.Lex();
515
516 if (Lex.getKind() == lltok::kw_section) {
517 Lex.Lex();
518 GV->setSection(Lex.getStrVal());
519 if (ParseToken(lltok::StringConstant, "expected global section string"))
520 return true;
521 } else if (Lex.getKind() == lltok::kw_align) {
522 unsigned Alignment;
523 if (ParseOptionalAlignment(Alignment)) return true;
524 GV->setAlignment(Alignment);
525 } else {
526 TokError("unknown global variable property!");
527 }
528 }
529
530 return false;
531}
532
533
534//===----------------------------------------------------------------------===//
535// GlobalValue Reference/Resolution Routines.
536//===----------------------------------------------------------------------===//
537
538/// GetGlobalVal - Get a value with the specified name or ID, creating a
539/// forward reference record if needed. This can return null if the value
540/// exists but does not have the right type.
541GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
542 LocTy Loc) {
543 const PointerType *PTy = dyn_cast<PointerType>(Ty);
544 if (PTy == 0) {
545 Error(Loc, "global variable reference must have pointer type");
546 return 0;
547 }
548
549 // Look this name up in the normal function symbol table.
550 GlobalValue *Val =
551 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
552
553 // If this is a forward reference for the value, see if we already created a
554 // forward ref record.
555 if (Val == 0) {
556 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
557 I = ForwardRefVals.find(Name);
558 if (I != ForwardRefVals.end())
559 Val = I->second.first;
560 }
561
562 // If we have the value in the symbol table or fwd-ref table, return it.
563 if (Val) {
564 if (Val->getType() == Ty) return Val;
565 Error(Loc, "'@" + Name + "' defined with type '" +
566 Val->getType()->getDescription() + "'");
567 return 0;
568 }
569
570 // Otherwise, create a new forward reference for this value and remember it.
571 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000572 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
573 // Function types can return opaque but functions can't.
574 if (isa<OpaqueType>(FT->getReturnType())) {
575 Error(Loc, "function may not return opaque type");
576 return 0;
577 }
578
Chris Lattnerdf986172009-01-02 07:01:27 +0000579 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000580 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000581 FwdVal = new GlobalVariable(PTy->getElementType(), false,
582 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000583 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000584
585 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
586 return FwdVal;
587}
588
589GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
590 const PointerType *PTy = dyn_cast<PointerType>(Ty);
591 if (PTy == 0) {
592 Error(Loc, "global variable reference must have pointer type");
593 return 0;
594 }
595
596 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
597
598 // If this is a forward reference for the value, see if we already created a
599 // forward ref record.
600 if (Val == 0) {
601 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
602 I = ForwardRefValIDs.find(ID);
603 if (I != ForwardRefValIDs.end())
604 Val = I->second.first;
605 }
606
607 // If we have the value in the symbol table or fwd-ref table, return it.
608 if (Val) {
609 if (Val->getType() == Ty) return Val;
610 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
611 Val->getType()->getDescription() + "'");
612 return 0;
613 }
614
615 // Otherwise, create a new forward reference for this value and remember it.
616 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000617 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
618 // Function types can return opaque but functions can't.
619 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000620 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000621 return 0;
622 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000623 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000624 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000625 FwdVal = new GlobalVariable(PTy->getElementType(), false,
626 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000627 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000628
629 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
630 return FwdVal;
631}
632
633
634//===----------------------------------------------------------------------===//
635// Helper Routines.
636//===----------------------------------------------------------------------===//
637
638/// ParseToken - If the current token has the specified kind, eat it and return
639/// success. Otherwise, emit the specified error and return failure.
640bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
641 if (Lex.getKind() != T)
642 return TokError(ErrMsg);
643 Lex.Lex();
644 return false;
645}
646
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000647/// ParseStringConstant
648/// ::= StringConstant
649bool LLParser::ParseStringConstant(std::string &Result) {
650 if (Lex.getKind() != lltok::StringConstant)
651 return TokError("expected string constant");
652 Result = Lex.getStrVal();
653 Lex.Lex();
654 return false;
655}
656
657/// ParseUInt32
658/// ::= uint32
659bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000660 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
661 return TokError("expected integer");
662 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
663 if (Val64 != unsigned(Val64))
664 return TokError("expected 32-bit integer (too large)");
665 Val = Val64;
666 Lex.Lex();
667 return false;
668}
669
670
671/// ParseOptionalAddrSpace
672/// := /*empty*/
673/// := 'addrspace' '(' uint32 ')'
674bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
675 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000676 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000679 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000680 ParseToken(lltok::rparen, "expected ')' in address space");
681}
682
683/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
684/// indicates what kind of attribute list this is: 0: function arg, 1: result,
685/// 2: function attr.
686bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687 Attrs = Attribute::None;
688 LocTy AttrLoc = Lex.getLoc();
689
690 while (1) {
691 switch (Lex.getKind()) {
692 case lltok::kw_sext:
693 case lltok::kw_zext:
694 // Treat these as signext/zeroext unless they are function attrs.
695 // FIXME: REMOVE THIS IN LLVM 3.0
696 if (AttrKind != 2) {
697 if (Lex.getKind() == lltok::kw_sext)
698 Attrs |= Attribute::SExt;
699 else
700 Attrs |= Attribute::ZExt;
701 break;
702 }
703 // FALL THROUGH.
704 default: // End of attributes.
705 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
706 return Error(AttrLoc, "invalid use of function-only attribute");
707
708 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
709 return Error(AttrLoc, "invalid use of parameter-only attribute");
710
711 return false;
712 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
713 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
714 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
715 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
716 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
717 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
718 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
719 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
720
721 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
722 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
723 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
724 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
725 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
726 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
727 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
728 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
729 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
730
731
732 case lltok::kw_align: {
733 unsigned Alignment;
734 if (ParseOptionalAlignment(Alignment))
735 return true;
736 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
737 continue;
738 }
739 }
740 Lex.Lex();
741 }
742}
743
744/// ParseOptionalLinkage
745/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000746/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000747/// ::= 'internal'
748/// ::= 'weak'
749/// ::= 'linkonce'
750/// ::= 'appending'
751/// ::= 'dllexport'
752/// ::= 'common'
753/// ::= 'dllimport'
754/// ::= 'extern_weak'
755/// ::= 'external'
756bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
757 HasLinkage = false;
758 switch (Lex.getKind()) {
759 default: Res = GlobalValue::ExternalLinkage; return false;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000760 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000761 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
762 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
763 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
764 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
765 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
766 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
767 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
768 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
769 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
770 }
771 Lex.Lex();
772 HasLinkage = true;
773 return false;
774}
775
776/// ParseOptionalVisibility
777/// ::= /*empty*/
778/// ::= 'default'
779/// ::= 'hidden'
780/// ::= 'protected'
781///
782bool LLParser::ParseOptionalVisibility(unsigned &Res) {
783 switch (Lex.getKind()) {
784 default: Res = GlobalValue::DefaultVisibility; return false;
785 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
786 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
787 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
788 }
789 Lex.Lex();
790 return false;
791}
792
793/// ParseOptionalCallingConv
794/// ::= /*empty*/
795/// ::= 'ccc'
796/// ::= 'fastcc'
797/// ::= 'coldcc'
798/// ::= 'x86_stdcallcc'
799/// ::= 'x86_fastcallcc'
800/// ::= 'cc' UINT
801///
802bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
803 switch (Lex.getKind()) {
804 default: CC = CallingConv::C; return false;
805 case lltok::kw_ccc: CC = CallingConv::C; break;
806 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
807 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
808 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
809 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000810 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000811 }
812 Lex.Lex();
813 return false;
814}
815
816/// ParseOptionalAlignment
817/// ::= /* empty */
818/// ::= 'align' 4
819bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
820 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000821 if (!EatIfPresent(lltok::kw_align))
822 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000823 LocTy AlignLoc = Lex.getLoc();
824 if (ParseUInt32(Alignment)) return true;
825 if (!isPowerOf2_32(Alignment))
826 return Error(AlignLoc, "alignment is not a power of two");
827 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000828}
829
830/// ParseOptionalCommaAlignment
831/// ::= /* empty */
832/// ::= ',' 'align' 4
833bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
834 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000835 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000836 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000837 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000838 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000839}
840
841/// ParseIndexList
842/// ::= (',' uint32)+
843bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
844 if (Lex.getKind() != lltok::comma)
845 return TokError("expected ',' as start of index list");
846
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000847 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000848 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000849 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000850 Indices.push_back(Idx);
851 }
852
853 return false;
854}
855
856//===----------------------------------------------------------------------===//
857// Type Parsing.
858//===----------------------------------------------------------------------===//
859
860/// ParseType - Parse and resolve a full type.
861bool LLParser::ParseType(PATypeHolder &Result) {
862 if (ParseTypeRec(Result)) return true;
863
864 // Verify no unresolved uprefs.
865 if (!UpRefs.empty())
866 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000867
868 return false;
869}
870
871/// HandleUpRefs - Every time we finish a new layer of types, this function is
872/// called. It loops through the UpRefs vector, which is a list of the
873/// currently active types. For each type, if the up-reference is contained in
874/// the newly completed type, we decrement the level count. When the level
875/// count reaches zero, the up-referenced type is the type that is passed in:
876/// thus we can complete the cycle.
877///
878PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
879 // If Ty isn't abstract, or if there are no up-references in it, then there is
880 // nothing to resolve here.
881 if (!ty->isAbstract() || UpRefs.empty()) return ty;
882
883 PATypeHolder Ty(ty);
884#if 0
885 errs() << "Type '" << Ty->getDescription()
886 << "' newly formed. Resolving upreferences.\n"
887 << UpRefs.size() << " upreferences active!\n";
888#endif
889
890 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
891 // to zero), we resolve them all together before we resolve them to Ty. At
892 // the end of the loop, if there is anything to resolve to Ty, it will be in
893 // this variable.
894 OpaqueType *TypeToResolve = 0;
895
896 for (unsigned i = 0; i != UpRefs.size(); ++i) {
897 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
898 bool ContainsType =
899 std::find(Ty->subtype_begin(), Ty->subtype_end(),
900 UpRefs[i].LastContainedTy) != Ty->subtype_end();
901
902#if 0
903 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
904 << UpRefs[i].LastContainedTy->getDescription() << ") = "
905 << (ContainsType ? "true" : "false")
906 << " level=" << UpRefs[i].NestingLevel << "\n";
907#endif
908 if (!ContainsType)
909 continue;
910
911 // Decrement level of upreference
912 unsigned Level = --UpRefs[i].NestingLevel;
913 UpRefs[i].LastContainedTy = Ty;
914
915 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
916 if (Level != 0)
917 continue;
918
919#if 0
920 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
921#endif
922 if (!TypeToResolve)
923 TypeToResolve = UpRefs[i].UpRefTy;
924 else
925 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
926 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
927 --i; // Do not skip the next element.
928 }
929
930 if (TypeToResolve)
931 TypeToResolve->refineAbstractTypeTo(Ty);
932
933 return Ty;
934}
935
936
937/// ParseTypeRec - The recursive function used to process the internal
938/// implementation details of types.
939bool LLParser::ParseTypeRec(PATypeHolder &Result) {
940 switch (Lex.getKind()) {
941 default:
942 return TokError("expected type");
943 case lltok::Type:
944 // TypeRec ::= 'float' | 'void' (etc)
945 Result = Lex.getTyVal();
946 Lex.Lex();
947 break;
948 case lltok::kw_opaque:
949 // TypeRec ::= 'opaque'
950 Result = OpaqueType::get();
951 Lex.Lex();
952 break;
953 case lltok::lbrace:
954 // TypeRec ::= '{' ... '}'
955 if (ParseStructType(Result, false))
956 return true;
957 break;
958 case lltok::lsquare:
959 // TypeRec ::= '[' ... ']'
960 Lex.Lex(); // eat the lsquare.
961 if (ParseArrayVectorType(Result, false))
962 return true;
963 break;
964 case lltok::less: // Either vector or packed struct.
965 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000966 Lex.Lex();
967 if (Lex.getKind() == lltok::lbrace) {
968 if (ParseStructType(Result, true) ||
969 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000970 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000971 } else if (ParseArrayVectorType(Result, true))
972 return true;
973 break;
974 case lltok::LocalVar:
975 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
976 // TypeRec ::= %foo
977 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
978 Result = T;
979 } else {
980 Result = OpaqueType::get();
981 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
982 std::make_pair(Result,
983 Lex.getLoc())));
984 M->addTypeName(Lex.getStrVal(), Result.get());
985 }
986 Lex.Lex();
987 break;
988
989 case lltok::LocalVarID:
990 // TypeRec ::= %4
991 if (Lex.getUIntVal() < NumberedTypes.size())
992 Result = NumberedTypes[Lex.getUIntVal()];
993 else {
994 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
995 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
996 if (I != ForwardRefTypeIDs.end())
997 Result = I->second.first;
998 else {
999 Result = OpaqueType::get();
1000 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1001 std::make_pair(Result,
1002 Lex.getLoc())));
1003 }
1004 }
1005 Lex.Lex();
1006 break;
1007 case lltok::backslash: {
1008 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001009 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001010 unsigned Val;
1011 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001012 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1013 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1014 Result = OT;
1015 break;
1016 }
1017 }
1018
1019 // Parse the type suffixes.
1020 while (1) {
1021 switch (Lex.getKind()) {
1022 // End of type.
1023 default: return false;
1024
1025 // TypeRec ::= TypeRec '*'
1026 case lltok::star:
1027 if (Result.get() == Type::LabelTy)
1028 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001029 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001030 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001031 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1032 Lex.Lex();
1033 break;
1034
1035 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1036 case lltok::kw_addrspace: {
1037 if (Result.get() == Type::LabelTy)
1038 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001039 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001040 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001041 unsigned AddrSpace;
1042 if (ParseOptionalAddrSpace(AddrSpace) ||
1043 ParseToken(lltok::star, "expected '*' in address space"))
1044 return true;
1045
1046 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1047 break;
1048 }
1049
1050 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1051 case lltok::lparen:
1052 if (ParseFunctionType(Result))
1053 return true;
1054 break;
1055 }
1056 }
1057}
1058
1059/// ParseParameterList
1060/// ::= '(' ')'
1061/// ::= '(' Arg (',' Arg)* ')'
1062/// Arg
1063/// ::= Type OptionalAttributes Value OptionalAttributes
1064bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1065 PerFunctionState &PFS) {
1066 if (ParseToken(lltok::lparen, "expected '(' in call"))
1067 return true;
1068
1069 while (Lex.getKind() != lltok::rparen) {
1070 // If this isn't the first argument, we need a comma.
1071 if (!ArgList.empty() &&
1072 ParseToken(lltok::comma, "expected ',' in argument list"))
1073 return true;
1074
1075 // Parse the argument.
1076 LocTy ArgLoc;
1077 PATypeHolder ArgTy(Type::VoidTy);
1078 unsigned ArgAttrs1, ArgAttrs2;
1079 Value *V;
1080 if (ParseType(ArgTy, ArgLoc) ||
1081 ParseOptionalAttrs(ArgAttrs1, 0) ||
1082 ParseValue(ArgTy, V, PFS) ||
1083 // FIXME: Should not allow attributes after the argument, remove this in
1084 // LLVM 3.0.
1085 ParseOptionalAttrs(ArgAttrs2, 0))
1086 return true;
1087 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1088 }
1089
1090 Lex.Lex(); // Lex the ')'.
1091 return false;
1092}
1093
1094
1095
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001096/// ParseArgumentList - Parse the argument list for a function type or function
1097/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001098/// ::= '(' ArgTypeListI ')'
1099/// ArgTypeListI
1100/// ::= /*empty*/
1101/// ::= '...'
1102/// ::= ArgTypeList ',' '...'
1103/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001104///
Chris Lattnerdf986172009-01-02 07:01:27 +00001105bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001106 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001107 isVarArg = false;
1108 assert(Lex.getKind() == lltok::lparen);
1109 Lex.Lex(); // eat the (.
1110
1111 if (Lex.getKind() == lltok::rparen) {
1112 // empty
1113 } else if (Lex.getKind() == lltok::dotdotdot) {
1114 isVarArg = true;
1115 Lex.Lex();
1116 } else {
1117 LocTy TypeLoc = Lex.getLoc();
1118 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001119 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001121
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001122 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1123 // types (such as a function returning a pointer to itself). If parsing a
1124 // function prototype, we require fully resolved types.
1125 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001126 ParseOptionalAttrs(Attrs, 0)) return true;
1127
Chris Lattnerdf986172009-01-02 07:01:27 +00001128 if (Lex.getKind() == lltok::LocalVar ||
1129 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1130 Name = Lex.getStrVal();
1131 Lex.Lex();
1132 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001133
1134 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1135 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001136
1137 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1138
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001139 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001140 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001141 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001142 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001143 break;
1144 }
1145
1146 // Otherwise must be an argument type.
1147 TypeLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001148 if (ParseTypeRec(ArgTy) ||
1149 ParseOptionalAttrs(Attrs, 0)) return true;
1150
Chris Lattnerdf986172009-01-02 07:01:27 +00001151 if (Lex.getKind() == lltok::LocalVar ||
1152 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1153 Name = Lex.getStrVal();
1154 Lex.Lex();
1155 } else {
1156 Name = "";
1157 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001158
1159 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1160 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001161
1162 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1163 }
1164 }
1165
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001166 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001167}
1168
1169/// ParseFunctionType
1170/// ::= Type ArgumentList OptionalAttrs
1171bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1172 assert(Lex.getKind() == lltok::lparen);
1173
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001174 if (!FunctionType::isValidReturnType(Result))
1175 return TokError("invalid function return type");
1176
Chris Lattnerdf986172009-01-02 07:01:27 +00001177 std::vector<ArgInfo> ArgList;
1178 bool isVarArg;
1179 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001180 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001181 // FIXME: Allow, but ignore attributes on function types!
1182 // FIXME: Remove in LLVM 3.0
1183 ParseOptionalAttrs(Attrs, 2))
1184 return true;
1185
1186 // Reject names on the arguments lists.
1187 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1188 if (!ArgList[i].Name.empty())
1189 return Error(ArgList[i].Loc, "argument name invalid in function type");
1190 if (!ArgList[i].Attrs != 0) {
1191 // Allow but ignore attributes on function types; this permits
1192 // auto-upgrade.
1193 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1194 }
1195 }
1196
1197 std::vector<const Type*> ArgListTy;
1198 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1199 ArgListTy.push_back(ArgList[i].Type);
1200
1201 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1202 return false;
1203}
1204
1205/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1206/// TypeRec
1207/// ::= '{' '}'
1208/// ::= '{' TypeRec (',' TypeRec)* '}'
1209/// ::= '<' '{' '}' '>'
1210/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1211bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1212 assert(Lex.getKind() == lltok::lbrace);
1213 Lex.Lex(); // Consume the '{'
1214
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001215 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001217 return false;
1218 }
1219
1220 std::vector<PATypeHolder> ParamsList;
1221 if (ParseTypeRec(Result)) return true;
1222 ParamsList.push_back(Result);
1223
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001224 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 if (ParseTypeRec(Result)) return true;
1226 ParamsList.push_back(Result);
1227 }
1228
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001229 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1230 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001231
1232 std::vector<const Type*> ParamsListTy;
1233 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1234 ParamsListTy.push_back(ParamsList[i].get());
1235 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1236 return false;
1237}
1238
1239/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1240/// token has already been consumed.
1241/// TypeRec
1242/// ::= '[' APSINTVAL 'x' Types ']'
1243/// ::= '<' APSINTVAL 'x' Types '>'
1244bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1245 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1246 Lex.getAPSIntVal().getBitWidth() > 64)
1247 return TokError("expected number in address space");
1248
1249 LocTy SizeLoc = Lex.getLoc();
1250 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001251 Lex.Lex();
1252
1253 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1254 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001255
1256 LocTy TypeLoc = Lex.getLoc();
1257 PATypeHolder EltTy(Type::VoidTy);
1258 if (ParseTypeRec(EltTy)) return true;
1259
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001260 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1261 "expected end of sequential type"))
1262 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001263
1264 if (isVector) {
1265 if ((unsigned)Size != Size)
1266 return Error(SizeLoc, "size too large for vector");
1267 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1268 return Error(TypeLoc, "vector element type must be fp or integer");
1269 Result = VectorType::get(EltTy, unsigned(Size));
1270 } else {
1271 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1272 return Error(TypeLoc, "invalid array element type");
1273 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1274 }
1275 return false;
1276}
1277
1278//===----------------------------------------------------------------------===//
1279// Function Semantic Analysis.
1280//===----------------------------------------------------------------------===//
1281
1282LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1283 : P(p), F(f) {
1284
1285 // Insert unnamed arguments into the NumberedVals list.
1286 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1287 AI != E; ++AI)
1288 if (!AI->hasName())
1289 NumberedVals.push_back(AI);
1290}
1291
1292LLParser::PerFunctionState::~PerFunctionState() {
1293 // If there were any forward referenced non-basicblock values, delete them.
1294 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1295 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1296 if (!isa<BasicBlock>(I->second.first)) {
1297 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1298 ->getType()));
1299 delete I->second.first;
1300 I->second.first = 0;
1301 }
1302
1303 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1304 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1305 if (!isa<BasicBlock>(I->second.first)) {
1306 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1307 ->getType()));
1308 delete I->second.first;
1309 I->second.first = 0;
1310 }
1311}
1312
1313bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1314 if (!ForwardRefVals.empty())
1315 return P.Error(ForwardRefVals.begin()->second.second,
1316 "use of undefined value '%" + ForwardRefVals.begin()->first +
1317 "'");
1318 if (!ForwardRefValIDs.empty())
1319 return P.Error(ForwardRefValIDs.begin()->second.second,
1320 "use of undefined value '%" +
1321 utostr(ForwardRefValIDs.begin()->first) + "'");
1322 return false;
1323}
1324
1325
1326/// GetVal - Get a value with the specified name or ID, creating a
1327/// forward reference record if needed. This can return null if the value
1328/// exists but does not have the right type.
1329Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1330 const Type *Ty, LocTy Loc) {
1331 // Look this name up in the normal function symbol table.
1332 Value *Val = F.getValueSymbolTable().lookup(Name);
1333
1334 // If this is a forward reference for the value, see if we already created a
1335 // forward ref record.
1336 if (Val == 0) {
1337 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1338 I = ForwardRefVals.find(Name);
1339 if (I != ForwardRefVals.end())
1340 Val = I->second.first;
1341 }
1342
1343 // If we have the value in the symbol table or fwd-ref table, return it.
1344 if (Val) {
1345 if (Val->getType() == Ty) return Val;
1346 if (Ty == Type::LabelTy)
1347 P.Error(Loc, "'%" + Name + "' is not a basic block");
1348 else
1349 P.Error(Loc, "'%" + Name + "' defined with type '" +
1350 Val->getType()->getDescription() + "'");
1351 return 0;
1352 }
1353
1354 // Don't make placeholders with invalid type.
1355 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1356 P.Error(Loc, "invalid use of a non-first-class type");
1357 return 0;
1358 }
1359
1360 // Otherwise, create a new forward reference for this value and remember it.
1361 Value *FwdVal;
1362 if (Ty == Type::LabelTy)
1363 FwdVal = BasicBlock::Create(Name, &F);
1364 else
1365 FwdVal = new Argument(Ty, Name);
1366
1367 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1368 return FwdVal;
1369}
1370
1371Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1372 LocTy Loc) {
1373 // Look this name up in the normal function symbol table.
1374 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1375
1376 // If this is a forward reference for the value, see if we already created a
1377 // forward ref record.
1378 if (Val == 0) {
1379 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1380 I = ForwardRefValIDs.find(ID);
1381 if (I != ForwardRefValIDs.end())
1382 Val = I->second.first;
1383 }
1384
1385 // If we have the value in the symbol table or fwd-ref table, return it.
1386 if (Val) {
1387 if (Val->getType() == Ty) return Val;
1388 if (Ty == Type::LabelTy)
1389 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1390 else
1391 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1392 Val->getType()->getDescription() + "'");
1393 return 0;
1394 }
1395
1396 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1397 P.Error(Loc, "invalid use of a non-first-class type");
1398 return 0;
1399 }
1400
1401 // Otherwise, create a new forward reference for this value and remember it.
1402 Value *FwdVal;
1403 if (Ty == Type::LabelTy)
1404 FwdVal = BasicBlock::Create("", &F);
1405 else
1406 FwdVal = new Argument(Ty);
1407
1408 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1409 return FwdVal;
1410}
1411
1412/// SetInstName - After an instruction is parsed and inserted into its
1413/// basic block, this installs its name.
1414bool LLParser::PerFunctionState::SetInstName(int NameID,
1415 const std::string &NameStr,
1416 LocTy NameLoc, Instruction *Inst) {
1417 // If this instruction has void type, it cannot have a name or ID specified.
1418 if (Inst->getType() == Type::VoidTy) {
1419 if (NameID != -1 || !NameStr.empty())
1420 return P.Error(NameLoc, "instructions returning void cannot have a name");
1421 return false;
1422 }
1423
1424 // If this was a numbered instruction, verify that the instruction is the
1425 // expected value and resolve any forward references.
1426 if (NameStr.empty()) {
1427 // If neither a name nor an ID was specified, just use the next ID.
1428 if (NameID == -1)
1429 NameID = NumberedVals.size();
1430
1431 if (unsigned(NameID) != NumberedVals.size())
1432 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1433 utostr(NumberedVals.size()) + "'");
1434
1435 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1436 ForwardRefValIDs.find(NameID);
1437 if (FI != ForwardRefValIDs.end()) {
1438 if (FI->second.first->getType() != Inst->getType())
1439 return P.Error(NameLoc, "instruction forward referenced with type '" +
1440 FI->second.first->getType()->getDescription() + "'");
1441 FI->second.first->replaceAllUsesWith(Inst);
1442 ForwardRefValIDs.erase(FI);
1443 }
1444
1445 NumberedVals.push_back(Inst);
1446 return false;
1447 }
1448
1449 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1450 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1451 FI = ForwardRefVals.find(NameStr);
1452 if (FI != ForwardRefVals.end()) {
1453 if (FI->second.first->getType() != Inst->getType())
1454 return P.Error(NameLoc, "instruction forward referenced with type '" +
1455 FI->second.first->getType()->getDescription() + "'");
1456 FI->second.first->replaceAllUsesWith(Inst);
1457 ForwardRefVals.erase(FI);
1458 }
1459
1460 // Set the name on the instruction.
1461 Inst->setName(NameStr);
1462
1463 if (Inst->getNameStr() != NameStr)
1464 return P.Error(NameLoc, "multiple definition of local value named '" +
1465 NameStr + "'");
1466 return false;
1467}
1468
1469/// GetBB - Get a basic block with the specified name or ID, creating a
1470/// forward reference record if needed.
1471BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1472 LocTy Loc) {
1473 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1474}
1475
1476BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1477 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1478}
1479
1480/// DefineBB - Define the specified basic block, which is either named or
1481/// unnamed. If there is an error, this returns null otherwise it returns
1482/// the block being defined.
1483BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1484 LocTy Loc) {
1485 BasicBlock *BB;
1486 if (Name.empty())
1487 BB = GetBB(NumberedVals.size(), Loc);
1488 else
1489 BB = GetBB(Name, Loc);
1490 if (BB == 0) return 0; // Already diagnosed error.
1491
1492 // Move the block to the end of the function. Forward ref'd blocks are
1493 // inserted wherever they happen to be referenced.
1494 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1495
1496 // Remove the block from forward ref sets.
1497 if (Name.empty()) {
1498 ForwardRefValIDs.erase(NumberedVals.size());
1499 NumberedVals.push_back(BB);
1500 } else {
1501 // BB forward references are already in the function symbol table.
1502 ForwardRefVals.erase(Name);
1503 }
1504
1505 return BB;
1506}
1507
1508//===----------------------------------------------------------------------===//
1509// Constants.
1510//===----------------------------------------------------------------------===//
1511
1512/// ParseValID - Parse an abstract value that doesn't necessarily have a
1513/// type implied. For example, if we parse "4" we don't know what integer type
1514/// it has. The value will later be combined with its type and checked for
1515/// sanity.
1516bool LLParser::ParseValID(ValID &ID) {
1517 ID.Loc = Lex.getLoc();
1518 switch (Lex.getKind()) {
1519 default: return TokError("expected value token");
1520 case lltok::GlobalID: // @42
1521 ID.UIntVal = Lex.getUIntVal();
1522 ID.Kind = ValID::t_GlobalID;
1523 break;
1524 case lltok::GlobalVar: // @foo
1525 ID.StrVal = Lex.getStrVal();
1526 ID.Kind = ValID::t_GlobalName;
1527 break;
1528 case lltok::LocalVarID: // %42
1529 ID.UIntVal = Lex.getUIntVal();
1530 ID.Kind = ValID::t_LocalID;
1531 break;
1532 case lltok::LocalVar: // %foo
1533 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1534 ID.StrVal = Lex.getStrVal();
1535 ID.Kind = ValID::t_LocalName;
1536 break;
1537 case lltok::APSInt:
1538 ID.APSIntVal = Lex.getAPSIntVal();
1539 ID.Kind = ValID::t_APSInt;
1540 break;
1541 case lltok::APFloat:
1542 ID.APFloatVal = Lex.getAPFloatVal();
1543 ID.Kind = ValID::t_APFloat;
1544 break;
1545 case lltok::kw_true:
1546 ID.ConstantVal = ConstantInt::getTrue();
1547 ID.Kind = ValID::t_Constant;
1548 break;
1549 case lltok::kw_false:
1550 ID.ConstantVal = ConstantInt::getFalse();
1551 ID.Kind = ValID::t_Constant;
1552 break;
1553 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1554 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1555 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1556
1557 case lltok::lbrace: {
1558 // ValID ::= '{' ConstVector '}'
1559 Lex.Lex();
1560 SmallVector<Constant*, 16> Elts;
1561 if (ParseGlobalValueVector(Elts) ||
1562 ParseToken(lltok::rbrace, "expected end of struct constant"))
1563 return true;
1564
1565 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1566 ID.Kind = ValID::t_Constant;
1567 return false;
1568 }
1569 case lltok::less: {
1570 // ValID ::= '<' ConstVector '>' --> Vector.
1571 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1572 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001573 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001574
1575 SmallVector<Constant*, 16> Elts;
1576 LocTy FirstEltLoc = Lex.getLoc();
1577 if (ParseGlobalValueVector(Elts) ||
1578 (isPackedStruct &&
1579 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1580 ParseToken(lltok::greater, "expected end of constant"))
1581 return true;
1582
1583 if (isPackedStruct) {
1584 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1585 ID.Kind = ValID::t_Constant;
1586 return false;
1587 }
1588
1589 if (Elts.empty())
1590 return Error(ID.Loc, "constant vector must not be empty");
1591
1592 if (!Elts[0]->getType()->isInteger() &&
1593 !Elts[0]->getType()->isFloatingPoint())
1594 return Error(FirstEltLoc,
1595 "vector elements must have integer or floating point type");
1596
1597 // Verify that all the vector elements have the same type.
1598 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1599 if (Elts[i]->getType() != Elts[0]->getType())
1600 return Error(FirstEltLoc,
1601 "vector element #" + utostr(i) +
1602 " is not of type '" + Elts[0]->getType()->getDescription());
1603
1604 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1605 ID.Kind = ValID::t_Constant;
1606 return false;
1607 }
1608 case lltok::lsquare: { // Array Constant
1609 Lex.Lex();
1610 SmallVector<Constant*, 16> Elts;
1611 LocTy FirstEltLoc = Lex.getLoc();
1612 if (ParseGlobalValueVector(Elts) ||
1613 ParseToken(lltok::rsquare, "expected end of array constant"))
1614 return true;
1615
1616 // Handle empty element.
1617 if (Elts.empty()) {
1618 // Use undef instead of an array because it's inconvenient to determine
1619 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001620 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001621 return false;
1622 }
1623
1624 if (!Elts[0]->getType()->isFirstClassType())
1625 return Error(FirstEltLoc, "invalid array element type: " +
1626 Elts[0]->getType()->getDescription());
1627
1628 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1629
1630 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001631 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001632 if (Elts[i]->getType() != Elts[0]->getType())
1633 return Error(FirstEltLoc,
1634 "array element #" + utostr(i) +
1635 " is not of type '" +Elts[0]->getType()->getDescription());
1636 }
1637
1638 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1639 ID.Kind = ValID::t_Constant;
1640 return false;
1641 }
1642 case lltok::kw_c: // c "foo"
1643 Lex.Lex();
1644 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1645 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1646 ID.Kind = ValID::t_Constant;
1647 return false;
1648
1649 case lltok::kw_asm: {
1650 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1651 bool HasSideEffect;
1652 Lex.Lex();
1653 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001654 ParseStringConstant(ID.StrVal) ||
1655 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001656 ParseToken(lltok::StringConstant, "expected constraint string"))
1657 return true;
1658 ID.StrVal2 = Lex.getStrVal();
1659 ID.UIntVal = HasSideEffect;
1660 ID.Kind = ValID::t_InlineAsm;
1661 return false;
1662 }
1663
1664 case lltok::kw_trunc:
1665 case lltok::kw_zext:
1666 case lltok::kw_sext:
1667 case lltok::kw_fptrunc:
1668 case lltok::kw_fpext:
1669 case lltok::kw_bitcast:
1670 case lltok::kw_uitofp:
1671 case lltok::kw_sitofp:
1672 case lltok::kw_fptoui:
1673 case lltok::kw_fptosi:
1674 case lltok::kw_inttoptr:
1675 case lltok::kw_ptrtoint: {
1676 unsigned Opc = Lex.getUIntVal();
1677 PATypeHolder DestTy(Type::VoidTy);
1678 Constant *SrcVal;
1679 Lex.Lex();
1680 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1681 ParseGlobalTypeAndValue(SrcVal) ||
1682 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1683 ParseType(DestTy) ||
1684 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1685 return true;
1686 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1687 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1688 SrcVal->getType()->getDescription() + "' to '" +
1689 DestTy->getDescription() + "'");
1690 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1691 DestTy);
1692 ID.Kind = ValID::t_Constant;
1693 return false;
1694 }
1695 case lltok::kw_extractvalue: {
1696 Lex.Lex();
1697 Constant *Val;
1698 SmallVector<unsigned, 4> Indices;
1699 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1700 ParseGlobalTypeAndValue(Val) ||
1701 ParseIndexList(Indices) ||
1702 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1703 return true;
1704 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1705 return Error(ID.Loc, "extractvalue operand must be array or struct");
1706 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1707 Indices.end()))
1708 return Error(ID.Loc, "invalid indices for extractvalue");
1709 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1710 &Indices[0], Indices.size());
1711 ID.Kind = ValID::t_Constant;
1712 return false;
1713 }
1714 case lltok::kw_insertvalue: {
1715 Lex.Lex();
1716 Constant *Val0, *Val1;
1717 SmallVector<unsigned, 4> Indices;
1718 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1719 ParseGlobalTypeAndValue(Val0) ||
1720 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1721 ParseGlobalTypeAndValue(Val1) ||
1722 ParseIndexList(Indices) ||
1723 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1724 return true;
1725 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1726 return Error(ID.Loc, "extractvalue operand must be array or struct");
1727 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1728 Indices.end()))
1729 return Error(ID.Loc, "invalid indices for insertvalue");
1730 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1731 &Indices[0], Indices.size());
1732 ID.Kind = ValID::t_Constant;
1733 return false;
1734 }
1735 case lltok::kw_icmp:
1736 case lltok::kw_fcmp:
1737 case lltok::kw_vicmp:
1738 case lltok::kw_vfcmp: {
1739 unsigned PredVal, Opc = Lex.getUIntVal();
1740 Constant *Val0, *Val1;
1741 Lex.Lex();
1742 if (ParseCmpPredicate(PredVal, Opc) ||
1743 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1744 ParseGlobalTypeAndValue(Val0) ||
1745 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1746 ParseGlobalTypeAndValue(Val1) ||
1747 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1748 return true;
1749
1750 if (Val0->getType() != Val1->getType())
1751 return Error(ID.Loc, "compare operands must have the same type");
1752
1753 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1754
1755 if (Opc == Instruction::FCmp) {
1756 if (!Val0->getType()->isFPOrFPVector())
1757 return Error(ID.Loc, "fcmp requires floating point operands");
1758 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1759 } else if (Opc == Instruction::ICmp) {
1760 if (!Val0->getType()->isIntOrIntVector() &&
1761 !isa<PointerType>(Val0->getType()))
1762 return Error(ID.Loc, "icmp requires pointer or integer operands");
1763 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1764 } else if (Opc == Instruction::VFCmp) {
1765 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001766 if (!Val0->getType()->isFPOrFPVector() ||
1767 !isa<VectorType>(Val0->getType()))
1768 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1770 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001771 // FIXME: REMOVE VICMP Support
1772 if (!Val0->getType()->isIntOrIntVector() ||
1773 !isa<VectorType>(Val0->getType()))
1774 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001775 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1776 }
1777 ID.Kind = ValID::t_Constant;
1778 return false;
1779 }
1780
1781 // Binary Operators.
1782 case lltok::kw_add:
1783 case lltok::kw_sub:
1784 case lltok::kw_mul:
1785 case lltok::kw_udiv:
1786 case lltok::kw_sdiv:
1787 case lltok::kw_fdiv:
1788 case lltok::kw_urem:
1789 case lltok::kw_srem:
1790 case lltok::kw_frem: {
1791 unsigned Opc = Lex.getUIntVal();
1792 Constant *Val0, *Val1;
1793 Lex.Lex();
1794 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1795 ParseGlobalTypeAndValue(Val0) ||
1796 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1797 ParseGlobalTypeAndValue(Val1) ||
1798 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1799 return true;
1800 if (Val0->getType() != Val1->getType())
1801 return Error(ID.Loc, "operands of constexpr must have same type");
1802 if (!Val0->getType()->isIntOrIntVector() &&
1803 !Val0->getType()->isFPOrFPVector())
1804 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1805 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1806 ID.Kind = ValID::t_Constant;
1807 return false;
1808 }
1809
1810 // Logical Operations
1811 case lltok::kw_shl:
1812 case lltok::kw_lshr:
1813 case lltok::kw_ashr:
1814 case lltok::kw_and:
1815 case lltok::kw_or:
1816 case lltok::kw_xor: {
1817 unsigned Opc = Lex.getUIntVal();
1818 Constant *Val0, *Val1;
1819 Lex.Lex();
1820 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1821 ParseGlobalTypeAndValue(Val0) ||
1822 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1823 ParseGlobalTypeAndValue(Val1) ||
1824 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1825 return true;
1826 if (Val0->getType() != Val1->getType())
1827 return Error(ID.Loc, "operands of constexpr must have same type");
1828 if (!Val0->getType()->isIntOrIntVector())
1829 return Error(ID.Loc,
1830 "constexpr requires integer or integer vector operands");
1831 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1832 ID.Kind = ValID::t_Constant;
1833 return false;
1834 }
1835
1836 case lltok::kw_getelementptr:
1837 case lltok::kw_shufflevector:
1838 case lltok::kw_insertelement:
1839 case lltok::kw_extractelement:
1840 case lltok::kw_select: {
1841 unsigned Opc = Lex.getUIntVal();
1842 SmallVector<Constant*, 16> Elts;
1843 Lex.Lex();
1844 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1845 ParseGlobalValueVector(Elts) ||
1846 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1847 return true;
1848
1849 if (Opc == Instruction::GetElementPtr) {
1850 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1851 return Error(ID.Loc, "getelementptr requires pointer operand");
1852
1853 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1854 (Value**)&Elts[1], Elts.size()-1))
1855 return Error(ID.Loc, "invalid indices for getelementptr");
1856 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1857 &Elts[1], Elts.size()-1);
1858 } else if (Opc == Instruction::Select) {
1859 if (Elts.size() != 3)
1860 return Error(ID.Loc, "expected three operands to select");
1861 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1862 Elts[2]))
1863 return Error(ID.Loc, Reason);
1864 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1865 } else if (Opc == Instruction::ShuffleVector) {
1866 if (Elts.size() != 3)
1867 return Error(ID.Loc, "expected three operands to shufflevector");
1868 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1869 return Error(ID.Loc, "invalid operands to shufflevector");
1870 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1871 } else if (Opc == Instruction::ExtractElement) {
1872 if (Elts.size() != 2)
1873 return Error(ID.Loc, "expected two operands to extractelement");
1874 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1875 return Error(ID.Loc, "invalid extractelement operands");
1876 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1877 } else {
1878 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1879 if (Elts.size() != 3)
1880 return Error(ID.Loc, "expected three operands to insertelement");
1881 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1882 return Error(ID.Loc, "invalid insertelement operands");
1883 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1884 }
1885
1886 ID.Kind = ValID::t_Constant;
1887 return false;
1888 }
1889 }
1890
1891 Lex.Lex();
1892 return false;
1893}
1894
1895/// ParseGlobalValue - Parse a global value with the specified type.
1896bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1897 V = 0;
1898 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001899 return ParseValID(ID) ||
1900 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001901}
1902
1903/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1904/// constant.
1905bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1906 Constant *&V) {
1907 if (isa<FunctionType>(Ty))
1908 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1909
1910 switch (ID.Kind) {
1911 default: assert(0 && "Unknown ValID!");
1912 case ValID::t_LocalID:
1913 case ValID::t_LocalName:
1914 return Error(ID.Loc, "invalid use of function-local name");
1915 case ValID::t_InlineAsm:
1916 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1917 case ValID::t_GlobalName:
1918 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1919 return V == 0;
1920 case ValID::t_GlobalID:
1921 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1922 return V == 0;
1923 case ValID::t_APSInt:
1924 if (!isa<IntegerType>(Ty))
1925 return Error(ID.Loc, "integer constant must have integer type");
1926 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1927 V = ConstantInt::get(ID.APSIntVal);
1928 return false;
1929 case ValID::t_APFloat:
1930 if (!Ty->isFloatingPoint() ||
1931 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1932 return Error(ID.Loc, "floating point constant invalid for type");
1933
1934 // The lexer has no type info, so builds all float and double FP constants
1935 // as double. Fix this here. Long double does not need this.
1936 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1937 Ty == Type::FloatTy) {
1938 bool Ignored;
1939 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1940 &Ignored);
1941 }
1942 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001943
1944 if (V->getType() != Ty)
1945 return Error(ID.Loc, "floating point constant does not have type '" +
1946 Ty->getDescription() + "'");
1947
Chris Lattnerdf986172009-01-02 07:01:27 +00001948 return false;
1949 case ValID::t_Null:
1950 if (!isa<PointerType>(Ty))
1951 return Error(ID.Loc, "null must be a pointer type");
1952 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1953 return false;
1954 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001955 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00001956 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1957 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001958 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 V = UndefValue::get(Ty);
1960 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00001961 case ValID::t_EmptyArray:
1962 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1963 return Error(ID.Loc, "invalid empty array initializer");
1964 V = UndefValue::get(Ty);
1965 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001967 // FIXME: LabelTy should not be a first-class type.
1968 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 return Error(ID.Loc, "invalid type for null constant");
1970 V = Constant::getNullValue(Ty);
1971 return false;
1972 case ValID::t_Constant:
1973 if (ID.ConstantVal->getType() != Ty)
1974 return Error(ID.Loc, "constant expression type mismatch");
1975 V = ID.ConstantVal;
1976 return false;
1977 }
1978}
1979
1980bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1981 PATypeHolder Type(Type::VoidTy);
1982 return ParseType(Type) ||
1983 ParseGlobalValue(Type, V);
1984}
1985
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001986/// ParseGlobalValueVector
1987/// ::= /*empty*/
1988/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00001989bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1990 // Empty list.
1991 if (Lex.getKind() == lltok::rbrace ||
1992 Lex.getKind() == lltok::rsquare ||
1993 Lex.getKind() == lltok::greater ||
1994 Lex.getKind() == lltok::rparen)
1995 return false;
1996
1997 Constant *C;
1998 if (ParseGlobalTypeAndValue(C)) return true;
1999 Elts.push_back(C);
2000
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002001 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 if (ParseGlobalTypeAndValue(C)) return true;
2003 Elts.push_back(C);
2004 }
2005
2006 return false;
2007}
2008
2009
2010//===----------------------------------------------------------------------===//
2011// Function Parsing.
2012//===----------------------------------------------------------------------===//
2013
2014bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2015 PerFunctionState &PFS) {
2016 if (ID.Kind == ValID::t_LocalID)
2017 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2018 else if (ID.Kind == ValID::t_LocalName)
2019 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002020 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2022 const FunctionType *FTy =
2023 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2024 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2025 return Error(ID.Loc, "invalid type for inline asm constraint string");
2026 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2027 return false;
2028 } else {
2029 Constant *C;
2030 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2031 V = C;
2032 return false;
2033 }
2034
2035 return V == 0;
2036}
2037
2038bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2039 V = 0;
2040 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002041 return ParseValID(ID) ||
2042 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002043}
2044
2045bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2046 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002047 return ParseType(T) ||
2048 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002049}
2050
2051/// FunctionHeader
2052/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2053/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2054/// OptionalAlign OptGC
2055bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2056 // Parse the linkage.
2057 LocTy LinkageLoc = Lex.getLoc();
2058 unsigned Linkage;
2059
2060 unsigned Visibility, CC, RetAttrs;
2061 PATypeHolder RetType(Type::VoidTy);
2062 LocTy RetTypeLoc = Lex.getLoc();
2063 if (ParseOptionalLinkage(Linkage) ||
2064 ParseOptionalVisibility(Visibility) ||
2065 ParseOptionalCallingConv(CC) ||
2066 ParseOptionalAttrs(RetAttrs, 1) ||
2067 ParseType(RetType, RetTypeLoc))
2068 return true;
2069
2070 // Verify that the linkage is ok.
2071 switch ((GlobalValue::LinkageTypes)Linkage) {
2072 case GlobalValue::ExternalLinkage:
2073 break; // always ok.
2074 case GlobalValue::DLLImportLinkage:
2075 case GlobalValue::ExternalWeakLinkage:
2076 if (isDefine)
2077 return Error(LinkageLoc, "invalid linkage for function definition");
2078 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002079 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 case GlobalValue::InternalLinkage:
2081 case GlobalValue::LinkOnceLinkage:
2082 case GlobalValue::WeakLinkage:
2083 case GlobalValue::DLLExportLinkage:
2084 if (!isDefine)
2085 return Error(LinkageLoc, "invalid linkage for function declaration");
2086 break;
2087 case GlobalValue::AppendingLinkage:
2088 case GlobalValue::GhostLinkage:
2089 case GlobalValue::CommonLinkage:
2090 return Error(LinkageLoc, "invalid function linkage type");
2091 }
2092
Chris Lattner99bb3152009-01-05 08:00:30 +00002093 if (!FunctionType::isValidReturnType(RetType) ||
2094 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 return Error(RetTypeLoc, "invalid function return type");
2096
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002098
2099 std::string FunctionName;
2100 if (Lex.getKind() == lltok::GlobalVar) {
2101 FunctionName = Lex.getStrVal();
2102 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2103 unsigned NameID = Lex.getUIntVal();
2104
2105 if (NameID != NumberedVals.size())
2106 return TokError("function expected to be numbered '%" +
2107 utostr(NumberedVals.size()) + "'");
2108 } else {
2109 return TokError("expected function name");
2110 }
2111
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002112 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002113
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002114 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002115 return TokError("expected '(' in function argument list");
2116
2117 std::vector<ArgInfo> ArgList;
2118 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002120 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002122 std::string GC;
2123
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002124 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002125 ParseOptionalAttrs(FuncAttrs, 2) ||
2126 (EatIfPresent(lltok::kw_section) &&
2127 ParseStringConstant(Section)) ||
2128 ParseOptionalAlignment(Alignment) ||
2129 (EatIfPresent(lltok::kw_gc) &&
2130 ParseStringConstant(GC)))
2131 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002132
2133 // If the alignment was parsed as an attribute, move to the alignment field.
2134 if (FuncAttrs & Attribute::Alignment) {
2135 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2136 FuncAttrs &= ~Attribute::Alignment;
2137 }
2138
Chris Lattnerdf986172009-01-02 07:01:27 +00002139 // Okay, if we got here, the function is syntactically valid. Convert types
2140 // and do semantic checks.
2141 std::vector<const Type*> ParamTypeList;
2142 SmallVector<AttributeWithIndex, 8> Attrs;
2143 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2144 // attributes.
2145 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2146 if (FuncAttrs & ObsoleteFuncAttrs) {
2147 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2148 FuncAttrs &= ~ObsoleteFuncAttrs;
2149 }
2150
2151 if (RetAttrs != Attribute::None)
2152 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2153
2154 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2155 ParamTypeList.push_back(ArgList[i].Type);
2156 if (ArgList[i].Attrs != Attribute::None)
2157 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2158 }
2159
2160 if (FuncAttrs != Attribute::None)
2161 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2162
2163 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2164
2165 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2166 const PointerType *PFT = PointerType::getUnqual(FT);
2167
2168 Fn = 0;
2169 if (!FunctionName.empty()) {
2170 // If this was a definition of a forward reference, remove the definition
2171 // from the forward reference table and fill in the forward ref.
2172 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2173 ForwardRefVals.find(FunctionName);
2174 if (FRVI != ForwardRefVals.end()) {
2175 Fn = M->getFunction(FunctionName);
2176 ForwardRefVals.erase(FRVI);
2177 } else if ((Fn = M->getFunction(FunctionName))) {
2178 // If this function already exists in the symbol table, then it is
2179 // multiply defined. We accept a few cases for old backwards compat.
2180 // FIXME: Remove this stuff for LLVM 3.0.
2181 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2182 (!Fn->isDeclaration() && isDefine)) {
2183 // If the redefinition has different type or different attributes,
2184 // reject it. If both have bodies, reject it.
2185 return Error(NameLoc, "invalid redefinition of function '" +
2186 FunctionName + "'");
2187 } else if (Fn->isDeclaration()) {
2188 // Make sure to strip off any argument names so we can't get conflicts.
2189 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2190 AI != AE; ++AI)
2191 AI->setName("");
2192 }
2193 }
2194
2195 } else if (FunctionName.empty()) {
2196 // If this is a definition of a forward referenced function, make sure the
2197 // types agree.
2198 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2199 = ForwardRefValIDs.find(NumberedVals.size());
2200 if (I != ForwardRefValIDs.end()) {
2201 Fn = cast<Function>(I->second.first);
2202 if (Fn->getType() != PFT)
2203 return Error(NameLoc, "type of definition and forward reference of '@" +
2204 utostr(NumberedVals.size()) +"' disagree");
2205 ForwardRefValIDs.erase(I);
2206 }
2207 }
2208
2209 if (Fn == 0)
2210 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2211 else // Move the forward-reference to the correct spot in the module.
2212 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2213
2214 if (FunctionName.empty())
2215 NumberedVals.push_back(Fn);
2216
2217 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2218 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2219 Fn->setCallingConv(CC);
2220 Fn->setAttributes(PAL);
2221 Fn->setAlignment(Alignment);
2222 Fn->setSection(Section);
2223 if (!GC.empty()) Fn->setGC(GC.c_str());
2224
2225 // Add all of the arguments we parsed to the function.
2226 Function::arg_iterator ArgIt = Fn->arg_begin();
2227 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2228 // If the argument has a name, insert it into the argument symbol table.
2229 if (ArgList[i].Name.empty()) continue;
2230
2231 // Set the name, if it conflicted, it will be auto-renamed.
2232 ArgIt->setName(ArgList[i].Name);
2233
2234 if (ArgIt->getNameStr() != ArgList[i].Name)
2235 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2236 ArgList[i].Name + "'");
2237 }
2238
2239 return false;
2240}
2241
2242
2243/// ParseFunctionBody
2244/// ::= '{' BasicBlock+ '}'
2245/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2246///
2247bool LLParser::ParseFunctionBody(Function &Fn) {
2248 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2249 return TokError("expected '{' in function body");
2250 Lex.Lex(); // eat the {.
2251
2252 PerFunctionState PFS(*this, Fn);
2253
2254 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2255 if (ParseBasicBlock(PFS)) return true;
2256
2257 // Eat the }.
2258 Lex.Lex();
2259
2260 // Verify function is ok.
2261 return PFS.VerifyFunctionComplete();
2262}
2263
2264/// ParseBasicBlock
2265/// ::= LabelStr? Instruction*
2266bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2267 // If this basic block starts out with a name, remember it.
2268 std::string Name;
2269 LocTy NameLoc = Lex.getLoc();
2270 if (Lex.getKind() == lltok::LabelStr) {
2271 Name = Lex.getStrVal();
2272 Lex.Lex();
2273 }
2274
2275 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2276 if (BB == 0) return true;
2277
2278 std::string NameStr;
2279
2280 // Parse the instructions in this block until we get a terminator.
2281 Instruction *Inst;
2282 do {
2283 // This instruction may have three possibilities for a name: a) none
2284 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2285 LocTy NameLoc = Lex.getLoc();
2286 int NameID = -1;
2287 NameStr = "";
2288
2289 if (Lex.getKind() == lltok::LocalVarID) {
2290 NameID = Lex.getUIntVal();
2291 Lex.Lex();
2292 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2293 return true;
2294 } else if (Lex.getKind() == lltok::LocalVar ||
2295 // FIXME: REMOVE IN LLVM 3.0
2296 Lex.getKind() == lltok::StringConstant) {
2297 NameStr = Lex.getStrVal();
2298 Lex.Lex();
2299 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2300 return true;
2301 }
2302
2303 if (ParseInstruction(Inst, BB, PFS)) return true;
2304
2305 BB->getInstList().push_back(Inst);
2306
2307 // Set the name on the instruction.
2308 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2309 } while (!isa<TerminatorInst>(Inst));
2310
2311 return false;
2312}
2313
2314//===----------------------------------------------------------------------===//
2315// Instruction Parsing.
2316//===----------------------------------------------------------------------===//
2317
2318/// ParseInstruction - Parse one of the many different instructions.
2319///
2320bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2321 PerFunctionState &PFS) {
2322 lltok::Kind Token = Lex.getKind();
2323 if (Token == lltok::Eof)
2324 return TokError("found end of file when expecting more instructions");
2325 LocTy Loc = Lex.getLoc();
2326 Lex.Lex(); // Eat the keyword.
2327
2328 switch (Token) {
2329 default: return Error(Loc, "expected instruction opcode");
2330 // Terminator Instructions.
2331 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2332 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2333 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2334 case lltok::kw_br: return ParseBr(Inst, PFS);
2335 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2336 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2337 // Binary Operators.
2338 case lltok::kw_add:
2339 case lltok::kw_sub:
Chris Lattnere914b592009-01-05 08:24:46 +00002340 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 case lltok::kw_udiv:
2343 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 case lltok::kw_urem:
Chris Lattnere914b592009-01-05 08:24:46 +00002345 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2346 case lltok::kw_fdiv:
2347 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002348 case lltok::kw_shl:
2349 case lltok::kw_lshr:
2350 case lltok::kw_ashr:
2351 case lltok::kw_and:
2352 case lltok::kw_or:
2353 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2354 case lltok::kw_icmp:
2355 case lltok::kw_fcmp:
2356 case lltok::kw_vicmp:
2357 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2358 // Casts.
2359 case lltok::kw_trunc:
2360 case lltok::kw_zext:
2361 case lltok::kw_sext:
2362 case lltok::kw_fptrunc:
2363 case lltok::kw_fpext:
2364 case lltok::kw_bitcast:
2365 case lltok::kw_uitofp:
2366 case lltok::kw_sitofp:
2367 case lltok::kw_fptoui:
2368 case lltok::kw_fptosi:
2369 case lltok::kw_inttoptr:
2370 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2371 // Other.
2372 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002373 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2375 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2376 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2377 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2378 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2379 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2380 // Memory.
2381 case lltok::kw_alloca:
2382 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2383 case lltok::kw_free: return ParseFree(Inst, PFS);
2384 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2385 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2386 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002387 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002389 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002390 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002391 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2394 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2395 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2396 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2397 }
2398}
2399
2400/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2401bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2402 // FIXME: REMOVE vicmp/vfcmp!
2403 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2404 switch (Lex.getKind()) {
2405 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2406 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2407 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2408 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2409 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2410 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2411 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2412 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2413 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2414 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2415 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2416 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2417 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2418 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2419 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2420 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2421 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2422 }
2423 } else {
2424 switch (Lex.getKind()) {
2425 default: TokError("expected icmp predicate (e.g. 'eq')");
2426 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2427 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2428 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2429 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2430 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2431 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2432 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2433 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2434 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2435 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2436 }
2437 }
2438 Lex.Lex();
2439 return false;
2440}
2441
2442//===----------------------------------------------------------------------===//
2443// Terminator Instructions.
2444//===----------------------------------------------------------------------===//
2445
2446/// ParseRet - Parse a return instruction.
2447/// ::= 'ret' void
2448/// ::= 'ret' TypeAndValue
2449/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2450bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2451 PerFunctionState &PFS) {
2452 PATypeHolder Ty(Type::VoidTy);
2453 if (ParseType(Ty)) return true;
2454
2455 if (Ty == Type::VoidTy) {
2456 Inst = ReturnInst::Create();
2457 return false;
2458 }
2459
2460 Value *RV;
2461 if (ParseValue(Ty, RV, PFS)) return true;
2462
2463 // The normal case is one return value.
2464 if (Lex.getKind() == lltok::comma) {
2465 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2466 // of 'ret {i32,i32} {i32 1, i32 2}'
2467 SmallVector<Value*, 8> RVs;
2468 RVs.push_back(RV);
2469
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002470 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002471 if (ParseTypeAndValue(RV, PFS)) return true;
2472 RVs.push_back(RV);
2473 }
2474
2475 RV = UndefValue::get(PFS.getFunction().getReturnType());
2476 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2477 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2478 BB->getInstList().push_back(I);
2479 RV = I;
2480 }
2481 }
2482 Inst = ReturnInst::Create(RV);
2483 return false;
2484}
2485
2486
2487/// ParseBr
2488/// ::= 'br' TypeAndValue
2489/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2490bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2491 LocTy Loc, Loc2;
2492 Value *Op0, *Op1, *Op2;
2493 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2494
2495 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2496 Inst = BranchInst::Create(BB);
2497 return false;
2498 }
2499
2500 if (Op0->getType() != Type::Int1Ty)
2501 return Error(Loc, "branch condition must have 'i1' type");
2502
2503 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2504 ParseTypeAndValue(Op1, Loc, PFS) ||
2505 ParseToken(lltok::comma, "expected ',' after true destination") ||
2506 ParseTypeAndValue(Op2, Loc2, PFS))
2507 return true;
2508
2509 if (!isa<BasicBlock>(Op1))
2510 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002511 if (!isa<BasicBlock>(Op2))
2512 return Error(Loc2, "true destination of branch must be a basic block");
2513
2514 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2515 return false;
2516}
2517
2518/// ParseSwitch
2519/// Instruction
2520/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2521/// JumpTable
2522/// ::= (TypeAndValue ',' TypeAndValue)*
2523bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2524 LocTy CondLoc, BBLoc;
2525 Value *Cond, *DefaultBB;
2526 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2527 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2528 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2529 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2530 return true;
2531
2532 if (!isa<IntegerType>(Cond->getType()))
2533 return Error(CondLoc, "switch condition must have integer type");
2534 if (!isa<BasicBlock>(DefaultBB))
2535 return Error(BBLoc, "default destination must be a basic block");
2536
2537 // Parse the jump table pairs.
2538 SmallPtrSet<Value*, 32> SeenCases;
2539 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2540 while (Lex.getKind() != lltok::rsquare) {
2541 Value *Constant, *DestBB;
2542
2543 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2544 ParseToken(lltok::comma, "expected ',' after case value") ||
2545 ParseTypeAndValue(DestBB, BBLoc, PFS))
2546 return true;
2547
2548 if (!SeenCases.insert(Constant))
2549 return Error(CondLoc, "duplicate case value in switch");
2550 if (!isa<ConstantInt>(Constant))
2551 return Error(CondLoc, "case value is not a constant integer");
2552 if (!isa<BasicBlock>(DestBB))
2553 return Error(BBLoc, "case destination is not a basic block");
2554
2555 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2556 cast<BasicBlock>(DestBB)));
2557 }
2558
2559 Lex.Lex(); // Eat the ']'.
2560
2561 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2562 Table.size());
2563 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2564 SI->addCase(Table[i].first, Table[i].second);
2565 Inst = SI;
2566 return false;
2567}
2568
2569/// ParseInvoke
2570/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2571/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2572bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2573 LocTy CallLoc = Lex.getLoc();
2574 unsigned CC, RetAttrs, FnAttrs;
2575 PATypeHolder RetType(Type::VoidTy);
2576 LocTy RetTypeLoc;
2577 ValID CalleeID;
2578 SmallVector<ParamInfo, 16> ArgList;
2579
2580 Value *NormalBB, *UnwindBB;
2581 if (ParseOptionalCallingConv(CC) ||
2582 ParseOptionalAttrs(RetAttrs, 1) ||
2583 ParseType(RetType, RetTypeLoc) ||
2584 ParseValID(CalleeID) ||
2585 ParseParameterList(ArgList, PFS) ||
2586 ParseOptionalAttrs(FnAttrs, 2) ||
2587 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2588 ParseTypeAndValue(NormalBB, PFS) ||
2589 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2590 ParseTypeAndValue(UnwindBB, PFS))
2591 return true;
2592
2593 if (!isa<BasicBlock>(NormalBB))
2594 return Error(CallLoc, "normal destination is not a basic block");
2595 if (!isa<BasicBlock>(UnwindBB))
2596 return Error(CallLoc, "unwind destination is not a basic block");
2597
2598 // If RetType is a non-function pointer type, then this is the short syntax
2599 // for the call, which means that RetType is just the return type. Infer the
2600 // rest of the function argument types from the arguments that are present.
2601 const PointerType *PFTy = 0;
2602 const FunctionType *Ty = 0;
2603 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2604 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2605 // Pull out the types of all of the arguments...
2606 std::vector<const Type*> ParamTypes;
2607 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2608 ParamTypes.push_back(ArgList[i].V->getType());
2609
2610 if (!FunctionType::isValidReturnType(RetType))
2611 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2612
2613 Ty = FunctionType::get(RetType, ParamTypes, false);
2614 PFTy = PointerType::getUnqual(Ty);
2615 }
2616
2617 // Look up the callee.
2618 Value *Callee;
2619 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2620
2621 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2622 // function attributes.
2623 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2624 if (FnAttrs & ObsoleteFuncAttrs) {
2625 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2626 FnAttrs &= ~ObsoleteFuncAttrs;
2627 }
2628
2629 // Set up the Attributes for the function.
2630 SmallVector<AttributeWithIndex, 8> Attrs;
2631 if (RetAttrs != Attribute::None)
2632 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2633
2634 SmallVector<Value*, 8> Args;
2635
2636 // Loop through FunctionType's arguments and ensure they are specified
2637 // correctly. Also, gather any parameter attributes.
2638 FunctionType::param_iterator I = Ty->param_begin();
2639 FunctionType::param_iterator E = Ty->param_end();
2640 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2641 const Type *ExpectedTy = 0;
2642 if (I != E) {
2643 ExpectedTy = *I++;
2644 } else if (!Ty->isVarArg()) {
2645 return Error(ArgList[i].Loc, "too many arguments specified");
2646 }
2647
2648 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2649 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2650 ExpectedTy->getDescription() + "'");
2651 Args.push_back(ArgList[i].V);
2652 if (ArgList[i].Attrs != Attribute::None)
2653 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2654 }
2655
2656 if (I != E)
2657 return Error(CallLoc, "not enough parameters specified for call");
2658
2659 if (FnAttrs != Attribute::None)
2660 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2661
2662 // Finish off the Attributes and check them
2663 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2664
2665 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2666 cast<BasicBlock>(UnwindBB),
2667 Args.begin(), Args.end());
2668 II->setCallingConv(CC);
2669 II->setAttributes(PAL);
2670 Inst = II;
2671 return false;
2672}
2673
2674
2675
2676//===----------------------------------------------------------------------===//
2677// Binary Operators.
2678//===----------------------------------------------------------------------===//
2679
2680/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002681/// ::= ArithmeticOps TypeAndValue ',' Value
2682///
2683/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2684/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002685bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002686 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002687 LocTy Loc; Value *LHS, *RHS;
2688 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2689 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2690 ParseValue(LHS->getType(), RHS, PFS))
2691 return true;
2692
Chris Lattnere914b592009-01-05 08:24:46 +00002693 bool Valid;
2694 switch (OperandType) {
2695 default: assert(0 && "Unknown operand type!");
2696 case 0: // int or FP.
2697 Valid = LHS->getType()->isIntOrIntVector() ||
2698 LHS->getType()->isFPOrFPVector();
2699 break;
2700 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2701 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2702 }
2703
2704 if (!Valid)
2705 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002706
2707 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2708 return false;
2709}
2710
2711/// ParseLogical
2712/// ::= ArithmeticOps TypeAndValue ',' Value {
2713bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2714 unsigned Opc) {
2715 LocTy Loc; Value *LHS, *RHS;
2716 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2717 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2718 ParseValue(LHS->getType(), RHS, PFS))
2719 return true;
2720
2721 if (!LHS->getType()->isIntOrIntVector())
2722 return Error(Loc,"instruction requires integer or integer vector operands");
2723
2724 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2725 return false;
2726}
2727
2728
2729/// ParseCompare
2730/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2731/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2732/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2733/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2734bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2735 unsigned Opc) {
2736 // Parse the integer/fp comparison predicate.
2737 LocTy Loc;
2738 unsigned Pred;
2739 Value *LHS, *RHS;
2740 if (ParseCmpPredicate(Pred, Opc) ||
2741 ParseTypeAndValue(LHS, Loc, PFS) ||
2742 ParseToken(lltok::comma, "expected ',' after compare value") ||
2743 ParseValue(LHS->getType(), RHS, PFS))
2744 return true;
2745
2746 if (Opc == Instruction::FCmp) {
2747 if (!LHS->getType()->isFPOrFPVector())
2748 return Error(Loc, "fcmp requires floating point operands");
2749 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2750 } else if (Opc == Instruction::ICmp) {
2751 if (!LHS->getType()->isIntOrIntVector() &&
2752 !isa<PointerType>(LHS->getType()))
2753 return Error(Loc, "icmp requires integer operands");
2754 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2755 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002756 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2757 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2759 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002760 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2761 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2763 }
2764 return false;
2765}
2766
2767//===----------------------------------------------------------------------===//
2768// Other Instructions.
2769//===----------------------------------------------------------------------===//
2770
2771
2772/// ParseCast
2773/// ::= CastOpc TypeAndValue 'to' Type
2774bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2775 unsigned Opc) {
2776 LocTy Loc; Value *Op;
2777 PATypeHolder DestTy(Type::VoidTy);
2778 if (ParseTypeAndValue(Op, Loc, PFS) ||
2779 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2780 ParseType(DestTy))
2781 return true;
2782
2783 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2784 return Error(Loc, "invalid cast opcode for cast from '" +
2785 Op->getType()->getDescription() + "' to '" +
2786 DestTy->getDescription() + "'");
2787 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2788 return false;
2789}
2790
2791/// ParseSelect
2792/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2793bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2794 LocTy Loc;
2795 Value *Op0, *Op1, *Op2;
2796 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2797 ParseToken(lltok::comma, "expected ',' after select condition") ||
2798 ParseTypeAndValue(Op1, PFS) ||
2799 ParseToken(lltok::comma, "expected ',' after select value") ||
2800 ParseTypeAndValue(Op2, PFS))
2801 return true;
2802
2803 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2804 return Error(Loc, Reason);
2805
2806 Inst = SelectInst::Create(Op0, Op1, Op2);
2807 return false;
2808}
2809
Chris Lattner0088a5c2009-01-05 08:18:44 +00002810/// ParseVA_Arg
2811/// ::= 'va_arg' TypeAndValue ',' Type
2812bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 Value *Op;
2814 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002815 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 if (ParseTypeAndValue(Op, PFS) ||
2817 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002818 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002820
2821 if (!EltTy->isFirstClassType())
2822 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002823
2824 Inst = new VAArgInst(Op, EltTy);
2825 return false;
2826}
2827
2828/// ParseExtractElement
2829/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2830bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2831 LocTy Loc;
2832 Value *Op0, *Op1;
2833 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2834 ParseToken(lltok::comma, "expected ',' after extract value") ||
2835 ParseTypeAndValue(Op1, PFS))
2836 return true;
2837
2838 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2839 return Error(Loc, "invalid extractelement operands");
2840
2841 Inst = new ExtractElementInst(Op0, Op1);
2842 return false;
2843}
2844
2845/// ParseInsertElement
2846/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2847bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2848 LocTy Loc;
2849 Value *Op0, *Op1, *Op2;
2850 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2851 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2852 ParseTypeAndValue(Op1, PFS) ||
2853 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2854 ParseTypeAndValue(Op2, PFS))
2855 return true;
2856
2857 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2858 return Error(Loc, "invalid extractelement operands");
2859
2860 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2861 return false;
2862}
2863
2864/// ParseShuffleVector
2865/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2866bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2867 LocTy Loc;
2868 Value *Op0, *Op1, *Op2;
2869 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2870 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2871 ParseTypeAndValue(Op1, PFS) ||
2872 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2873 ParseTypeAndValue(Op2, PFS))
2874 return true;
2875
2876 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2877 return Error(Loc, "invalid extractelement operands");
2878
2879 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2880 return false;
2881}
2882
2883/// ParsePHI
2884/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2885bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2886 PATypeHolder Ty(Type::VoidTy);
2887 Value *Op0, *Op1;
2888 LocTy TypeLoc = Lex.getLoc();
2889
2890 if (ParseType(Ty) ||
2891 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2892 ParseValue(Ty, Op0, PFS) ||
2893 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2894 ParseValue(Type::LabelTy, Op1, PFS) ||
2895 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2896 return true;
2897
2898 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2899 while (1) {
2900 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2901
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002902 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002903 break;
2904
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002905 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002906 ParseValue(Ty, Op0, PFS) ||
2907 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2908 ParseValue(Type::LabelTy, Op1, PFS) ||
2909 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2910 return true;
2911 }
2912
2913 if (!Ty->isFirstClassType())
2914 return Error(TypeLoc, "phi node must have first class type");
2915
2916 PHINode *PN = PHINode::Create(Ty);
2917 PN->reserveOperandSpace(PHIVals.size());
2918 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2919 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2920 Inst = PN;
2921 return false;
2922}
2923
2924/// ParseCall
2925/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2926/// ParameterList OptionalAttrs
2927bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2928 bool isTail) {
2929 unsigned CC, RetAttrs, FnAttrs;
2930 PATypeHolder RetType(Type::VoidTy);
2931 LocTy RetTypeLoc;
2932 ValID CalleeID;
2933 SmallVector<ParamInfo, 16> ArgList;
2934 LocTy CallLoc = Lex.getLoc();
2935
2936 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2937 ParseOptionalCallingConv(CC) ||
2938 ParseOptionalAttrs(RetAttrs, 1) ||
2939 ParseType(RetType, RetTypeLoc) ||
2940 ParseValID(CalleeID) ||
2941 ParseParameterList(ArgList, PFS) ||
2942 ParseOptionalAttrs(FnAttrs, 2))
2943 return true;
2944
2945 // If RetType is a non-function pointer type, then this is the short syntax
2946 // for the call, which means that RetType is just the return type. Infer the
2947 // rest of the function argument types from the arguments that are present.
2948 const PointerType *PFTy = 0;
2949 const FunctionType *Ty = 0;
2950 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2951 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2952 // Pull out the types of all of the arguments...
2953 std::vector<const Type*> ParamTypes;
2954 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2955 ParamTypes.push_back(ArgList[i].V->getType());
2956
2957 if (!FunctionType::isValidReturnType(RetType))
2958 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2959
2960 Ty = FunctionType::get(RetType, ParamTypes, false);
2961 PFTy = PointerType::getUnqual(Ty);
2962 }
2963
2964 // Look up the callee.
2965 Value *Callee;
2966 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2967
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2969 // function attributes.
2970 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2971 if (FnAttrs & ObsoleteFuncAttrs) {
2972 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2973 FnAttrs &= ~ObsoleteFuncAttrs;
2974 }
2975
2976 // Set up the Attributes for the function.
2977 SmallVector<AttributeWithIndex, 8> Attrs;
2978 if (RetAttrs != Attribute::None)
2979 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2980
2981 SmallVector<Value*, 8> Args;
2982
2983 // Loop through FunctionType's arguments and ensure they are specified
2984 // correctly. Also, gather any parameter attributes.
2985 FunctionType::param_iterator I = Ty->param_begin();
2986 FunctionType::param_iterator E = Ty->param_end();
2987 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2988 const Type *ExpectedTy = 0;
2989 if (I != E) {
2990 ExpectedTy = *I++;
2991 } else if (!Ty->isVarArg()) {
2992 return Error(ArgList[i].Loc, "too many arguments specified");
2993 }
2994
2995 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2996 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2997 ExpectedTy->getDescription() + "'");
2998 Args.push_back(ArgList[i].V);
2999 if (ArgList[i].Attrs != Attribute::None)
3000 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3001 }
3002
3003 if (I != E)
3004 return Error(CallLoc, "not enough parameters specified for call");
3005
3006 if (FnAttrs != Attribute::None)
3007 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3008
3009 // Finish off the Attributes and check them
3010 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3011
3012 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3013 CI->setTailCall(isTail);
3014 CI->setCallingConv(CC);
3015 CI->setAttributes(PAL);
3016 Inst = CI;
3017 return false;
3018}
3019
3020//===----------------------------------------------------------------------===//
3021// Memory Instructions.
3022//===----------------------------------------------------------------------===//
3023
3024/// ParseAlloc
3025/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3026/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3027bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3028 unsigned Opc) {
3029 PATypeHolder Ty(Type::VoidTy);
3030 Value *Size = 0;
3031 LocTy SizeLoc = 0;
3032 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003033 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003034
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003035 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003036 if (Lex.getKind() == lltok::kw_align) {
3037 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003038 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3039 ParseOptionalCommaAlignment(Alignment)) {
3040 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 }
3042 }
3043
3044 if (Size && Size->getType() != Type::Int32Ty)
3045 return Error(SizeLoc, "element count must be i32");
3046
3047 if (Opc == Instruction::Malloc)
3048 Inst = new MallocInst(Ty, Size, Alignment);
3049 else
3050 Inst = new AllocaInst(Ty, Size, Alignment);
3051 return false;
3052}
3053
3054/// ParseFree
3055/// ::= 'free' TypeAndValue
3056bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3057 Value *Val; LocTy Loc;
3058 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3059 if (!isa<PointerType>(Val->getType()))
3060 return Error(Loc, "operand to free must be a pointer");
3061 Inst = new FreeInst(Val);
3062 return false;
3063}
3064
3065/// ParseLoad
3066/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3067bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3068 bool isVolatile) {
3069 Value *Val; LocTy Loc;
3070 unsigned Alignment;
3071 if (ParseTypeAndValue(Val, Loc, PFS) ||
3072 ParseOptionalCommaAlignment(Alignment))
3073 return true;
3074
3075 if (!isa<PointerType>(Val->getType()) ||
3076 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3077 return Error(Loc, "load operand must be a pointer to a first class type");
3078
3079 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3080 return false;
3081}
3082
3083/// ParseStore
3084/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3085bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3086 bool isVolatile) {
3087 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3088 unsigned Alignment;
3089 if (ParseTypeAndValue(Val, Loc, PFS) ||
3090 ParseToken(lltok::comma, "expected ',' after store operand") ||
3091 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3092 ParseOptionalCommaAlignment(Alignment))
3093 return true;
3094
3095 if (!isa<PointerType>(Ptr->getType()))
3096 return Error(PtrLoc, "store operand must be a pointer");
3097 if (!Val->getType()->isFirstClassType())
3098 return Error(Loc, "store operand must be a first class value");
3099 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3100 return Error(Loc, "stored value and pointer type do not match");
3101
3102 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3103 return false;
3104}
3105
3106/// ParseGetResult
3107/// ::= 'getresult' TypeAndValue ',' uint
3108/// FIXME: Remove support for getresult in LLVM 3.0
3109bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3110 Value *Val; LocTy ValLoc, EltLoc;
3111 unsigned Element;
3112 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3113 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003114 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 return true;
3116
3117 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3118 return Error(ValLoc, "getresult inst requires an aggregate operand");
3119 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3120 return Error(EltLoc, "invalid getresult index for value");
3121 Inst = ExtractValueInst::Create(Val, Element);
3122 return false;
3123}
3124
3125/// ParseGetElementPtr
3126/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3127bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3128 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003129 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003130
3131 if (!isa<PointerType>(Ptr->getType()))
3132 return Error(Loc, "base of getelementptr must be a pointer");
3133
3134 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003135 while (EatIfPresent(lltok::comma)) {
3136 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003137 if (!isa<IntegerType>(Val->getType()))
3138 return Error(EltLoc, "getelementptr index must be an integer");
3139 Indices.push_back(Val);
3140 }
3141
3142 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3143 Indices.begin(), Indices.end()))
3144 return Error(Loc, "invalid getelementptr indices");
3145 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3146 return false;
3147}
3148
3149/// ParseExtractValue
3150/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3151bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3152 Value *Val; LocTy Loc;
3153 SmallVector<unsigned, 4> Indices;
3154 if (ParseTypeAndValue(Val, Loc, PFS) ||
3155 ParseIndexList(Indices))
3156 return true;
3157
3158 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3159 return Error(Loc, "extractvalue operand must be array or struct");
3160
3161 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3162 Indices.end()))
3163 return Error(Loc, "invalid indices for extractvalue");
3164 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3165 return false;
3166}
3167
3168/// ParseInsertValue
3169/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3170bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3171 Value *Val0, *Val1; LocTy Loc0, Loc1;
3172 SmallVector<unsigned, 4> Indices;
3173 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3174 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3175 ParseTypeAndValue(Val1, Loc1, PFS) ||
3176 ParseIndexList(Indices))
3177 return true;
3178
3179 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3180 return Error(Loc0, "extractvalue operand must be array or struct");
3181
3182 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3183 Indices.end()))
3184 return Error(Loc0, "invalid indices for insertvalue");
3185 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3186 return false;
3187}