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