blob: a9f8e192d382842351d88035a4415f9e336ce26f [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;
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
568 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
569 else
570 FwdVal = new GlobalVariable(PTy->getElementType(), false,
571 GlobalValue::ExternalWeakLinkage, 0, Name, M);
572
573 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
574 return FwdVal;
575}
576
577GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
579 if (PTy == 0) {
580 Error(Loc, "global variable reference must have pointer type");
581 return 0;
582 }
583
584 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
585
586 // If this is a forward reference for the value, see if we already created a
587 // forward ref record.
588 if (Val == 0) {
589 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
590 I = ForwardRefValIDs.find(ID);
591 if (I != ForwardRefValIDs.end())
592 Val = I->second.first;
593 }
594
595 // If we have the value in the symbol table or fwd-ref table, return it.
596 if (Val) {
597 if (Val->getType() == Ty) return Val;
598 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
599 Val->getType()->getDescription() + "'");
600 return 0;
601 }
602
603 // Otherwise, create a new forward reference for this value and remember it.
604 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000605 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
606 // Function types can return opaque but functions can't.
607 if (isa<OpaqueType>(FT->getReturnType())) {
608 Error(Loc, "function may not return return opaque type");
609 return 0;
610 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000612 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000613 FwdVal = new GlobalVariable(PTy->getElementType(), false,
614 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000615 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000616
617 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
618 return FwdVal;
619}
620
621
622//===----------------------------------------------------------------------===//
623// Helper Routines.
624//===----------------------------------------------------------------------===//
625
626/// ParseToken - If the current token has the specified kind, eat it and return
627/// success. Otherwise, emit the specified error and return failure.
628bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
629 if (Lex.getKind() != T)
630 return TokError(ErrMsg);
631 Lex.Lex();
632 return false;
633}
634
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000635/// ParseStringConstant
636/// ::= StringConstant
637bool LLParser::ParseStringConstant(std::string &Result) {
638 if (Lex.getKind() != lltok::StringConstant)
639 return TokError("expected string constant");
640 Result = Lex.getStrVal();
641 Lex.Lex();
642 return false;
643}
644
645/// ParseUInt32
646/// ::= uint32
647bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000648 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
649 return TokError("expected integer");
650 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
651 if (Val64 != unsigned(Val64))
652 return TokError("expected 32-bit integer (too large)");
653 Val = Val64;
654 Lex.Lex();
655 return false;
656}
657
658
659/// ParseOptionalAddrSpace
660/// := /*empty*/
661/// := 'addrspace' '(' uint32 ')'
662bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
663 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000664 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000665 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000666 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000667 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000668 ParseToken(lltok::rparen, "expected ')' in address space");
669}
670
671/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
672/// indicates what kind of attribute list this is: 0: function arg, 1: result,
673/// 2: function attr.
674bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
675 Attrs = Attribute::None;
676 LocTy AttrLoc = Lex.getLoc();
677
678 while (1) {
679 switch (Lex.getKind()) {
680 case lltok::kw_sext:
681 case lltok::kw_zext:
682 // Treat these as signext/zeroext unless they are function attrs.
683 // FIXME: REMOVE THIS IN LLVM 3.0
684 if (AttrKind != 2) {
685 if (Lex.getKind() == lltok::kw_sext)
686 Attrs |= Attribute::SExt;
687 else
688 Attrs |= Attribute::ZExt;
689 break;
690 }
691 // FALL THROUGH.
692 default: // End of attributes.
693 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
694 return Error(AttrLoc, "invalid use of function-only attribute");
695
696 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
697 return Error(AttrLoc, "invalid use of parameter-only attribute");
698
699 return false;
700 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
701 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
702 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
703 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
704 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
705 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
706 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
707 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
708
709 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
710 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
711 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
712 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
713 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
714 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
715 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
716 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
717 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
718
719
720 case lltok::kw_align: {
721 unsigned Alignment;
722 if (ParseOptionalAlignment(Alignment))
723 return true;
724 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
725 continue;
726 }
727 }
728 Lex.Lex();
729 }
730}
731
732/// ParseOptionalLinkage
733/// ::= /*empty*/
734/// ::= 'internal'
735/// ::= 'weak'
736/// ::= 'linkonce'
737/// ::= 'appending'
738/// ::= 'dllexport'
739/// ::= 'common'
740/// ::= 'dllimport'
741/// ::= 'extern_weak'
742/// ::= 'external'
743bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
744 HasLinkage = false;
745 switch (Lex.getKind()) {
746 default: Res = GlobalValue::ExternalLinkage; return false;
747 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
748 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
749 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
750 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
751 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
752 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
753 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
754 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
755 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
756 }
757 Lex.Lex();
758 HasLinkage = true;
759 return false;
760}
761
762/// ParseOptionalVisibility
763/// ::= /*empty*/
764/// ::= 'default'
765/// ::= 'hidden'
766/// ::= 'protected'
767///
768bool LLParser::ParseOptionalVisibility(unsigned &Res) {
769 switch (Lex.getKind()) {
770 default: Res = GlobalValue::DefaultVisibility; return false;
771 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
772 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
773 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
774 }
775 Lex.Lex();
776 return false;
777}
778
779/// ParseOptionalCallingConv
780/// ::= /*empty*/
781/// ::= 'ccc'
782/// ::= 'fastcc'
783/// ::= 'coldcc'
784/// ::= 'x86_stdcallcc'
785/// ::= 'x86_fastcallcc'
786/// ::= 'cc' UINT
787///
788bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
789 switch (Lex.getKind()) {
790 default: CC = CallingConv::C; return false;
791 case lltok::kw_ccc: CC = CallingConv::C; break;
792 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
793 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
794 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
795 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000796 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 }
798 Lex.Lex();
799 return false;
800}
801
802/// ParseOptionalAlignment
803/// ::= /* empty */
804/// ::= 'align' 4
805bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
806 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000807 if (!EatIfPresent(lltok::kw_align))
808 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000809 LocTy AlignLoc = Lex.getLoc();
810 if (ParseUInt32(Alignment)) return true;
811 if (!isPowerOf2_32(Alignment))
812 return Error(AlignLoc, "alignment is not a power of two");
813 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000814}
815
816/// ParseOptionalCommaAlignment
817/// ::= /* empty */
818/// ::= ',' 'align' 4
819bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
820 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000821 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000823 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000824 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000825}
826
827/// ParseIndexList
828/// ::= (',' uint32)+
829bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
830 if (Lex.getKind() != lltok::comma)
831 return TokError("expected ',' as start of index list");
832
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000833 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000834 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000835 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000836 Indices.push_back(Idx);
837 }
838
839 return false;
840}
841
842//===----------------------------------------------------------------------===//
843// Type Parsing.
844//===----------------------------------------------------------------------===//
845
846/// ParseType - Parse and resolve a full type.
847bool LLParser::ParseType(PATypeHolder &Result) {
848 if (ParseTypeRec(Result)) return true;
849
850 // Verify no unresolved uprefs.
851 if (!UpRefs.empty())
852 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000853
854 return false;
855}
856
857/// HandleUpRefs - Every time we finish a new layer of types, this function is
858/// called. It loops through the UpRefs vector, which is a list of the
859/// currently active types. For each type, if the up-reference is contained in
860/// the newly completed type, we decrement the level count. When the level
861/// count reaches zero, the up-referenced type is the type that is passed in:
862/// thus we can complete the cycle.
863///
864PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
865 // If Ty isn't abstract, or if there are no up-references in it, then there is
866 // nothing to resolve here.
867 if (!ty->isAbstract() || UpRefs.empty()) return ty;
868
869 PATypeHolder Ty(ty);
870#if 0
871 errs() << "Type '" << Ty->getDescription()
872 << "' newly formed. Resolving upreferences.\n"
873 << UpRefs.size() << " upreferences active!\n";
874#endif
875
876 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
877 // to zero), we resolve them all together before we resolve them to Ty. At
878 // the end of the loop, if there is anything to resolve to Ty, it will be in
879 // this variable.
880 OpaqueType *TypeToResolve = 0;
881
882 for (unsigned i = 0; i != UpRefs.size(); ++i) {
883 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
884 bool ContainsType =
885 std::find(Ty->subtype_begin(), Ty->subtype_end(),
886 UpRefs[i].LastContainedTy) != Ty->subtype_end();
887
888#if 0
889 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
890 << UpRefs[i].LastContainedTy->getDescription() << ") = "
891 << (ContainsType ? "true" : "false")
892 << " level=" << UpRefs[i].NestingLevel << "\n";
893#endif
894 if (!ContainsType)
895 continue;
896
897 // Decrement level of upreference
898 unsigned Level = --UpRefs[i].NestingLevel;
899 UpRefs[i].LastContainedTy = Ty;
900
901 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
902 if (Level != 0)
903 continue;
904
905#if 0
906 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
907#endif
908 if (!TypeToResolve)
909 TypeToResolve = UpRefs[i].UpRefTy;
910 else
911 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
912 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
913 --i; // Do not skip the next element.
914 }
915
916 if (TypeToResolve)
917 TypeToResolve->refineAbstractTypeTo(Ty);
918
919 return Ty;
920}
921
922
923/// ParseTypeRec - The recursive function used to process the internal
924/// implementation details of types.
925bool LLParser::ParseTypeRec(PATypeHolder &Result) {
926 switch (Lex.getKind()) {
927 default:
928 return TokError("expected type");
929 case lltok::Type:
930 // TypeRec ::= 'float' | 'void' (etc)
931 Result = Lex.getTyVal();
932 Lex.Lex();
933 break;
934 case lltok::kw_opaque:
935 // TypeRec ::= 'opaque'
936 Result = OpaqueType::get();
937 Lex.Lex();
938 break;
939 case lltok::lbrace:
940 // TypeRec ::= '{' ... '}'
941 if (ParseStructType(Result, false))
942 return true;
943 break;
944 case lltok::lsquare:
945 // TypeRec ::= '[' ... ']'
946 Lex.Lex(); // eat the lsquare.
947 if (ParseArrayVectorType(Result, false))
948 return true;
949 break;
950 case lltok::less: // Either vector or packed struct.
951 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000952 Lex.Lex();
953 if (Lex.getKind() == lltok::lbrace) {
954 if (ParseStructType(Result, true) ||
955 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000956 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000957 } else if (ParseArrayVectorType(Result, true))
958 return true;
959 break;
960 case lltok::LocalVar:
961 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
962 // TypeRec ::= %foo
963 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
964 Result = T;
965 } else {
966 Result = OpaqueType::get();
967 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
968 std::make_pair(Result,
969 Lex.getLoc())));
970 M->addTypeName(Lex.getStrVal(), Result.get());
971 }
972 Lex.Lex();
973 break;
974
975 case lltok::LocalVarID:
976 // TypeRec ::= %4
977 if (Lex.getUIntVal() < NumberedTypes.size())
978 Result = NumberedTypes[Lex.getUIntVal()];
979 else {
980 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
981 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
982 if (I != ForwardRefTypeIDs.end())
983 Result = I->second.first;
984 else {
985 Result = OpaqueType::get();
986 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
987 std::make_pair(Result,
988 Lex.getLoc())));
989 }
990 }
991 Lex.Lex();
992 break;
993 case lltok::backslash: {
994 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +0000995 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000996 unsigned Val;
997 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000998 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
999 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1000 Result = OT;
1001 break;
1002 }
1003 }
1004
1005 // Parse the type suffixes.
1006 while (1) {
1007 switch (Lex.getKind()) {
1008 // End of type.
1009 default: return false;
1010
1011 // TypeRec ::= TypeRec '*'
1012 case lltok::star:
1013 if (Result.get() == Type::LabelTy)
1014 return TokError("basic block pointers are invalid");
1015 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1016 Lex.Lex();
1017 break;
1018
1019 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1020 case lltok::kw_addrspace: {
1021 if (Result.get() == Type::LabelTy)
1022 return TokError("basic block pointers are invalid");
1023 unsigned AddrSpace;
1024 if (ParseOptionalAddrSpace(AddrSpace) ||
1025 ParseToken(lltok::star, "expected '*' in address space"))
1026 return true;
1027
1028 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1029 break;
1030 }
1031
1032 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1033 case lltok::lparen:
1034 if (ParseFunctionType(Result))
1035 return true;
1036 break;
1037 }
1038 }
1039}
1040
1041/// ParseParameterList
1042/// ::= '(' ')'
1043/// ::= '(' Arg (',' Arg)* ')'
1044/// Arg
1045/// ::= Type OptionalAttributes Value OptionalAttributes
1046bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1047 PerFunctionState &PFS) {
1048 if (ParseToken(lltok::lparen, "expected '(' in call"))
1049 return true;
1050
1051 while (Lex.getKind() != lltok::rparen) {
1052 // If this isn't the first argument, we need a comma.
1053 if (!ArgList.empty() &&
1054 ParseToken(lltok::comma, "expected ',' in argument list"))
1055 return true;
1056
1057 // Parse the argument.
1058 LocTy ArgLoc;
1059 PATypeHolder ArgTy(Type::VoidTy);
1060 unsigned ArgAttrs1, ArgAttrs2;
1061 Value *V;
1062 if (ParseType(ArgTy, ArgLoc) ||
1063 ParseOptionalAttrs(ArgAttrs1, 0) ||
1064 ParseValue(ArgTy, V, PFS) ||
1065 // FIXME: Should not allow attributes after the argument, remove this in
1066 // LLVM 3.0.
1067 ParseOptionalAttrs(ArgAttrs2, 0))
1068 return true;
1069 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1070 }
1071
1072 Lex.Lex(); // Lex the ')'.
1073 return false;
1074}
1075
1076
1077
1078/// ParseArgumentList
1079/// ::= '(' ArgTypeListI ')'
1080/// ArgTypeListI
1081/// ::= /*empty*/
1082/// ::= '...'
1083/// ::= ArgTypeList ',' '...'
1084/// ::= ArgType (',' ArgType)*
1085bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1086 bool &isVarArg) {
1087 isVarArg = false;
1088 assert(Lex.getKind() == lltok::lparen);
1089 Lex.Lex(); // eat the (.
1090
1091 if (Lex.getKind() == lltok::rparen) {
1092 // empty
1093 } else if (Lex.getKind() == lltok::dotdotdot) {
1094 isVarArg = true;
1095 Lex.Lex();
1096 } else {
1097 LocTy TypeLoc = Lex.getLoc();
1098 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001099 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001100 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001101
1102 if (ParseTypeRec(ArgTy) ||
1103 ParseOptionalAttrs(Attrs, 0)) return true;
1104
Chris Lattnerdf986172009-01-02 07:01:27 +00001105 if (Lex.getKind() == lltok::LocalVar ||
1106 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1107 Name = Lex.getStrVal();
1108 Lex.Lex();
1109 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001110
1111 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1112 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001113
1114 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1115
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001116 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001118 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001119 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 break;
1121 }
1122
1123 // Otherwise must be an argument type.
1124 TypeLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001125 if (ParseTypeRec(ArgTy) ||
1126 ParseOptionalAttrs(Attrs, 0)) return true;
1127
Chris Lattnerdf986172009-01-02 07:01:27 +00001128 if (Lex.getKind() == lltok::LocalVar ||
1129 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1130 Name = Lex.getStrVal();
1131 Lex.Lex();
1132 } else {
1133 Name = "";
1134 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001135
1136 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1137 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001138
1139 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1140 }
1141 }
1142
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001143 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001144}
1145
1146/// ParseFunctionType
1147/// ::= Type ArgumentList OptionalAttrs
1148bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1149 assert(Lex.getKind() == lltok::lparen);
1150
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001151 if (!FunctionType::isValidReturnType(Result))
1152 return TokError("invalid function return type");
1153
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 std::vector<ArgInfo> ArgList;
1155 bool isVarArg;
1156 unsigned Attrs;
1157 if (ParseArgumentList(ArgList, isVarArg) ||
1158 // FIXME: Allow, but ignore attributes on function types!
1159 // FIXME: Remove in LLVM 3.0
1160 ParseOptionalAttrs(Attrs, 2))
1161 return true;
1162
1163 // Reject names on the arguments lists.
1164 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1165 if (!ArgList[i].Name.empty())
1166 return Error(ArgList[i].Loc, "argument name invalid in function type");
1167 if (!ArgList[i].Attrs != 0) {
1168 // Allow but ignore attributes on function types; this permits
1169 // auto-upgrade.
1170 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1171 }
1172 }
1173
1174 std::vector<const Type*> ArgListTy;
1175 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1176 ArgListTy.push_back(ArgList[i].Type);
1177
1178 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1179 return false;
1180}
1181
1182/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1183/// TypeRec
1184/// ::= '{' '}'
1185/// ::= '{' TypeRec (',' TypeRec)* '}'
1186/// ::= '<' '{' '}' '>'
1187/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1188bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1189 assert(Lex.getKind() == lltok::lbrace);
1190 Lex.Lex(); // Consume the '{'
1191
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001192 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001193 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001194 return false;
1195 }
1196
1197 std::vector<PATypeHolder> ParamsList;
1198 if (ParseTypeRec(Result)) return true;
1199 ParamsList.push_back(Result);
1200
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001201 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001202 if (ParseTypeRec(Result)) return true;
1203 ParamsList.push_back(Result);
1204 }
1205
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001206 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1207 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001208
1209 std::vector<const Type*> ParamsListTy;
1210 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1211 ParamsListTy.push_back(ParamsList[i].get());
1212 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1213 return false;
1214}
1215
1216/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1217/// token has already been consumed.
1218/// TypeRec
1219/// ::= '[' APSINTVAL 'x' Types ']'
1220/// ::= '<' APSINTVAL 'x' Types '>'
1221bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1222 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1223 Lex.getAPSIntVal().getBitWidth() > 64)
1224 return TokError("expected number in address space");
1225
1226 LocTy SizeLoc = Lex.getLoc();
1227 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001228 Lex.Lex();
1229
1230 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1231 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001232
1233 LocTy TypeLoc = Lex.getLoc();
1234 PATypeHolder EltTy(Type::VoidTy);
1235 if (ParseTypeRec(EltTy)) return true;
1236
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001237 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1238 "expected end of sequential type"))
1239 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001240
1241 if (isVector) {
1242 if ((unsigned)Size != Size)
1243 return Error(SizeLoc, "size too large for vector");
1244 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1245 return Error(TypeLoc, "vector element type must be fp or integer");
1246 Result = VectorType::get(EltTy, unsigned(Size));
1247 } else {
1248 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1249 return Error(TypeLoc, "invalid array element type");
1250 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1251 }
1252 return false;
1253}
1254
1255//===----------------------------------------------------------------------===//
1256// Function Semantic Analysis.
1257//===----------------------------------------------------------------------===//
1258
1259LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1260 : P(p), F(f) {
1261
1262 // Insert unnamed arguments into the NumberedVals list.
1263 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1264 AI != E; ++AI)
1265 if (!AI->hasName())
1266 NumberedVals.push_back(AI);
1267}
1268
1269LLParser::PerFunctionState::~PerFunctionState() {
1270 // If there were any forward referenced non-basicblock values, delete them.
1271 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1272 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1273 if (!isa<BasicBlock>(I->second.first)) {
1274 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1275 ->getType()));
1276 delete I->second.first;
1277 I->second.first = 0;
1278 }
1279
1280 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1281 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1282 if (!isa<BasicBlock>(I->second.first)) {
1283 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1284 ->getType()));
1285 delete I->second.first;
1286 I->second.first = 0;
1287 }
1288}
1289
1290bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1291 if (!ForwardRefVals.empty())
1292 return P.Error(ForwardRefVals.begin()->second.second,
1293 "use of undefined value '%" + ForwardRefVals.begin()->first +
1294 "'");
1295 if (!ForwardRefValIDs.empty())
1296 return P.Error(ForwardRefValIDs.begin()->second.second,
1297 "use of undefined value '%" +
1298 utostr(ForwardRefValIDs.begin()->first) + "'");
1299 return false;
1300}
1301
1302
1303/// GetVal - Get a value with the specified name or ID, creating a
1304/// forward reference record if needed. This can return null if the value
1305/// exists but does not have the right type.
1306Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1307 const Type *Ty, LocTy Loc) {
1308 // Look this name up in the normal function symbol table.
1309 Value *Val = F.getValueSymbolTable().lookup(Name);
1310
1311 // If this is a forward reference for the value, see if we already created a
1312 // forward ref record.
1313 if (Val == 0) {
1314 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1315 I = ForwardRefVals.find(Name);
1316 if (I != ForwardRefVals.end())
1317 Val = I->second.first;
1318 }
1319
1320 // If we have the value in the symbol table or fwd-ref table, return it.
1321 if (Val) {
1322 if (Val->getType() == Ty) return Val;
1323 if (Ty == Type::LabelTy)
1324 P.Error(Loc, "'%" + Name + "' is not a basic block");
1325 else
1326 P.Error(Loc, "'%" + Name + "' defined with type '" +
1327 Val->getType()->getDescription() + "'");
1328 return 0;
1329 }
1330
1331 // Don't make placeholders with invalid type.
1332 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1333 P.Error(Loc, "invalid use of a non-first-class type");
1334 return 0;
1335 }
1336
1337 // Otherwise, create a new forward reference for this value and remember it.
1338 Value *FwdVal;
1339 if (Ty == Type::LabelTy)
1340 FwdVal = BasicBlock::Create(Name, &F);
1341 else
1342 FwdVal = new Argument(Ty, Name);
1343
1344 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1345 return FwdVal;
1346}
1347
1348Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1349 LocTy Loc) {
1350 // Look this name up in the normal function symbol table.
1351 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1352
1353 // If this is a forward reference for the value, see if we already created a
1354 // forward ref record.
1355 if (Val == 0) {
1356 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1357 I = ForwardRefValIDs.find(ID);
1358 if (I != ForwardRefValIDs.end())
1359 Val = I->second.first;
1360 }
1361
1362 // If we have the value in the symbol table or fwd-ref table, return it.
1363 if (Val) {
1364 if (Val->getType() == Ty) return Val;
1365 if (Ty == Type::LabelTy)
1366 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1367 else
1368 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1369 Val->getType()->getDescription() + "'");
1370 return 0;
1371 }
1372
1373 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1374 P.Error(Loc, "invalid use of a non-first-class type");
1375 return 0;
1376 }
1377
1378 // Otherwise, create a new forward reference for this value and remember it.
1379 Value *FwdVal;
1380 if (Ty == Type::LabelTy)
1381 FwdVal = BasicBlock::Create("", &F);
1382 else
1383 FwdVal = new Argument(Ty);
1384
1385 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1386 return FwdVal;
1387}
1388
1389/// SetInstName - After an instruction is parsed and inserted into its
1390/// basic block, this installs its name.
1391bool LLParser::PerFunctionState::SetInstName(int NameID,
1392 const std::string &NameStr,
1393 LocTy NameLoc, Instruction *Inst) {
1394 // If this instruction has void type, it cannot have a name or ID specified.
1395 if (Inst->getType() == Type::VoidTy) {
1396 if (NameID != -1 || !NameStr.empty())
1397 return P.Error(NameLoc, "instructions returning void cannot have a name");
1398 return false;
1399 }
1400
1401 // If this was a numbered instruction, verify that the instruction is the
1402 // expected value and resolve any forward references.
1403 if (NameStr.empty()) {
1404 // If neither a name nor an ID was specified, just use the next ID.
1405 if (NameID == -1)
1406 NameID = NumberedVals.size();
1407
1408 if (unsigned(NameID) != NumberedVals.size())
1409 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1410 utostr(NumberedVals.size()) + "'");
1411
1412 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1413 ForwardRefValIDs.find(NameID);
1414 if (FI != ForwardRefValIDs.end()) {
1415 if (FI->second.first->getType() != Inst->getType())
1416 return P.Error(NameLoc, "instruction forward referenced with type '" +
1417 FI->second.first->getType()->getDescription() + "'");
1418 FI->second.first->replaceAllUsesWith(Inst);
1419 ForwardRefValIDs.erase(FI);
1420 }
1421
1422 NumberedVals.push_back(Inst);
1423 return false;
1424 }
1425
1426 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1427 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1428 FI = ForwardRefVals.find(NameStr);
1429 if (FI != ForwardRefVals.end()) {
1430 if (FI->second.first->getType() != Inst->getType())
1431 return P.Error(NameLoc, "instruction forward referenced with type '" +
1432 FI->second.first->getType()->getDescription() + "'");
1433 FI->second.first->replaceAllUsesWith(Inst);
1434 ForwardRefVals.erase(FI);
1435 }
1436
1437 // Set the name on the instruction.
1438 Inst->setName(NameStr);
1439
1440 if (Inst->getNameStr() != NameStr)
1441 return P.Error(NameLoc, "multiple definition of local value named '" +
1442 NameStr + "'");
1443 return false;
1444}
1445
1446/// GetBB - Get a basic block with the specified name or ID, creating a
1447/// forward reference record if needed.
1448BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1449 LocTy Loc) {
1450 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1451}
1452
1453BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1454 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1455}
1456
1457/// DefineBB - Define the specified basic block, which is either named or
1458/// unnamed. If there is an error, this returns null otherwise it returns
1459/// the block being defined.
1460BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1461 LocTy Loc) {
1462 BasicBlock *BB;
1463 if (Name.empty())
1464 BB = GetBB(NumberedVals.size(), Loc);
1465 else
1466 BB = GetBB(Name, Loc);
1467 if (BB == 0) return 0; // Already diagnosed error.
1468
1469 // Move the block to the end of the function. Forward ref'd blocks are
1470 // inserted wherever they happen to be referenced.
1471 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1472
1473 // Remove the block from forward ref sets.
1474 if (Name.empty()) {
1475 ForwardRefValIDs.erase(NumberedVals.size());
1476 NumberedVals.push_back(BB);
1477 } else {
1478 // BB forward references are already in the function symbol table.
1479 ForwardRefVals.erase(Name);
1480 }
1481
1482 return BB;
1483}
1484
1485//===----------------------------------------------------------------------===//
1486// Constants.
1487//===----------------------------------------------------------------------===//
1488
1489/// ParseValID - Parse an abstract value that doesn't necessarily have a
1490/// type implied. For example, if we parse "4" we don't know what integer type
1491/// it has. The value will later be combined with its type and checked for
1492/// sanity.
1493bool LLParser::ParseValID(ValID &ID) {
1494 ID.Loc = Lex.getLoc();
1495 switch (Lex.getKind()) {
1496 default: return TokError("expected value token");
1497 case lltok::GlobalID: // @42
1498 ID.UIntVal = Lex.getUIntVal();
1499 ID.Kind = ValID::t_GlobalID;
1500 break;
1501 case lltok::GlobalVar: // @foo
1502 ID.StrVal = Lex.getStrVal();
1503 ID.Kind = ValID::t_GlobalName;
1504 break;
1505 case lltok::LocalVarID: // %42
1506 ID.UIntVal = Lex.getUIntVal();
1507 ID.Kind = ValID::t_LocalID;
1508 break;
1509 case lltok::LocalVar: // %foo
1510 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1511 ID.StrVal = Lex.getStrVal();
1512 ID.Kind = ValID::t_LocalName;
1513 break;
1514 case lltok::APSInt:
1515 ID.APSIntVal = Lex.getAPSIntVal();
1516 ID.Kind = ValID::t_APSInt;
1517 break;
1518 case lltok::APFloat:
1519 ID.APFloatVal = Lex.getAPFloatVal();
1520 ID.Kind = ValID::t_APFloat;
1521 break;
1522 case lltok::kw_true:
1523 ID.ConstantVal = ConstantInt::getTrue();
1524 ID.Kind = ValID::t_Constant;
1525 break;
1526 case lltok::kw_false:
1527 ID.ConstantVal = ConstantInt::getFalse();
1528 ID.Kind = ValID::t_Constant;
1529 break;
1530 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1531 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1532 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1533
1534 case lltok::lbrace: {
1535 // ValID ::= '{' ConstVector '}'
1536 Lex.Lex();
1537 SmallVector<Constant*, 16> Elts;
1538 if (ParseGlobalValueVector(Elts) ||
1539 ParseToken(lltok::rbrace, "expected end of struct constant"))
1540 return true;
1541
1542 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1543 ID.Kind = ValID::t_Constant;
1544 return false;
1545 }
1546 case lltok::less: {
1547 // ValID ::= '<' ConstVector '>' --> Vector.
1548 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1549 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001550 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001551
1552 SmallVector<Constant*, 16> Elts;
1553 LocTy FirstEltLoc = Lex.getLoc();
1554 if (ParseGlobalValueVector(Elts) ||
1555 (isPackedStruct &&
1556 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1557 ParseToken(lltok::greater, "expected end of constant"))
1558 return true;
1559
1560 if (isPackedStruct) {
1561 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1562 ID.Kind = ValID::t_Constant;
1563 return false;
1564 }
1565
1566 if (Elts.empty())
1567 return Error(ID.Loc, "constant vector must not be empty");
1568
1569 if (!Elts[0]->getType()->isInteger() &&
1570 !Elts[0]->getType()->isFloatingPoint())
1571 return Error(FirstEltLoc,
1572 "vector elements must have integer or floating point type");
1573
1574 // Verify that all the vector elements have the same type.
1575 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1576 if (Elts[i]->getType() != Elts[0]->getType())
1577 return Error(FirstEltLoc,
1578 "vector element #" + utostr(i) +
1579 " is not of type '" + Elts[0]->getType()->getDescription());
1580
1581 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1582 ID.Kind = ValID::t_Constant;
1583 return false;
1584 }
1585 case lltok::lsquare: { // Array Constant
1586 Lex.Lex();
1587 SmallVector<Constant*, 16> Elts;
1588 LocTy FirstEltLoc = Lex.getLoc();
1589 if (ParseGlobalValueVector(Elts) ||
1590 ParseToken(lltok::rsquare, "expected end of array constant"))
1591 return true;
1592
1593 // Handle empty element.
1594 if (Elts.empty()) {
1595 // Use undef instead of an array because it's inconvenient to determine
1596 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001597 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 return false;
1599 }
1600
1601 if (!Elts[0]->getType()->isFirstClassType())
1602 return Error(FirstEltLoc, "invalid array element type: " +
1603 Elts[0]->getType()->getDescription());
1604
1605 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1606
1607 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001608 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001609 if (Elts[i]->getType() != Elts[0]->getType())
1610 return Error(FirstEltLoc,
1611 "array element #" + utostr(i) +
1612 " is not of type '" +Elts[0]->getType()->getDescription());
1613 }
1614
1615 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1616 ID.Kind = ValID::t_Constant;
1617 return false;
1618 }
1619 case lltok::kw_c: // c "foo"
1620 Lex.Lex();
1621 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1622 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1623 ID.Kind = ValID::t_Constant;
1624 return false;
1625
1626 case lltok::kw_asm: {
1627 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1628 bool HasSideEffect;
1629 Lex.Lex();
1630 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001631 ParseStringConstant(ID.StrVal) ||
1632 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001633 ParseToken(lltok::StringConstant, "expected constraint string"))
1634 return true;
1635 ID.StrVal2 = Lex.getStrVal();
1636 ID.UIntVal = HasSideEffect;
1637 ID.Kind = ValID::t_InlineAsm;
1638 return false;
1639 }
1640
1641 case lltok::kw_trunc:
1642 case lltok::kw_zext:
1643 case lltok::kw_sext:
1644 case lltok::kw_fptrunc:
1645 case lltok::kw_fpext:
1646 case lltok::kw_bitcast:
1647 case lltok::kw_uitofp:
1648 case lltok::kw_sitofp:
1649 case lltok::kw_fptoui:
1650 case lltok::kw_fptosi:
1651 case lltok::kw_inttoptr:
1652 case lltok::kw_ptrtoint: {
1653 unsigned Opc = Lex.getUIntVal();
1654 PATypeHolder DestTy(Type::VoidTy);
1655 Constant *SrcVal;
1656 Lex.Lex();
1657 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1658 ParseGlobalTypeAndValue(SrcVal) ||
1659 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1660 ParseType(DestTy) ||
1661 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1662 return true;
1663 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1664 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1665 SrcVal->getType()->getDescription() + "' to '" +
1666 DestTy->getDescription() + "'");
1667 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1668 DestTy);
1669 ID.Kind = ValID::t_Constant;
1670 return false;
1671 }
1672 case lltok::kw_extractvalue: {
1673 Lex.Lex();
1674 Constant *Val;
1675 SmallVector<unsigned, 4> Indices;
1676 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1677 ParseGlobalTypeAndValue(Val) ||
1678 ParseIndexList(Indices) ||
1679 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1680 return true;
1681 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1682 return Error(ID.Loc, "extractvalue operand must be array or struct");
1683 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1684 Indices.end()))
1685 return Error(ID.Loc, "invalid indices for extractvalue");
1686 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1687 &Indices[0], Indices.size());
1688 ID.Kind = ValID::t_Constant;
1689 return false;
1690 }
1691 case lltok::kw_insertvalue: {
1692 Lex.Lex();
1693 Constant *Val0, *Val1;
1694 SmallVector<unsigned, 4> Indices;
1695 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1696 ParseGlobalTypeAndValue(Val0) ||
1697 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1698 ParseGlobalTypeAndValue(Val1) ||
1699 ParseIndexList(Indices) ||
1700 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1701 return true;
1702 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1703 return Error(ID.Loc, "extractvalue operand must be array or struct");
1704 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1705 Indices.end()))
1706 return Error(ID.Loc, "invalid indices for insertvalue");
1707 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1708 &Indices[0], Indices.size());
1709 ID.Kind = ValID::t_Constant;
1710 return false;
1711 }
1712 case lltok::kw_icmp:
1713 case lltok::kw_fcmp:
1714 case lltok::kw_vicmp:
1715 case lltok::kw_vfcmp: {
1716 unsigned PredVal, Opc = Lex.getUIntVal();
1717 Constant *Val0, *Val1;
1718 Lex.Lex();
1719 if (ParseCmpPredicate(PredVal, Opc) ||
1720 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1721 ParseGlobalTypeAndValue(Val0) ||
1722 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1723 ParseGlobalTypeAndValue(Val1) ||
1724 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1725 return true;
1726
1727 if (Val0->getType() != Val1->getType())
1728 return Error(ID.Loc, "compare operands must have the same type");
1729
1730 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1731
1732 if (Opc == Instruction::FCmp) {
1733 if (!Val0->getType()->isFPOrFPVector())
1734 return Error(ID.Loc, "fcmp requires floating point operands");
1735 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1736 } else if (Opc == Instruction::ICmp) {
1737 if (!Val0->getType()->isIntOrIntVector() &&
1738 !isa<PointerType>(Val0->getType()))
1739 return Error(ID.Loc, "icmp requires pointer or integer operands");
1740 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1741 } else if (Opc == Instruction::VFCmp) {
1742 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001743 if (!Val0->getType()->isFPOrFPVector() ||
1744 !isa<VectorType>(Val0->getType()))
1745 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1747 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001748 // FIXME: REMOVE VICMP Support
1749 if (!Val0->getType()->isIntOrIntVector() ||
1750 !isa<VectorType>(Val0->getType()))
1751 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1753 }
1754 ID.Kind = ValID::t_Constant;
1755 return false;
1756 }
1757
1758 // Binary Operators.
1759 case lltok::kw_add:
1760 case lltok::kw_sub:
1761 case lltok::kw_mul:
1762 case lltok::kw_udiv:
1763 case lltok::kw_sdiv:
1764 case lltok::kw_fdiv:
1765 case lltok::kw_urem:
1766 case lltok::kw_srem:
1767 case lltok::kw_frem: {
1768 unsigned Opc = Lex.getUIntVal();
1769 Constant *Val0, *Val1;
1770 Lex.Lex();
1771 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1772 ParseGlobalTypeAndValue(Val0) ||
1773 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1774 ParseGlobalTypeAndValue(Val1) ||
1775 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1776 return true;
1777 if (Val0->getType() != Val1->getType())
1778 return Error(ID.Loc, "operands of constexpr must have same type");
1779 if (!Val0->getType()->isIntOrIntVector() &&
1780 !Val0->getType()->isFPOrFPVector())
1781 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1782 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1783 ID.Kind = ValID::t_Constant;
1784 return false;
1785 }
1786
1787 // Logical Operations
1788 case lltok::kw_shl:
1789 case lltok::kw_lshr:
1790 case lltok::kw_ashr:
1791 case lltok::kw_and:
1792 case lltok::kw_or:
1793 case lltok::kw_xor: {
1794 unsigned Opc = Lex.getUIntVal();
1795 Constant *Val0, *Val1;
1796 Lex.Lex();
1797 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1798 ParseGlobalTypeAndValue(Val0) ||
1799 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1800 ParseGlobalTypeAndValue(Val1) ||
1801 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1802 return true;
1803 if (Val0->getType() != Val1->getType())
1804 return Error(ID.Loc, "operands of constexpr must have same type");
1805 if (!Val0->getType()->isIntOrIntVector())
1806 return Error(ID.Loc,
1807 "constexpr requires integer or integer vector operands");
1808 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1809 ID.Kind = ValID::t_Constant;
1810 return false;
1811 }
1812
1813 case lltok::kw_getelementptr:
1814 case lltok::kw_shufflevector:
1815 case lltok::kw_insertelement:
1816 case lltok::kw_extractelement:
1817 case lltok::kw_select: {
1818 unsigned Opc = Lex.getUIntVal();
1819 SmallVector<Constant*, 16> Elts;
1820 Lex.Lex();
1821 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1822 ParseGlobalValueVector(Elts) ||
1823 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1824 return true;
1825
1826 if (Opc == Instruction::GetElementPtr) {
1827 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1828 return Error(ID.Loc, "getelementptr requires pointer operand");
1829
1830 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1831 (Value**)&Elts[1], Elts.size()-1))
1832 return Error(ID.Loc, "invalid indices for getelementptr");
1833 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1834 &Elts[1], Elts.size()-1);
1835 } else if (Opc == Instruction::Select) {
1836 if (Elts.size() != 3)
1837 return Error(ID.Loc, "expected three operands to select");
1838 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1839 Elts[2]))
1840 return Error(ID.Loc, Reason);
1841 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1842 } else if (Opc == Instruction::ShuffleVector) {
1843 if (Elts.size() != 3)
1844 return Error(ID.Loc, "expected three operands to shufflevector");
1845 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1846 return Error(ID.Loc, "invalid operands to shufflevector");
1847 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1848 } else if (Opc == Instruction::ExtractElement) {
1849 if (Elts.size() != 2)
1850 return Error(ID.Loc, "expected two operands to extractelement");
1851 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1852 return Error(ID.Loc, "invalid extractelement operands");
1853 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1854 } else {
1855 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1856 if (Elts.size() != 3)
1857 return Error(ID.Loc, "expected three operands to insertelement");
1858 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1859 return Error(ID.Loc, "invalid insertelement operands");
1860 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1861 }
1862
1863 ID.Kind = ValID::t_Constant;
1864 return false;
1865 }
1866 }
1867
1868 Lex.Lex();
1869 return false;
1870}
1871
1872/// ParseGlobalValue - Parse a global value with the specified type.
1873bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1874 V = 0;
1875 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001876 return ParseValID(ID) ||
1877 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001878}
1879
1880/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1881/// constant.
1882bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1883 Constant *&V) {
1884 if (isa<FunctionType>(Ty))
1885 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1886
1887 switch (ID.Kind) {
1888 default: assert(0 && "Unknown ValID!");
1889 case ValID::t_LocalID:
1890 case ValID::t_LocalName:
1891 return Error(ID.Loc, "invalid use of function-local name");
1892 case ValID::t_InlineAsm:
1893 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1894 case ValID::t_GlobalName:
1895 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1896 return V == 0;
1897 case ValID::t_GlobalID:
1898 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1899 return V == 0;
1900 case ValID::t_APSInt:
1901 if (!isa<IntegerType>(Ty))
1902 return Error(ID.Loc, "integer constant must have integer type");
1903 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1904 V = ConstantInt::get(ID.APSIntVal);
1905 return false;
1906 case ValID::t_APFloat:
1907 if (!Ty->isFloatingPoint() ||
1908 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1909 return Error(ID.Loc, "floating point constant invalid for type");
1910
1911 // The lexer has no type info, so builds all float and double FP constants
1912 // as double. Fix this here. Long double does not need this.
1913 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1914 Ty == Type::FloatTy) {
1915 bool Ignored;
1916 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1917 &Ignored);
1918 }
1919 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001920
1921 if (V->getType() != Ty)
1922 return Error(ID.Loc, "floating point constant does not have type '" +
1923 Ty->getDescription() + "'");
1924
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 return false;
1926 case ValID::t_Null:
1927 if (!isa<PointerType>(Ty))
1928 return Error(ID.Loc, "null must be a pointer type");
1929 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1930 return false;
1931 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001932 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00001933 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1934 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001935 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00001936 V = UndefValue::get(Ty);
1937 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00001938 case ValID::t_EmptyArray:
1939 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1940 return Error(ID.Loc, "invalid empty array initializer");
1941 V = UndefValue::get(Ty);
1942 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001944 // FIXME: LabelTy should not be a first-class type.
1945 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00001946 return Error(ID.Loc, "invalid type for null constant");
1947 V = Constant::getNullValue(Ty);
1948 return false;
1949 case ValID::t_Constant:
1950 if (ID.ConstantVal->getType() != Ty)
1951 return Error(ID.Loc, "constant expression type mismatch");
1952 V = ID.ConstantVal;
1953 return false;
1954 }
1955}
1956
1957bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1958 PATypeHolder Type(Type::VoidTy);
1959 return ParseType(Type) ||
1960 ParseGlobalValue(Type, V);
1961}
1962
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001963/// ParseGlobalValueVector
1964/// ::= /*empty*/
1965/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00001966bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1967 // Empty list.
1968 if (Lex.getKind() == lltok::rbrace ||
1969 Lex.getKind() == lltok::rsquare ||
1970 Lex.getKind() == lltok::greater ||
1971 Lex.getKind() == lltok::rparen)
1972 return false;
1973
1974 Constant *C;
1975 if (ParseGlobalTypeAndValue(C)) return true;
1976 Elts.push_back(C);
1977
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001978 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 if (ParseGlobalTypeAndValue(C)) return true;
1980 Elts.push_back(C);
1981 }
1982
1983 return false;
1984}
1985
1986
1987//===----------------------------------------------------------------------===//
1988// Function Parsing.
1989//===----------------------------------------------------------------------===//
1990
1991bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1992 PerFunctionState &PFS) {
1993 if (ID.Kind == ValID::t_LocalID)
1994 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
1995 else if (ID.Kind == ValID::t_LocalName)
1996 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
1997 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
1998 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1999 const FunctionType *FTy =
2000 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2001 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2002 return Error(ID.Loc, "invalid type for inline asm constraint string");
2003 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2004 return false;
2005 } else {
2006 Constant *C;
2007 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2008 V = C;
2009 return false;
2010 }
2011
2012 return V == 0;
2013}
2014
2015bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2016 V = 0;
2017 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002018 return ParseValID(ID) ||
2019 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002020}
2021
2022bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2023 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002024 return ParseType(T) ||
2025 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002026}
2027
2028/// FunctionHeader
2029/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2030/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2031/// OptionalAlign OptGC
2032bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2033 // Parse the linkage.
2034 LocTy LinkageLoc = Lex.getLoc();
2035 unsigned Linkage;
2036
2037 unsigned Visibility, CC, RetAttrs;
2038 PATypeHolder RetType(Type::VoidTy);
2039 LocTy RetTypeLoc = Lex.getLoc();
2040 if (ParseOptionalLinkage(Linkage) ||
2041 ParseOptionalVisibility(Visibility) ||
2042 ParseOptionalCallingConv(CC) ||
2043 ParseOptionalAttrs(RetAttrs, 1) ||
2044 ParseType(RetType, RetTypeLoc))
2045 return true;
2046
2047 // Verify that the linkage is ok.
2048 switch ((GlobalValue::LinkageTypes)Linkage) {
2049 case GlobalValue::ExternalLinkage:
2050 break; // always ok.
2051 case GlobalValue::DLLImportLinkage:
2052 case GlobalValue::ExternalWeakLinkage:
2053 if (isDefine)
2054 return Error(LinkageLoc, "invalid linkage for function definition");
2055 break;
2056 case GlobalValue::InternalLinkage:
2057 case GlobalValue::LinkOnceLinkage:
2058 case GlobalValue::WeakLinkage:
2059 case GlobalValue::DLLExportLinkage:
2060 if (!isDefine)
2061 return Error(LinkageLoc, "invalid linkage for function declaration");
2062 break;
2063 case GlobalValue::AppendingLinkage:
2064 case GlobalValue::GhostLinkage:
2065 case GlobalValue::CommonLinkage:
2066 return Error(LinkageLoc, "invalid function linkage type");
2067 }
2068
Chris Lattner99bb3152009-01-05 08:00:30 +00002069 if (!FunctionType::isValidReturnType(RetType) ||
2070 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002071 return Error(RetTypeLoc, "invalid function return type");
2072
2073 if (Lex.getKind() != lltok::GlobalVar)
2074 return TokError("expected function name");
2075
2076 LocTy NameLoc = Lex.getLoc();
2077 std::string FunctionName = Lex.getStrVal();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002078 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002079
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002080 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 return TokError("expected '(' in function argument list");
2082
2083 std::vector<ArgInfo> ArgList;
2084 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002087 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002088 std::string GC;
2089
2090 if (ParseArgumentList(ArgList, isVarArg) ||
2091 ParseOptionalAttrs(FuncAttrs, 2) ||
2092 (EatIfPresent(lltok::kw_section) &&
2093 ParseStringConstant(Section)) ||
2094 ParseOptionalAlignment(Alignment) ||
2095 (EatIfPresent(lltok::kw_gc) &&
2096 ParseStringConstant(GC)))
2097 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002098
2099 // If the alignment was parsed as an attribute, move to the alignment field.
2100 if (FuncAttrs & Attribute::Alignment) {
2101 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2102 FuncAttrs &= ~Attribute::Alignment;
2103 }
2104
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 // Okay, if we got here, the function is syntactically valid. Convert types
2106 // and do semantic checks.
2107 std::vector<const Type*> ParamTypeList;
2108 SmallVector<AttributeWithIndex, 8> Attrs;
2109 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2110 // attributes.
2111 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2112 if (FuncAttrs & ObsoleteFuncAttrs) {
2113 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2114 FuncAttrs &= ~ObsoleteFuncAttrs;
2115 }
2116
2117 if (RetAttrs != Attribute::None)
2118 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2119
2120 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2121 ParamTypeList.push_back(ArgList[i].Type);
2122 if (ArgList[i].Attrs != Attribute::None)
2123 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2124 }
2125
2126 if (FuncAttrs != Attribute::None)
2127 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2128
2129 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2130
2131 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2132 const PointerType *PFT = PointerType::getUnqual(FT);
2133
2134 Fn = 0;
2135 if (!FunctionName.empty()) {
2136 // If this was a definition of a forward reference, remove the definition
2137 // from the forward reference table and fill in the forward ref.
2138 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2139 ForwardRefVals.find(FunctionName);
2140 if (FRVI != ForwardRefVals.end()) {
2141 Fn = M->getFunction(FunctionName);
2142 ForwardRefVals.erase(FRVI);
2143 } else if ((Fn = M->getFunction(FunctionName))) {
2144 // If this function already exists in the symbol table, then it is
2145 // multiply defined. We accept a few cases for old backwards compat.
2146 // FIXME: Remove this stuff for LLVM 3.0.
2147 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2148 (!Fn->isDeclaration() && isDefine)) {
2149 // If the redefinition has different type or different attributes,
2150 // reject it. If both have bodies, reject it.
2151 return Error(NameLoc, "invalid redefinition of function '" +
2152 FunctionName + "'");
2153 } else if (Fn->isDeclaration()) {
2154 // Make sure to strip off any argument names so we can't get conflicts.
2155 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2156 AI != AE; ++AI)
2157 AI->setName("");
2158 }
2159 }
2160
2161 } else if (FunctionName.empty()) {
2162 // If this is a definition of a forward referenced function, make sure the
2163 // types agree.
2164 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2165 = ForwardRefValIDs.find(NumberedVals.size());
2166 if (I != ForwardRefValIDs.end()) {
2167 Fn = cast<Function>(I->second.first);
2168 if (Fn->getType() != PFT)
2169 return Error(NameLoc, "type of definition and forward reference of '@" +
2170 utostr(NumberedVals.size()) +"' disagree");
2171 ForwardRefValIDs.erase(I);
2172 }
2173 }
2174
2175 if (Fn == 0)
2176 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2177 else // Move the forward-reference to the correct spot in the module.
2178 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2179
2180 if (FunctionName.empty())
2181 NumberedVals.push_back(Fn);
2182
2183 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2184 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2185 Fn->setCallingConv(CC);
2186 Fn->setAttributes(PAL);
2187 Fn->setAlignment(Alignment);
2188 Fn->setSection(Section);
2189 if (!GC.empty()) Fn->setGC(GC.c_str());
2190
2191 // Add all of the arguments we parsed to the function.
2192 Function::arg_iterator ArgIt = Fn->arg_begin();
2193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2194 // If the argument has a name, insert it into the argument symbol table.
2195 if (ArgList[i].Name.empty()) continue;
2196
2197 // Set the name, if it conflicted, it will be auto-renamed.
2198 ArgIt->setName(ArgList[i].Name);
2199
2200 if (ArgIt->getNameStr() != ArgList[i].Name)
2201 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2202 ArgList[i].Name + "'");
2203 }
2204
2205 return false;
2206}
2207
2208
2209/// ParseFunctionBody
2210/// ::= '{' BasicBlock+ '}'
2211/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2212///
2213bool LLParser::ParseFunctionBody(Function &Fn) {
2214 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2215 return TokError("expected '{' in function body");
2216 Lex.Lex(); // eat the {.
2217
2218 PerFunctionState PFS(*this, Fn);
2219
2220 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2221 if (ParseBasicBlock(PFS)) return true;
2222
2223 // Eat the }.
2224 Lex.Lex();
2225
2226 // Verify function is ok.
2227 return PFS.VerifyFunctionComplete();
2228}
2229
2230/// ParseBasicBlock
2231/// ::= LabelStr? Instruction*
2232bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2233 // If this basic block starts out with a name, remember it.
2234 std::string Name;
2235 LocTy NameLoc = Lex.getLoc();
2236 if (Lex.getKind() == lltok::LabelStr) {
2237 Name = Lex.getStrVal();
2238 Lex.Lex();
2239 }
2240
2241 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2242 if (BB == 0) return true;
2243
2244 std::string NameStr;
2245
2246 // Parse the instructions in this block until we get a terminator.
2247 Instruction *Inst;
2248 do {
2249 // This instruction may have three possibilities for a name: a) none
2250 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2251 LocTy NameLoc = Lex.getLoc();
2252 int NameID = -1;
2253 NameStr = "";
2254
2255 if (Lex.getKind() == lltok::LocalVarID) {
2256 NameID = Lex.getUIntVal();
2257 Lex.Lex();
2258 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2259 return true;
2260 } else if (Lex.getKind() == lltok::LocalVar ||
2261 // FIXME: REMOVE IN LLVM 3.0
2262 Lex.getKind() == lltok::StringConstant) {
2263 NameStr = Lex.getStrVal();
2264 Lex.Lex();
2265 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2266 return true;
2267 }
2268
2269 if (ParseInstruction(Inst, BB, PFS)) return true;
2270
2271 BB->getInstList().push_back(Inst);
2272
2273 // Set the name on the instruction.
2274 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2275 } while (!isa<TerminatorInst>(Inst));
2276
2277 return false;
2278}
2279
2280//===----------------------------------------------------------------------===//
2281// Instruction Parsing.
2282//===----------------------------------------------------------------------===//
2283
2284/// ParseInstruction - Parse one of the many different instructions.
2285///
2286bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2287 PerFunctionState &PFS) {
2288 lltok::Kind Token = Lex.getKind();
2289 if (Token == lltok::Eof)
2290 return TokError("found end of file when expecting more instructions");
2291 LocTy Loc = Lex.getLoc();
2292 Lex.Lex(); // Eat the keyword.
2293
2294 switch (Token) {
2295 default: return Error(Loc, "expected instruction opcode");
2296 // Terminator Instructions.
2297 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2298 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2299 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2300 case lltok::kw_br: return ParseBr(Inst, PFS);
2301 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2302 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2303 // Binary Operators.
2304 case lltok::kw_add:
2305 case lltok::kw_sub:
Chris Lattnere914b592009-01-05 08:24:46 +00002306 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2307
Chris Lattnerdf986172009-01-02 07:01:27 +00002308 case lltok::kw_udiv:
2309 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002310 case lltok::kw_urem:
Chris Lattnere914b592009-01-05 08:24:46 +00002311 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2312 case lltok::kw_fdiv:
2313 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 case lltok::kw_shl:
2315 case lltok::kw_lshr:
2316 case lltok::kw_ashr:
2317 case lltok::kw_and:
2318 case lltok::kw_or:
2319 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2320 case lltok::kw_icmp:
2321 case lltok::kw_fcmp:
2322 case lltok::kw_vicmp:
2323 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2324 // Casts.
2325 case lltok::kw_trunc:
2326 case lltok::kw_zext:
2327 case lltok::kw_sext:
2328 case lltok::kw_fptrunc:
2329 case lltok::kw_fpext:
2330 case lltok::kw_bitcast:
2331 case lltok::kw_uitofp:
2332 case lltok::kw_sitofp:
2333 case lltok::kw_fptoui:
2334 case lltok::kw_fptosi:
2335 case lltok::kw_inttoptr:
2336 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2337 // Other.
2338 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002339 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2341 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2342 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2343 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2344 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2345 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2346 // Memory.
2347 case lltok::kw_alloca:
2348 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2349 case lltok::kw_free: return ParseFree(Inst, PFS);
2350 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2351 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2352 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002353 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002354 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002355 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002356 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002357 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2360 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2361 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2362 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2363 }
2364}
2365
2366/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2367bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2368 // FIXME: REMOVE vicmp/vfcmp!
2369 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2370 switch (Lex.getKind()) {
2371 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2372 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2373 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2374 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2375 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2376 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2377 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2378 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2379 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2380 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2381 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2382 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2383 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2384 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2385 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2386 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2387 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2388 }
2389 } else {
2390 switch (Lex.getKind()) {
2391 default: TokError("expected icmp predicate (e.g. 'eq')");
2392 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2393 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2394 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2395 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2396 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2397 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2398 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2399 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2400 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2401 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2402 }
2403 }
2404 Lex.Lex();
2405 return false;
2406}
2407
2408//===----------------------------------------------------------------------===//
2409// Terminator Instructions.
2410//===----------------------------------------------------------------------===//
2411
2412/// ParseRet - Parse a return instruction.
2413/// ::= 'ret' void
2414/// ::= 'ret' TypeAndValue
2415/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2416bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2417 PerFunctionState &PFS) {
2418 PATypeHolder Ty(Type::VoidTy);
2419 if (ParseType(Ty)) return true;
2420
2421 if (Ty == Type::VoidTy) {
2422 Inst = ReturnInst::Create();
2423 return false;
2424 }
2425
2426 Value *RV;
2427 if (ParseValue(Ty, RV, PFS)) return true;
2428
2429 // The normal case is one return value.
2430 if (Lex.getKind() == lltok::comma) {
2431 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2432 // of 'ret {i32,i32} {i32 1, i32 2}'
2433 SmallVector<Value*, 8> RVs;
2434 RVs.push_back(RV);
2435
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002436 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 if (ParseTypeAndValue(RV, PFS)) return true;
2438 RVs.push_back(RV);
2439 }
2440
2441 RV = UndefValue::get(PFS.getFunction().getReturnType());
2442 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2443 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2444 BB->getInstList().push_back(I);
2445 RV = I;
2446 }
2447 }
2448 Inst = ReturnInst::Create(RV);
2449 return false;
2450}
2451
2452
2453/// ParseBr
2454/// ::= 'br' TypeAndValue
2455/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2456bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2457 LocTy Loc, Loc2;
2458 Value *Op0, *Op1, *Op2;
2459 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2460
2461 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2462 Inst = BranchInst::Create(BB);
2463 return false;
2464 }
2465
2466 if (Op0->getType() != Type::Int1Ty)
2467 return Error(Loc, "branch condition must have 'i1' type");
2468
2469 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2470 ParseTypeAndValue(Op1, Loc, PFS) ||
2471 ParseToken(lltok::comma, "expected ',' after true destination") ||
2472 ParseTypeAndValue(Op2, Loc2, PFS))
2473 return true;
2474
2475 if (!isa<BasicBlock>(Op1))
2476 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002477 if (!isa<BasicBlock>(Op2))
2478 return Error(Loc2, "true destination of branch must be a basic block");
2479
2480 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2481 return false;
2482}
2483
2484/// ParseSwitch
2485/// Instruction
2486/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2487/// JumpTable
2488/// ::= (TypeAndValue ',' TypeAndValue)*
2489bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2490 LocTy CondLoc, BBLoc;
2491 Value *Cond, *DefaultBB;
2492 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2493 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2494 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2495 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2496 return true;
2497
2498 if (!isa<IntegerType>(Cond->getType()))
2499 return Error(CondLoc, "switch condition must have integer type");
2500 if (!isa<BasicBlock>(DefaultBB))
2501 return Error(BBLoc, "default destination must be a basic block");
2502
2503 // Parse the jump table pairs.
2504 SmallPtrSet<Value*, 32> SeenCases;
2505 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2506 while (Lex.getKind() != lltok::rsquare) {
2507 Value *Constant, *DestBB;
2508
2509 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2510 ParseToken(lltok::comma, "expected ',' after case value") ||
2511 ParseTypeAndValue(DestBB, BBLoc, PFS))
2512 return true;
2513
2514 if (!SeenCases.insert(Constant))
2515 return Error(CondLoc, "duplicate case value in switch");
2516 if (!isa<ConstantInt>(Constant))
2517 return Error(CondLoc, "case value is not a constant integer");
2518 if (!isa<BasicBlock>(DestBB))
2519 return Error(BBLoc, "case destination is not a basic block");
2520
2521 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2522 cast<BasicBlock>(DestBB)));
2523 }
2524
2525 Lex.Lex(); // Eat the ']'.
2526
2527 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2528 Table.size());
2529 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2530 SI->addCase(Table[i].first, Table[i].second);
2531 Inst = SI;
2532 return false;
2533}
2534
2535/// ParseInvoke
2536/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2537/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2538bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2539 LocTy CallLoc = Lex.getLoc();
2540 unsigned CC, RetAttrs, FnAttrs;
2541 PATypeHolder RetType(Type::VoidTy);
2542 LocTy RetTypeLoc;
2543 ValID CalleeID;
2544 SmallVector<ParamInfo, 16> ArgList;
2545
2546 Value *NormalBB, *UnwindBB;
2547 if (ParseOptionalCallingConv(CC) ||
2548 ParseOptionalAttrs(RetAttrs, 1) ||
2549 ParseType(RetType, RetTypeLoc) ||
2550 ParseValID(CalleeID) ||
2551 ParseParameterList(ArgList, PFS) ||
2552 ParseOptionalAttrs(FnAttrs, 2) ||
2553 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2554 ParseTypeAndValue(NormalBB, PFS) ||
2555 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2556 ParseTypeAndValue(UnwindBB, PFS))
2557 return true;
2558
2559 if (!isa<BasicBlock>(NormalBB))
2560 return Error(CallLoc, "normal destination is not a basic block");
2561 if (!isa<BasicBlock>(UnwindBB))
2562 return Error(CallLoc, "unwind destination is not a basic block");
2563
2564 // If RetType is a non-function pointer type, then this is the short syntax
2565 // for the call, which means that RetType is just the return type. Infer the
2566 // rest of the function argument types from the arguments that are present.
2567 const PointerType *PFTy = 0;
2568 const FunctionType *Ty = 0;
2569 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2570 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2571 // Pull out the types of all of the arguments...
2572 std::vector<const Type*> ParamTypes;
2573 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2574 ParamTypes.push_back(ArgList[i].V->getType());
2575
2576 if (!FunctionType::isValidReturnType(RetType))
2577 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2578
2579 Ty = FunctionType::get(RetType, ParamTypes, false);
2580 PFTy = PointerType::getUnqual(Ty);
2581 }
2582
2583 // Look up the callee.
2584 Value *Callee;
2585 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2586
2587 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2588 // function attributes.
2589 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2590 if (FnAttrs & ObsoleteFuncAttrs) {
2591 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2592 FnAttrs &= ~ObsoleteFuncAttrs;
2593 }
2594
2595 // Set up the Attributes for the function.
2596 SmallVector<AttributeWithIndex, 8> Attrs;
2597 if (RetAttrs != Attribute::None)
2598 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2599
2600 SmallVector<Value*, 8> Args;
2601
2602 // Loop through FunctionType's arguments and ensure they are specified
2603 // correctly. Also, gather any parameter attributes.
2604 FunctionType::param_iterator I = Ty->param_begin();
2605 FunctionType::param_iterator E = Ty->param_end();
2606 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2607 const Type *ExpectedTy = 0;
2608 if (I != E) {
2609 ExpectedTy = *I++;
2610 } else if (!Ty->isVarArg()) {
2611 return Error(ArgList[i].Loc, "too many arguments specified");
2612 }
2613
2614 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2615 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2616 ExpectedTy->getDescription() + "'");
2617 Args.push_back(ArgList[i].V);
2618 if (ArgList[i].Attrs != Attribute::None)
2619 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2620 }
2621
2622 if (I != E)
2623 return Error(CallLoc, "not enough parameters specified for call");
2624
2625 if (FnAttrs != Attribute::None)
2626 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2627
2628 // Finish off the Attributes and check them
2629 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2630
2631 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2632 cast<BasicBlock>(UnwindBB),
2633 Args.begin(), Args.end());
2634 II->setCallingConv(CC);
2635 II->setAttributes(PAL);
2636 Inst = II;
2637 return false;
2638}
2639
2640
2641
2642//===----------------------------------------------------------------------===//
2643// Binary Operators.
2644//===----------------------------------------------------------------------===//
2645
2646/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002647/// ::= ArithmeticOps TypeAndValue ',' Value
2648///
2649/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2650/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002651bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002652 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002653 LocTy Loc; Value *LHS, *RHS;
2654 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2655 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2656 ParseValue(LHS->getType(), RHS, PFS))
2657 return true;
2658
Chris Lattnere914b592009-01-05 08:24:46 +00002659 bool Valid;
2660 switch (OperandType) {
2661 default: assert(0 && "Unknown operand type!");
2662 case 0: // int or FP.
2663 Valid = LHS->getType()->isIntOrIntVector() ||
2664 LHS->getType()->isFPOrFPVector();
2665 break;
2666 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2667 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2668 }
2669
2670 if (!Valid)
2671 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002672
2673 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2674 return false;
2675}
2676
2677/// ParseLogical
2678/// ::= ArithmeticOps TypeAndValue ',' Value {
2679bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2680 unsigned Opc) {
2681 LocTy Loc; Value *LHS, *RHS;
2682 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2683 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2684 ParseValue(LHS->getType(), RHS, PFS))
2685 return true;
2686
2687 if (!LHS->getType()->isIntOrIntVector())
2688 return Error(Loc,"instruction requires integer or integer vector operands");
2689
2690 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2691 return false;
2692}
2693
2694
2695/// ParseCompare
2696/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2697/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2698/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2699/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2700bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2701 unsigned Opc) {
2702 // Parse the integer/fp comparison predicate.
2703 LocTy Loc;
2704 unsigned Pred;
2705 Value *LHS, *RHS;
2706 if (ParseCmpPredicate(Pred, Opc) ||
2707 ParseTypeAndValue(LHS, Loc, PFS) ||
2708 ParseToken(lltok::comma, "expected ',' after compare value") ||
2709 ParseValue(LHS->getType(), RHS, PFS))
2710 return true;
2711
2712 if (Opc == Instruction::FCmp) {
2713 if (!LHS->getType()->isFPOrFPVector())
2714 return Error(Loc, "fcmp requires floating point operands");
2715 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2716 } else if (Opc == Instruction::ICmp) {
2717 if (!LHS->getType()->isIntOrIntVector() &&
2718 !isa<PointerType>(LHS->getType()))
2719 return Error(Loc, "icmp requires integer operands");
2720 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2721 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002722 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2723 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2725 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002726 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2727 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2729 }
2730 return false;
2731}
2732
2733//===----------------------------------------------------------------------===//
2734// Other Instructions.
2735//===----------------------------------------------------------------------===//
2736
2737
2738/// ParseCast
2739/// ::= CastOpc TypeAndValue 'to' Type
2740bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2741 unsigned Opc) {
2742 LocTy Loc; Value *Op;
2743 PATypeHolder DestTy(Type::VoidTy);
2744 if (ParseTypeAndValue(Op, Loc, PFS) ||
2745 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2746 ParseType(DestTy))
2747 return true;
2748
2749 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2750 return Error(Loc, "invalid cast opcode for cast from '" +
2751 Op->getType()->getDescription() + "' to '" +
2752 DestTy->getDescription() + "'");
2753 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2754 return false;
2755}
2756
2757/// ParseSelect
2758/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2759bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2760 LocTy Loc;
2761 Value *Op0, *Op1, *Op2;
2762 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2763 ParseToken(lltok::comma, "expected ',' after select condition") ||
2764 ParseTypeAndValue(Op1, PFS) ||
2765 ParseToken(lltok::comma, "expected ',' after select value") ||
2766 ParseTypeAndValue(Op2, PFS))
2767 return true;
2768
2769 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2770 return Error(Loc, Reason);
2771
2772 Inst = SelectInst::Create(Op0, Op1, Op2);
2773 return false;
2774}
2775
Chris Lattner0088a5c2009-01-05 08:18:44 +00002776/// ParseVA_Arg
2777/// ::= 'va_arg' TypeAndValue ',' Type
2778bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002779 Value *Op;
2780 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002781 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 if (ParseTypeAndValue(Op, PFS) ||
2783 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002784 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002785 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002786
2787 if (!EltTy->isFirstClassType())
2788 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002789
2790 Inst = new VAArgInst(Op, EltTy);
2791 return false;
2792}
2793
2794/// ParseExtractElement
2795/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2796bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2797 LocTy Loc;
2798 Value *Op0, *Op1;
2799 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2800 ParseToken(lltok::comma, "expected ',' after extract value") ||
2801 ParseTypeAndValue(Op1, PFS))
2802 return true;
2803
2804 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2805 return Error(Loc, "invalid extractelement operands");
2806
2807 Inst = new ExtractElementInst(Op0, Op1);
2808 return false;
2809}
2810
2811/// ParseInsertElement
2812/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2813bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2814 LocTy Loc;
2815 Value *Op0, *Op1, *Op2;
2816 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2817 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2818 ParseTypeAndValue(Op1, PFS) ||
2819 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2820 ParseTypeAndValue(Op2, PFS))
2821 return true;
2822
2823 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2824 return Error(Loc, "invalid extractelement operands");
2825
2826 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2827 return false;
2828}
2829
2830/// ParseShuffleVector
2831/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2832bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2833 LocTy Loc;
2834 Value *Op0, *Op1, *Op2;
2835 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2836 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2837 ParseTypeAndValue(Op1, PFS) ||
2838 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2839 ParseTypeAndValue(Op2, PFS))
2840 return true;
2841
2842 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2843 return Error(Loc, "invalid extractelement operands");
2844
2845 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2846 return false;
2847}
2848
2849/// ParsePHI
2850/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2851bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2852 PATypeHolder Ty(Type::VoidTy);
2853 Value *Op0, *Op1;
2854 LocTy TypeLoc = Lex.getLoc();
2855
2856 if (ParseType(Ty) ||
2857 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2858 ParseValue(Ty, Op0, PFS) ||
2859 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2860 ParseValue(Type::LabelTy, Op1, PFS) ||
2861 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2862 return true;
2863
2864 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2865 while (1) {
2866 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2867
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002868 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 break;
2870
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002871 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002872 ParseValue(Ty, Op0, PFS) ||
2873 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2874 ParseValue(Type::LabelTy, Op1, PFS) ||
2875 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2876 return true;
2877 }
2878
2879 if (!Ty->isFirstClassType())
2880 return Error(TypeLoc, "phi node must have first class type");
2881
2882 PHINode *PN = PHINode::Create(Ty);
2883 PN->reserveOperandSpace(PHIVals.size());
2884 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2885 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2886 Inst = PN;
2887 return false;
2888}
2889
2890/// ParseCall
2891/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2892/// ParameterList OptionalAttrs
2893bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2894 bool isTail) {
2895 unsigned CC, RetAttrs, FnAttrs;
2896 PATypeHolder RetType(Type::VoidTy);
2897 LocTy RetTypeLoc;
2898 ValID CalleeID;
2899 SmallVector<ParamInfo, 16> ArgList;
2900 LocTy CallLoc = Lex.getLoc();
2901
2902 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2903 ParseOptionalCallingConv(CC) ||
2904 ParseOptionalAttrs(RetAttrs, 1) ||
2905 ParseType(RetType, RetTypeLoc) ||
2906 ParseValID(CalleeID) ||
2907 ParseParameterList(ArgList, PFS) ||
2908 ParseOptionalAttrs(FnAttrs, 2))
2909 return true;
2910
2911 // If RetType is a non-function pointer type, then this is the short syntax
2912 // for the call, which means that RetType is just the return type. Infer the
2913 // rest of the function argument types from the arguments that are present.
2914 const PointerType *PFTy = 0;
2915 const FunctionType *Ty = 0;
2916 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2917 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2918 // Pull out the types of all of the arguments...
2919 std::vector<const Type*> ParamTypes;
2920 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2921 ParamTypes.push_back(ArgList[i].V->getType());
2922
2923 if (!FunctionType::isValidReturnType(RetType))
2924 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2925
2926 Ty = FunctionType::get(RetType, ParamTypes, false);
2927 PFTy = PointerType::getUnqual(Ty);
2928 }
2929
2930 // Look up the callee.
2931 Value *Callee;
2932 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2933
2934 // Check for call to invalid intrinsic to avoid crashing later.
2935 if (Function *F = dyn_cast<Function>(Callee)) {
2936 if (F->hasName() && F->getNameLen() >= 5 &&
2937 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2938 !F->getIntrinsicID(true))
2939 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2940 F->getNameStr() + "'");
2941 }
2942
2943 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2944 // function attributes.
2945 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2946 if (FnAttrs & ObsoleteFuncAttrs) {
2947 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2948 FnAttrs &= ~ObsoleteFuncAttrs;
2949 }
2950
2951 // Set up the Attributes for the function.
2952 SmallVector<AttributeWithIndex, 8> Attrs;
2953 if (RetAttrs != Attribute::None)
2954 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2955
2956 SmallVector<Value*, 8> Args;
2957
2958 // Loop through FunctionType's arguments and ensure they are specified
2959 // correctly. Also, gather any parameter attributes.
2960 FunctionType::param_iterator I = Ty->param_begin();
2961 FunctionType::param_iterator E = Ty->param_end();
2962 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2963 const Type *ExpectedTy = 0;
2964 if (I != E) {
2965 ExpectedTy = *I++;
2966 } else if (!Ty->isVarArg()) {
2967 return Error(ArgList[i].Loc, "too many arguments specified");
2968 }
2969
2970 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2971 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2972 ExpectedTy->getDescription() + "'");
2973 Args.push_back(ArgList[i].V);
2974 if (ArgList[i].Attrs != Attribute::None)
2975 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2976 }
2977
2978 if (I != E)
2979 return Error(CallLoc, "not enough parameters specified for call");
2980
2981 if (FnAttrs != Attribute::None)
2982 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2983
2984 // Finish off the Attributes and check them
2985 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2986
2987 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2988 CI->setTailCall(isTail);
2989 CI->setCallingConv(CC);
2990 CI->setAttributes(PAL);
2991 Inst = CI;
2992 return false;
2993}
2994
2995//===----------------------------------------------------------------------===//
2996// Memory Instructions.
2997//===----------------------------------------------------------------------===//
2998
2999/// ParseAlloc
3000/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3001/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3002bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3003 unsigned Opc) {
3004 PATypeHolder Ty(Type::VoidTy);
3005 Value *Size = 0;
3006 LocTy SizeLoc = 0;
3007 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003008 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003009
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003010 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003011 if (Lex.getKind() == lltok::kw_align) {
3012 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003013 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3014 ParseOptionalCommaAlignment(Alignment)) {
3015 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 }
3017 }
3018
3019 if (Size && Size->getType() != Type::Int32Ty)
3020 return Error(SizeLoc, "element count must be i32");
3021
3022 if (Opc == Instruction::Malloc)
3023 Inst = new MallocInst(Ty, Size, Alignment);
3024 else
3025 Inst = new AllocaInst(Ty, Size, Alignment);
3026 return false;
3027}
3028
3029/// ParseFree
3030/// ::= 'free' TypeAndValue
3031bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3032 Value *Val; LocTy Loc;
3033 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3034 if (!isa<PointerType>(Val->getType()))
3035 return Error(Loc, "operand to free must be a pointer");
3036 Inst = new FreeInst(Val);
3037 return false;
3038}
3039
3040/// ParseLoad
3041/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3042bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3043 bool isVolatile) {
3044 Value *Val; LocTy Loc;
3045 unsigned Alignment;
3046 if (ParseTypeAndValue(Val, Loc, PFS) ||
3047 ParseOptionalCommaAlignment(Alignment))
3048 return true;
3049
3050 if (!isa<PointerType>(Val->getType()) ||
3051 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3052 return Error(Loc, "load operand must be a pointer to a first class type");
3053
3054 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3055 return false;
3056}
3057
3058/// ParseStore
3059/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3060bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3061 bool isVolatile) {
3062 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3063 unsigned Alignment;
3064 if (ParseTypeAndValue(Val, Loc, PFS) ||
3065 ParseToken(lltok::comma, "expected ',' after store operand") ||
3066 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3067 ParseOptionalCommaAlignment(Alignment))
3068 return true;
3069
3070 if (!isa<PointerType>(Ptr->getType()))
3071 return Error(PtrLoc, "store operand must be a pointer");
3072 if (!Val->getType()->isFirstClassType())
3073 return Error(Loc, "store operand must be a first class value");
3074 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3075 return Error(Loc, "stored value and pointer type do not match");
3076
3077 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3078 return false;
3079}
3080
3081/// ParseGetResult
3082/// ::= 'getresult' TypeAndValue ',' uint
3083/// FIXME: Remove support for getresult in LLVM 3.0
3084bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3085 Value *Val; LocTy ValLoc, EltLoc;
3086 unsigned Element;
3087 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3088 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003089 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 return true;
3091
3092 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3093 return Error(ValLoc, "getresult inst requires an aggregate operand");
3094 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3095 return Error(EltLoc, "invalid getresult index for value");
3096 Inst = ExtractValueInst::Create(Val, Element);
3097 return false;
3098}
3099
3100/// ParseGetElementPtr
3101/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3102bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3103 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003104 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003105
3106 if (!isa<PointerType>(Ptr->getType()))
3107 return Error(Loc, "base of getelementptr must be a pointer");
3108
3109 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003110 while (EatIfPresent(lltok::comma)) {
3111 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 if (!isa<IntegerType>(Val->getType()))
3113 return Error(EltLoc, "getelementptr index must be an integer");
3114 Indices.push_back(Val);
3115 }
3116
3117 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3118 Indices.begin(), Indices.end()))
3119 return Error(Loc, "invalid getelementptr indices");
3120 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3121 return false;
3122}
3123
3124/// ParseExtractValue
3125/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3126bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3127 Value *Val; LocTy Loc;
3128 SmallVector<unsigned, 4> Indices;
3129 if (ParseTypeAndValue(Val, Loc, PFS) ||
3130 ParseIndexList(Indices))
3131 return true;
3132
3133 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3134 return Error(Loc, "extractvalue operand must be array or struct");
3135
3136 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3137 Indices.end()))
3138 return Error(Loc, "invalid indices for extractvalue");
3139 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3140 return false;
3141}
3142
3143/// ParseInsertValue
3144/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3145bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3146 Value *Val0, *Val1; LocTy Loc0, Loc1;
3147 SmallVector<unsigned, 4> Indices;
3148 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3149 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3150 ParseTypeAndValue(Val1, Loc1, PFS) ||
3151 ParseIndexList(Indices))
3152 return true;
3153
3154 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3155 return Error(Loc0, "extractvalue operand must be array or struct");
3156
3157 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3158 Indices.end()))
3159 return Error(Loc0, "invalid indices for insertvalue");
3160 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3161 return false;
3162}