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