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