blob: b4577ad726d7e2b0107ab9b66b61dfd51b16bcb6 [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"
Nick Lewyckycb337992009-05-10 20:57:05 +000021#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000022#include "llvm/Module.h"
23#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattnerdf986172009-01-02 07:01:27 +000029namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030 /// ValID - Represents a reference of a definition of some sort with no type.
31 /// There are several cases where we have to parse the value but where the
32 /// type can depend on later context. This may either be a numeric reference
33 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000034 struct ValID {
35 enum {
36 t_LocalID, t_GlobalID, // ID in UIntVal.
37 t_LocalName, t_GlobalName, // Name in StrVal.
38 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
39 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000040 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000041 t_Constant, // Value in ConstantVal.
42 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
43 } Kind;
44
45 LLParser::LocTy Loc;
46 unsigned UIntVal;
47 std::string StrVal, StrVal2;
48 APSInt APSIntVal;
49 APFloat APFloatVal;
50 Constant *ConstantVal;
51 ValID() : APFloatVal(0.0) {}
52 };
53}
54
Chris Lattner3ed88ef2009-01-02 08:05:26 +000055/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000056bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000057 // Prime the lexer.
58 Lex.Lex();
59
Chris Lattnerad7d1e22009-01-04 20:44:11 +000060 return ParseTopLevelEntities() ||
61 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000062}
63
64/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65/// module.
66bool LLParser::ValidateEndOfModule() {
67 if (!ForwardRefTypes.empty())
68 return Error(ForwardRefTypes.begin()->second.second,
69 "use of undefined type named '" +
70 ForwardRefTypes.begin()->first + "'");
71 if (!ForwardRefTypeIDs.empty())
72 return Error(ForwardRefTypeIDs.begin()->second.second,
73 "use of undefined type '%" +
74 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75
76 if (!ForwardRefVals.empty())
77 return Error(ForwardRefVals.begin()->second.second,
78 "use of undefined value '@" + ForwardRefVals.begin()->first +
79 "'");
80
81 if (!ForwardRefValIDs.empty())
82 return Error(ForwardRefValIDs.begin()->second.second,
83 "use of undefined value '@" +
84 utostr(ForwardRefValIDs.begin()->first) + "'");
85
86 // Look for intrinsic functions and CallInst that need to be upgraded
87 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
88 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
89
90 return false;
91}
92
93//===----------------------------------------------------------------------===//
94// Top-Level Entities
95//===----------------------------------------------------------------------===//
96
97bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000098 while (1) {
99 switch (Lex.getKind()) {
100 default: return TokError("expected top-level entity");
101 case lltok::Eof: return false;
102 //case lltok::kw_define:
103 case lltok::kw_declare: if (ParseDeclare()) return true; break;
104 case lltok::kw_define: if (ParseDefine()) return true; break;
105 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
106 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
107 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
108 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
109 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
110 case lltok::LocalVar: if (ParseNamedType()) return true; break;
111 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112
113 // The Global variable production with no name can have many different
114 // optional leading prefixes, the production is:
115 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
116 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000117 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 case lltok::kw_internal: // OptionalLinkage
119 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000120 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000121 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000122 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::kw_appending: // OptionalLinkage
124 case lltok::kw_dllexport: // OptionalLinkage
125 case lltok::kw_common: // OptionalLinkage
126 case lltok::kw_dllimport: // OptionalLinkage
127 case lltok::kw_extern_weak: // OptionalLinkage
128 case lltok::kw_external: { // OptionalLinkage
129 unsigned Linkage, Visibility;
130 if (ParseOptionalLinkage(Linkage) ||
131 ParseOptionalVisibility(Visibility) ||
132 ParseGlobal("", 0, Linkage, true, Visibility))
133 return true;
134 break;
135 }
136 case lltok::kw_default: // OptionalVisibility
137 case lltok::kw_hidden: // OptionalVisibility
138 case lltok::kw_protected: { // OptionalVisibility
139 unsigned Visibility;
140 if (ParseOptionalVisibility(Visibility) ||
141 ParseGlobal("", 0, 0, false, Visibility))
142 return true;
143 break;
144 }
145
146 case lltok::kw_thread_local: // OptionalThreadLocal
147 case lltok::kw_addrspace: // OptionalAddrSpace
148 case lltok::kw_constant: // GlobalType
149 case lltok::kw_global: // GlobalType
150 if (ParseGlobal("", 0, 0, false, 0)) return true;
151 break;
152 }
153 }
154}
155
156
157/// toplevelentity
158/// ::= 'module' 'asm' STRINGCONSTANT
159bool LLParser::ParseModuleAsm() {
160 assert(Lex.getKind() == lltok::kw_module);
161 Lex.Lex();
162
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000163 std::string AsmStr;
164 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
165 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000166
167 const std::string &AsmSoFar = M->getModuleInlineAsm();
168 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000169 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 return false;
173}
174
175/// toplevelentity
176/// ::= 'target' 'triple' '=' STRINGCONSTANT
177/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
178bool LLParser::ParseTargetDefinition() {
179 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000180 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 switch (Lex.Lex()) {
182 default: return TokError("unknown target property");
183 case lltok::kw_triple:
184 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
186 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000187 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000188 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 return false;
190 case lltok::kw_datalayout:
191 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000192 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
193 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000194 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000195 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return false;
197 }
198}
199
200/// toplevelentity
201/// ::= 'deplibs' '=' '[' ']'
202/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
203bool LLParser::ParseDepLibs() {
204 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
207 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
208 return true;
209
210 if (EatIfPresent(lltok::rsquare))
211 return false;
212
213 std::string Str;
214 if (ParseStringConstant(Str)) return true;
215 M->addLibrary(Str);
216
217 while (EatIfPresent(lltok::comma)) {
218 if (ParseStringConstant(Str)) return true;
219 M->addLibrary(Str);
220 }
221
222 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000223}
224
225/// toplevelentity
226/// ::= 'type' type
227bool LLParser::ParseUnnamedType() {
228 assert(Lex.getKind() == lltok::kw_type);
229 LocTy TypeLoc = Lex.getLoc();
230 Lex.Lex(); // eat kw_type
231
232 PATypeHolder Ty(Type::VoidTy);
233 if (ParseType(Ty)) return true;
234
235 unsigned TypeID = NumberedTypes.size();
236
Chris Lattnerdf986172009-01-02 07:01:27 +0000237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000241 if (FI->second.first.get() == Ty)
242 return Error(TypeLoc, "self referential type is invalid");
243
Chris Lattnerdf986172009-01-02 07:01:27 +0000244 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
245 Ty = FI->second.first.get();
246 ForwardRefTypeIDs.erase(FI);
247 }
248
249 NumberedTypes.push_back(Ty);
250
251 return false;
252}
253
254/// toplevelentity
255/// ::= LocalVar '=' 'type' type
256bool LLParser::ParseNamedType() {
257 std::string Name = Lex.getStrVal();
258 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000259 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000260
261 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000262
263 if (ParseToken(lltok::equal, "expected '=' after name") ||
264 ParseToken(lltok::kw_type, "expected 'type' after name") ||
265 ParseType(Ty))
266 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000267
Chris Lattnerdf986172009-01-02 07:01:27 +0000268 // Set the type name, checking for conflicts as we do so.
269 bool AlreadyExists = M->addTypeName(Name, Ty);
270 if (!AlreadyExists) return false;
271
272 // See if this type is a forward reference. We need to eagerly resolve
273 // types to allow recursive type redefinitions below.
274 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
275 FI = ForwardRefTypes.find(Name);
276 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000277 if (FI->second.first.get() == Ty)
278 return Error(NameLoc, "self referential type is invalid");
279
Chris Lattnerdf986172009-01-02 07:01:27 +0000280 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
281 Ty = FI->second.first.get();
282 ForwardRefTypes.erase(FI);
283 }
284
285 // Inserting a name that is already defined, get the existing name.
286 const Type *Existing = M->getTypeByName(Name);
287 assert(Existing && "Conflict but no matching type?!");
288
289 // Otherwise, this is an attempt to redefine a type. That's okay if
290 // the redefinition is identical to the original.
291 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
292 if (Existing == Ty) return false;
293
294 // Any other kind of (non-equivalent) redefinition is an error.
295 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
296 Ty->getDescription() + "'");
297}
298
299
300/// toplevelentity
301/// ::= 'declare' FunctionHeader
302bool LLParser::ParseDeclare() {
303 assert(Lex.getKind() == lltok::kw_declare);
304 Lex.Lex();
305
306 Function *F;
307 return ParseFunctionHeader(F, false);
308}
309
310/// toplevelentity
311/// ::= 'define' FunctionHeader '{' ...
312bool LLParser::ParseDefine() {
313 assert(Lex.getKind() == lltok::kw_define);
314 Lex.Lex();
315
316 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000317 return ParseFunctionHeader(F, true) ||
318 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000319}
320
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000321/// ParseGlobalType
322/// ::= 'constant'
323/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000324bool LLParser::ParseGlobalType(bool &IsConstant) {
325 if (Lex.getKind() == lltok::kw_constant)
326 IsConstant = true;
327 else if (Lex.getKind() == lltok::kw_global)
328 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000329 else {
330 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000332 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 Lex.Lex();
334 return false;
335}
336
337/// ParseNamedGlobal:
338/// GlobalVar '=' OptionalVisibility ALIAS ...
339/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
340bool LLParser::ParseNamedGlobal() {
341 assert(Lex.getKind() == lltok::GlobalVar);
342 LocTy NameLoc = Lex.getLoc();
343 std::string Name = Lex.getStrVal();
344 Lex.Lex();
345
346 bool HasLinkage;
347 unsigned Linkage, Visibility;
348 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
349 ParseOptionalLinkage(Linkage, HasLinkage) ||
350 ParseOptionalVisibility(Visibility))
351 return true;
352
353 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
354 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
355 return ParseAlias(Name, NameLoc, Visibility);
356}
357
358/// ParseAlias:
359/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000361/// ::= TypeAndValue
362/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
363/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000364///
365/// Everything through visibility has already been parsed.
366///
367bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
370 Lex.Lex();
371 unsigned Linkage;
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
374 return true;
375
376 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000377 Linkage != GlobalValue::WeakAnyLinkage &&
378 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000379 Linkage != GlobalValue::InternalLinkage &&
380 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 return Error(LinkageLoc, "invalid linkage type for alias");
382
383 Constant *Aliasee;
384 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000385 if (Lex.getKind() != lltok::kw_bitcast &&
386 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000387 if (ParseGlobalTypeAndValue(Aliasee)) return true;
388 } else {
389 // The bitcast dest type is not present, it is implied by the dest type.
390 ValID ID;
391 if (ParseValID(ID)) return true;
392 if (ID.Kind != ValID::t_Constant)
393 return Error(AliaseeLoc, "invalid aliasee");
394 Aliasee = ID.ConstantVal;
395 }
396
397 if (!isa<PointerType>(Aliasee->getType()))
398 return Error(AliaseeLoc, "alias must have pointer type");
399
400 // Okay, create the alias but do not insert it into the module yet.
401 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
402 (GlobalValue::LinkageTypes)Linkage, Name,
403 Aliasee);
404 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
405
406 // See if this value already exists in the symbol table. If so, it is either
407 // a redefinition or a definition of a forward reference.
408 if (GlobalValue *Val =
409 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
410 // See if this was a redefinition. If so, there is no entry in
411 // ForwardRefVals.
412 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
413 I = ForwardRefVals.find(Name);
414 if (I == ForwardRefVals.end())
415 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
416
417 // Otherwise, this was a definition of forward ref. Verify that types
418 // agree.
419 if (Val->getType() != GA->getType())
420 return Error(NameLoc,
421 "forward reference and definition of alias have different types");
422
423 // If they agree, just RAUW the old value with the alias and remove the
424 // forward ref info.
425 Val->replaceAllUsesWith(GA);
426 Val->eraseFromParent();
427 ForwardRefVals.erase(I);
428 }
429
430 // Insert into the module, we know its name won't collide now.
431 M->getAliasList().push_back(GA);
432 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
433
434 return false;
435}
436
437/// ParseGlobal
438/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
439/// OptionalAddrSpace GlobalType Type Const
440/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
441/// OptionalAddrSpace GlobalType Type Const
442///
443/// Everything through visibility has been parsed already.
444///
445bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
446 unsigned Linkage, bool HasLinkage,
447 unsigned Visibility) {
448 unsigned AddrSpace;
449 bool ThreadLocal, IsConstant;
450 LocTy TyLoc;
451
452 PATypeHolder Ty(Type::VoidTy);
453 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
454 ParseOptionalAddrSpace(AddrSpace) ||
455 ParseGlobalType(IsConstant) ||
456 ParseType(Ty, TyLoc))
457 return true;
458
459 // If the linkage is specified and is external, then no initializer is
460 // present.
461 Constant *Init = 0;
462 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000463 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000464 Linkage != GlobalValue::ExternalLinkage)) {
465 if (ParseGlobalValue(Ty, Init))
466 return true;
467 }
468
Chris Lattnera9a9e072009-03-09 04:49:14 +0000469 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000470 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000471
472 GlobalVariable *GV = 0;
473
474 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000475 if (!Name.empty()) {
476 if ((GV = M->getGlobalVariable(Name, true)) &&
477 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000478 return Error(NameLoc, "redefinition of global '@" + Name + "'");
479 } else {
480 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
481 I = ForwardRefValIDs.find(NumberedVals.size());
482 if (I != ForwardRefValIDs.end()) {
483 GV = cast<GlobalVariable>(I->second.first);
484 ForwardRefValIDs.erase(I);
485 }
486 }
487
488 if (GV == 0) {
489 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
490 M, false, AddrSpace);
491 } else {
492 if (GV->getType()->getElementType() != Ty)
493 return Error(TyLoc,
494 "forward reference and definition of global have different types");
495
496 // Move the forward-reference to the correct spot in the module.
497 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
498 }
499
500 if (Name.empty())
501 NumberedVals.push_back(GV);
502
503 // Set the parsed properties on the global.
504 if (Init)
505 GV->setInitializer(Init);
506 GV->setConstant(IsConstant);
507 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
508 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
509 GV->setThreadLocal(ThreadLocal);
510
511 // Parse attributes on the global.
512 while (Lex.getKind() == lltok::comma) {
513 Lex.Lex();
514
515 if (Lex.getKind() == lltok::kw_section) {
516 Lex.Lex();
517 GV->setSection(Lex.getStrVal());
518 if (ParseToken(lltok::StringConstant, "expected global section string"))
519 return true;
520 } else if (Lex.getKind() == lltok::kw_align) {
521 unsigned Alignment;
522 if (ParseOptionalAlignment(Alignment)) return true;
523 GV->setAlignment(Alignment);
524 } else {
525 TokError("unknown global variable property!");
526 }
527 }
528
529 return false;
530}
531
532
533//===----------------------------------------------------------------------===//
534// GlobalValue Reference/Resolution Routines.
535//===----------------------------------------------------------------------===//
536
537/// GetGlobalVal - Get a value with the specified name or ID, creating a
538/// forward reference record if needed. This can return null if the value
539/// exists but does not have the right type.
540GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
541 LocTy Loc) {
542 const PointerType *PTy = dyn_cast<PointerType>(Ty);
543 if (PTy == 0) {
544 Error(Loc, "global variable reference must have pointer type");
545 return 0;
546 }
547
548 // Look this name up in the normal function symbol table.
549 GlobalValue *Val =
550 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
551
552 // If this is a forward reference for the value, see if we already created a
553 // forward ref record.
554 if (Val == 0) {
555 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
556 I = ForwardRefVals.find(Name);
557 if (I != ForwardRefVals.end())
558 Val = I->second.first;
559 }
560
561 // If we have the value in the symbol table or fwd-ref table, return it.
562 if (Val) {
563 if (Val->getType() == Ty) return Val;
564 Error(Loc, "'@" + Name + "' defined with type '" +
565 Val->getType()->getDescription() + "'");
566 return 0;
567 }
568
569 // Otherwise, create a new forward reference for this value and remember it.
570 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000571 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
572 // Function types can return opaque but functions can't.
573 if (isa<OpaqueType>(FT->getReturnType())) {
574 Error(Loc, "function may not return opaque type");
575 return 0;
576 }
577
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000578 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000579 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000580 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000581 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000582 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000583
584 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
585 return FwdVal;
586}
587
588GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
589 const PointerType *PTy = dyn_cast<PointerType>(Ty);
590 if (PTy == 0) {
591 Error(Loc, "global variable reference must have pointer type");
592 return 0;
593 }
594
595 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
596
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
599 if (Val == 0) {
600 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
601 I = ForwardRefValIDs.find(ID);
602 if (I != ForwardRefValIDs.end())
603 Val = I->second.first;
604 }
605
606 // If we have the value in the symbol table or fwd-ref table, return it.
607 if (Val) {
608 if (Val->getType() == Ty) return Val;
609 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
610 Val->getType()->getDescription() + "'");
611 return 0;
612 }
613
614 // Otherwise, create a new forward reference for this value and remember it.
615 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000616 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000619 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000620 return 0;
621 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000622 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000623 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000624 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000625 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000626 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000627
628 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629 return FwdVal;
630}
631
632
633//===----------------------------------------------------------------------===//
634// Helper Routines.
635//===----------------------------------------------------------------------===//
636
637/// ParseToken - If the current token has the specified kind, eat it and return
638/// success. Otherwise, emit the specified error and return failure.
639bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
640 if (Lex.getKind() != T)
641 return TokError(ErrMsg);
642 Lex.Lex();
643 return false;
644}
645
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000646/// ParseStringConstant
647/// ::= StringConstant
648bool LLParser::ParseStringConstant(std::string &Result) {
649 if (Lex.getKind() != lltok::StringConstant)
650 return TokError("expected string constant");
651 Result = Lex.getStrVal();
652 Lex.Lex();
653 return false;
654}
655
656/// ParseUInt32
657/// ::= uint32
658bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
660 return TokError("expected integer");
661 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
662 if (Val64 != unsigned(Val64))
663 return TokError("expected 32-bit integer (too large)");
664 Val = Val64;
665 Lex.Lex();
666 return false;
667}
668
669
670/// ParseOptionalAddrSpace
671/// := /*empty*/
672/// := 'addrspace' '(' uint32 ')'
673bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
674 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000675 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000678 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000679 ParseToken(lltok::rparen, "expected ')' in address space");
680}
681
682/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
683/// indicates what kind of attribute list this is: 0: function arg, 1: result,
684/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000685/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000686bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687 Attrs = Attribute::None;
688 LocTy AttrLoc = Lex.getLoc();
689
690 while (1) {
691 switch (Lex.getKind()) {
692 case lltok::kw_sext:
693 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000694 // Treat these as signext/zeroext if they occur in the argument list after
695 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
696 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
697 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000699 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 if (Lex.getKind() == lltok::kw_sext)
701 Attrs |= Attribute::SExt;
702 else
703 Attrs |= Attribute::ZExt;
704 break;
705 }
706 // FALL THROUGH.
707 default: // End of attributes.
708 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
709 return Error(AttrLoc, "invalid use of function-only attribute");
710
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000711 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000712 return Error(AttrLoc, "invalid use of parameter-only attribute");
713
714 return false;
715 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
716 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
717 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
718 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
719 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
720 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
721 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
722 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
723
724 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
725 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
726 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
727 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
728 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
729 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
730 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
731 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
732 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
Devang Pateld18e31a2009-06-04 22:05:33 +0000733 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000734
735 case lltok::kw_align: {
736 unsigned Alignment;
737 if (ParseOptionalAlignment(Alignment))
738 return true;
739 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
740 continue;
741 }
742 }
743 Lex.Lex();
744 }
745}
746
747/// ParseOptionalLinkage
748/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000749/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000750/// ::= 'internal'
751/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000752/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000753/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000754/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000755/// ::= 'appending'
756/// ::= 'dllexport'
757/// ::= 'common'
758/// ::= 'dllimport'
759/// ::= 'extern_weak'
760/// ::= 'external'
761bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
762 HasLinkage = false;
763 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000764 default: Res = GlobalValue::ExternalLinkage; return false;
765 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
766 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
767 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
768 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
769 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
770 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000771 case lltok::kw_available_externally:
772 Res = GlobalValue::AvailableExternallyLinkage;
773 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000774 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
775 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000776 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000777 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000778 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000779 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000780 }
781 Lex.Lex();
782 HasLinkage = true;
783 return false;
784}
785
786/// ParseOptionalVisibility
787/// ::= /*empty*/
788/// ::= 'default'
789/// ::= 'hidden'
790/// ::= 'protected'
791///
792bool LLParser::ParseOptionalVisibility(unsigned &Res) {
793 switch (Lex.getKind()) {
794 default: Res = GlobalValue::DefaultVisibility; return false;
795 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
796 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
797 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
798 }
799 Lex.Lex();
800 return false;
801}
802
803/// ParseOptionalCallingConv
804/// ::= /*empty*/
805/// ::= 'ccc'
806/// ::= 'fastcc'
807/// ::= 'coldcc'
808/// ::= 'x86_stdcallcc'
809/// ::= 'x86_fastcallcc'
810/// ::= 'cc' UINT
811///
812bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
813 switch (Lex.getKind()) {
814 default: CC = CallingConv::C; return false;
815 case lltok::kw_ccc: CC = CallingConv::C; break;
816 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
817 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
818 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
819 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000820 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000821 }
822 Lex.Lex();
823 return false;
824}
825
826/// ParseOptionalAlignment
827/// ::= /* empty */
828/// ::= 'align' 4
829bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
830 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000831 if (!EatIfPresent(lltok::kw_align))
832 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000833 LocTy AlignLoc = Lex.getLoc();
834 if (ParseUInt32(Alignment)) return true;
835 if (!isPowerOf2_32(Alignment))
836 return Error(AlignLoc, "alignment is not a power of two");
837 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000838}
839
840/// ParseOptionalCommaAlignment
841/// ::= /* empty */
842/// ::= ',' 'align' 4
843bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
844 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000845 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000846 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000847 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000848 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000849}
850
851/// ParseIndexList
852/// ::= (',' uint32)+
853bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
854 if (Lex.getKind() != lltok::comma)
855 return TokError("expected ',' as start of index list");
856
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000857 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000859 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000860 Indices.push_back(Idx);
861 }
862
863 return false;
864}
865
866//===----------------------------------------------------------------------===//
867// Type Parsing.
868//===----------------------------------------------------------------------===//
869
870/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000871bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
872 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000873 if (ParseTypeRec(Result)) return true;
874
875 // Verify no unresolved uprefs.
876 if (!UpRefs.empty())
877 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000878
Chris Lattnera9a9e072009-03-09 04:49:14 +0000879 if (!AllowVoid && Result.get() == Type::VoidTy)
880 return Error(TypeLoc, "void type only allowed for function results");
881
Chris Lattnerdf986172009-01-02 07:01:27 +0000882 return false;
883}
884
885/// HandleUpRefs - Every time we finish a new layer of types, this function is
886/// called. It loops through the UpRefs vector, which is a list of the
887/// currently active types. For each type, if the up-reference is contained in
888/// the newly completed type, we decrement the level count. When the level
889/// count reaches zero, the up-referenced type is the type that is passed in:
890/// thus we can complete the cycle.
891///
892PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
893 // If Ty isn't abstract, or if there are no up-references in it, then there is
894 // nothing to resolve here.
895 if (!ty->isAbstract() || UpRefs.empty()) return ty;
896
897 PATypeHolder Ty(ty);
898#if 0
899 errs() << "Type '" << Ty->getDescription()
900 << "' newly formed. Resolving upreferences.\n"
901 << UpRefs.size() << " upreferences active!\n";
902#endif
903
904 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
905 // to zero), we resolve them all together before we resolve them to Ty. At
906 // the end of the loop, if there is anything to resolve to Ty, it will be in
907 // this variable.
908 OpaqueType *TypeToResolve = 0;
909
910 for (unsigned i = 0; i != UpRefs.size(); ++i) {
911 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
912 bool ContainsType =
913 std::find(Ty->subtype_begin(), Ty->subtype_end(),
914 UpRefs[i].LastContainedTy) != Ty->subtype_end();
915
916#if 0
917 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918 << UpRefs[i].LastContainedTy->getDescription() << ") = "
919 << (ContainsType ? "true" : "false")
920 << " level=" << UpRefs[i].NestingLevel << "\n";
921#endif
922 if (!ContainsType)
923 continue;
924
925 // Decrement level of upreference
926 unsigned Level = --UpRefs[i].NestingLevel;
927 UpRefs[i].LastContainedTy = Ty;
928
929 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
930 if (Level != 0)
931 continue;
932
933#if 0
934 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
935#endif
936 if (!TypeToResolve)
937 TypeToResolve = UpRefs[i].UpRefTy;
938 else
939 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
940 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
941 --i; // Do not skip the next element.
942 }
943
944 if (TypeToResolve)
945 TypeToResolve->refineAbstractTypeTo(Ty);
946
947 return Ty;
948}
949
950
951/// ParseTypeRec - The recursive function used to process the internal
952/// implementation details of types.
953bool LLParser::ParseTypeRec(PATypeHolder &Result) {
954 switch (Lex.getKind()) {
955 default:
956 return TokError("expected type");
957 case lltok::Type:
958 // TypeRec ::= 'float' | 'void' (etc)
959 Result = Lex.getTyVal();
960 Lex.Lex();
961 break;
962 case lltok::kw_opaque:
963 // TypeRec ::= 'opaque'
964 Result = OpaqueType::get();
965 Lex.Lex();
966 break;
967 case lltok::lbrace:
968 // TypeRec ::= '{' ... '}'
969 if (ParseStructType(Result, false))
970 return true;
971 break;
972 case lltok::lsquare:
973 // TypeRec ::= '[' ... ']'
974 Lex.Lex(); // eat the lsquare.
975 if (ParseArrayVectorType(Result, false))
976 return true;
977 break;
978 case lltok::less: // Either vector or packed struct.
979 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000980 Lex.Lex();
981 if (Lex.getKind() == lltok::lbrace) {
982 if (ParseStructType(Result, true) ||
983 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000984 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000985 } else if (ParseArrayVectorType(Result, true))
986 return true;
987 break;
988 case lltok::LocalVar:
989 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
990 // TypeRec ::= %foo
991 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
992 Result = T;
993 } else {
994 Result = OpaqueType::get();
995 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
996 std::make_pair(Result,
997 Lex.getLoc())));
998 M->addTypeName(Lex.getStrVal(), Result.get());
999 }
1000 Lex.Lex();
1001 break;
1002
1003 case lltok::LocalVarID:
1004 // TypeRec ::= %4
1005 if (Lex.getUIntVal() < NumberedTypes.size())
1006 Result = NumberedTypes[Lex.getUIntVal()];
1007 else {
1008 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1009 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1010 if (I != ForwardRefTypeIDs.end())
1011 Result = I->second.first;
1012 else {
1013 Result = OpaqueType::get();
1014 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1015 std::make_pair(Result,
1016 Lex.getLoc())));
1017 }
1018 }
1019 Lex.Lex();
1020 break;
1021 case lltok::backslash: {
1022 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001023 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001024 unsigned Val;
1025 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001026 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1027 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1028 Result = OT;
1029 break;
1030 }
1031 }
1032
1033 // Parse the type suffixes.
1034 while (1) {
1035 switch (Lex.getKind()) {
1036 // End of type.
1037 default: return false;
1038
1039 // TypeRec ::= TypeRec '*'
1040 case lltok::star:
1041 if (Result.get() == Type::LabelTy)
1042 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001043 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001044 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001045 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1046 Lex.Lex();
1047 break;
1048
1049 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1050 case lltok::kw_addrspace: {
1051 if (Result.get() == Type::LabelTy)
1052 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001053 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001054 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001055 unsigned AddrSpace;
1056 if (ParseOptionalAddrSpace(AddrSpace) ||
1057 ParseToken(lltok::star, "expected '*' in address space"))
1058 return true;
1059
1060 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1061 break;
1062 }
1063
1064 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1065 case lltok::lparen:
1066 if (ParseFunctionType(Result))
1067 return true;
1068 break;
1069 }
1070 }
1071}
1072
1073/// ParseParameterList
1074/// ::= '(' ')'
1075/// ::= '(' Arg (',' Arg)* ')'
1076/// Arg
1077/// ::= Type OptionalAttributes Value OptionalAttributes
1078bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1079 PerFunctionState &PFS) {
1080 if (ParseToken(lltok::lparen, "expected '(' in call"))
1081 return true;
1082
1083 while (Lex.getKind() != lltok::rparen) {
1084 // If this isn't the first argument, we need a comma.
1085 if (!ArgList.empty() &&
1086 ParseToken(lltok::comma, "expected ',' in argument list"))
1087 return true;
1088
1089 // Parse the argument.
1090 LocTy ArgLoc;
1091 PATypeHolder ArgTy(Type::VoidTy);
1092 unsigned ArgAttrs1, ArgAttrs2;
1093 Value *V;
1094 if (ParseType(ArgTy, ArgLoc) ||
1095 ParseOptionalAttrs(ArgAttrs1, 0) ||
1096 ParseValue(ArgTy, V, PFS) ||
1097 // FIXME: Should not allow attributes after the argument, remove this in
1098 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001099 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001100 return true;
1101 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1102 }
1103
1104 Lex.Lex(); // Lex the ')'.
1105 return false;
1106}
1107
1108
1109
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001110/// ParseArgumentList - Parse the argument list for a function type or function
1111/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001112/// ::= '(' ArgTypeListI ')'
1113/// ArgTypeListI
1114/// ::= /*empty*/
1115/// ::= '...'
1116/// ::= ArgTypeList ',' '...'
1117/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001118///
Chris Lattnerdf986172009-01-02 07:01:27 +00001119bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001120 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001121 isVarArg = false;
1122 assert(Lex.getKind() == lltok::lparen);
1123 Lex.Lex(); // eat the (.
1124
1125 if (Lex.getKind() == lltok::rparen) {
1126 // empty
1127 } else if (Lex.getKind() == lltok::dotdotdot) {
1128 isVarArg = true;
1129 Lex.Lex();
1130 } else {
1131 LocTy TypeLoc = Lex.getLoc();
1132 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001133 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001135
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001136 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1137 // types (such as a function returning a pointer to itself). If parsing a
1138 // function prototype, we require fully resolved types.
1139 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001140 ParseOptionalAttrs(Attrs, 0)) return true;
1141
Chris Lattnera9a9e072009-03-09 04:49:14 +00001142 if (ArgTy == Type::VoidTy)
1143 return Error(TypeLoc, "argument can not have void type");
1144
Chris Lattnerdf986172009-01-02 07:01:27 +00001145 if (Lex.getKind() == lltok::LocalVar ||
1146 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1147 Name = Lex.getStrVal();
1148 Lex.Lex();
1149 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001150
1151 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1152 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001153
1154 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1155
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001156 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001157 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001158 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001159 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001160 break;
1161 }
1162
1163 // Otherwise must be an argument type.
1164 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001165 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001166 ParseOptionalAttrs(Attrs, 0)) return true;
1167
Chris Lattnera9a9e072009-03-09 04:49:14 +00001168 if (ArgTy == Type::VoidTy)
1169 return Error(TypeLoc, "argument can not have void type");
1170
Chris Lattnerdf986172009-01-02 07:01:27 +00001171 if (Lex.getKind() == lltok::LocalVar ||
1172 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1173 Name = Lex.getStrVal();
1174 Lex.Lex();
1175 } else {
1176 Name = "";
1177 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001178
1179 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1180 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001181
1182 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1183 }
1184 }
1185
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001186 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001187}
1188
1189/// ParseFunctionType
1190/// ::= Type ArgumentList OptionalAttrs
1191bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1192 assert(Lex.getKind() == lltok::lparen);
1193
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001194 if (!FunctionType::isValidReturnType(Result))
1195 return TokError("invalid function return type");
1196
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 std::vector<ArgInfo> ArgList;
1198 bool isVarArg;
1199 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001200 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001201 // FIXME: Allow, but ignore attributes on function types!
1202 // FIXME: Remove in LLVM 3.0
1203 ParseOptionalAttrs(Attrs, 2))
1204 return true;
1205
1206 // Reject names on the arguments lists.
1207 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1208 if (!ArgList[i].Name.empty())
1209 return Error(ArgList[i].Loc, "argument name invalid in function type");
1210 if (!ArgList[i].Attrs != 0) {
1211 // Allow but ignore attributes on function types; this permits
1212 // auto-upgrade.
1213 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1214 }
1215 }
1216
1217 std::vector<const Type*> ArgListTy;
1218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1219 ArgListTy.push_back(ArgList[i].Type);
1220
1221 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1222 return false;
1223}
1224
1225/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1226/// TypeRec
1227/// ::= '{' '}'
1228/// ::= '{' TypeRec (',' TypeRec)* '}'
1229/// ::= '<' '{' '}' '>'
1230/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1231bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1232 assert(Lex.getKind() == lltok::lbrace);
1233 Lex.Lex(); // Consume the '{'
1234
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001235 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001236 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 return false;
1238 }
1239
1240 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001241 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 if (ParseTypeRec(Result)) return true;
1243 ParamsList.push_back(Result);
1244
Chris Lattnera9a9e072009-03-09 04:49:14 +00001245 if (Result == Type::VoidTy)
1246 return Error(EltTyLoc, "struct element can not have void type");
1247
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001248 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001249 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001251
1252 if (Result == Type::VoidTy)
1253 return Error(EltTyLoc, "struct element can not have void type");
1254
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 ParamsList.push_back(Result);
1256 }
1257
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001258 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1259 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001260
1261 std::vector<const Type*> ParamsListTy;
1262 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1263 ParamsListTy.push_back(ParamsList[i].get());
1264 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1265 return false;
1266}
1267
1268/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1269/// token has already been consumed.
1270/// TypeRec
1271/// ::= '[' APSINTVAL 'x' Types ']'
1272/// ::= '<' APSINTVAL 'x' Types '>'
1273bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1275 Lex.getAPSIntVal().getBitWidth() > 64)
1276 return TokError("expected number in address space");
1277
1278 LocTy SizeLoc = Lex.getLoc();
1279 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001280 Lex.Lex();
1281
1282 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1283 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001284
1285 LocTy TypeLoc = Lex.getLoc();
1286 PATypeHolder EltTy(Type::VoidTy);
1287 if (ParseTypeRec(EltTy)) return true;
1288
Chris Lattnera9a9e072009-03-09 04:49:14 +00001289 if (EltTy == Type::VoidTy)
1290 return Error(TypeLoc, "array and vector element type cannot be void");
1291
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001292 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1293 "expected end of sequential type"))
1294 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001295
1296 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001297 if (Size == 0)
1298 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001299 if ((unsigned)Size != Size)
1300 return Error(SizeLoc, "size too large for vector");
1301 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1302 return Error(TypeLoc, "vector element type must be fp or integer");
1303 Result = VectorType::get(EltTy, unsigned(Size));
1304 } else {
1305 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1306 return Error(TypeLoc, "invalid array element type");
1307 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1308 }
1309 return false;
1310}
1311
1312//===----------------------------------------------------------------------===//
1313// Function Semantic Analysis.
1314//===----------------------------------------------------------------------===//
1315
1316LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1317 : P(p), F(f) {
1318
1319 // Insert unnamed arguments into the NumberedVals list.
1320 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1321 AI != E; ++AI)
1322 if (!AI->hasName())
1323 NumberedVals.push_back(AI);
1324}
1325
1326LLParser::PerFunctionState::~PerFunctionState() {
1327 // If there were any forward referenced non-basicblock values, delete them.
1328 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1329 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1330 if (!isa<BasicBlock>(I->second.first)) {
1331 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1332 ->getType()));
1333 delete I->second.first;
1334 I->second.first = 0;
1335 }
1336
1337 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1338 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1339 if (!isa<BasicBlock>(I->second.first)) {
1340 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1341 ->getType()));
1342 delete I->second.first;
1343 I->second.first = 0;
1344 }
1345}
1346
1347bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1348 if (!ForwardRefVals.empty())
1349 return P.Error(ForwardRefVals.begin()->second.second,
1350 "use of undefined value '%" + ForwardRefVals.begin()->first +
1351 "'");
1352 if (!ForwardRefValIDs.empty())
1353 return P.Error(ForwardRefValIDs.begin()->second.second,
1354 "use of undefined value '%" +
1355 utostr(ForwardRefValIDs.begin()->first) + "'");
1356 return false;
1357}
1358
1359
1360/// GetVal - Get a value with the specified name or ID, creating a
1361/// forward reference record if needed. This can return null if the value
1362/// exists but does not have the right type.
1363Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1364 const Type *Ty, LocTy Loc) {
1365 // Look this name up in the normal function symbol table.
1366 Value *Val = F.getValueSymbolTable().lookup(Name);
1367
1368 // If this is a forward reference for the value, see if we already created a
1369 // forward ref record.
1370 if (Val == 0) {
1371 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1372 I = ForwardRefVals.find(Name);
1373 if (I != ForwardRefVals.end())
1374 Val = I->second.first;
1375 }
1376
1377 // If we have the value in the symbol table or fwd-ref table, return it.
1378 if (Val) {
1379 if (Val->getType() == Ty) return Val;
1380 if (Ty == Type::LabelTy)
1381 P.Error(Loc, "'%" + Name + "' is not a basic block");
1382 else
1383 P.Error(Loc, "'%" + Name + "' defined with type '" +
1384 Val->getType()->getDescription() + "'");
1385 return 0;
1386 }
1387
1388 // Don't make placeholders with invalid type.
1389 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1390 P.Error(Loc, "invalid use of a non-first-class type");
1391 return 0;
1392 }
1393
1394 // Otherwise, create a new forward reference for this value and remember it.
1395 Value *FwdVal;
1396 if (Ty == Type::LabelTy)
1397 FwdVal = BasicBlock::Create(Name, &F);
1398 else
1399 FwdVal = new Argument(Ty, Name);
1400
1401 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1402 return FwdVal;
1403}
1404
1405Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1406 LocTy Loc) {
1407 // Look this name up in the normal function symbol table.
1408 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1409
1410 // If this is a forward reference for the value, see if we already created a
1411 // forward ref record.
1412 if (Val == 0) {
1413 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1414 I = ForwardRefValIDs.find(ID);
1415 if (I != ForwardRefValIDs.end())
1416 Val = I->second.first;
1417 }
1418
1419 // If we have the value in the symbol table or fwd-ref table, return it.
1420 if (Val) {
1421 if (Val->getType() == Ty) return Val;
1422 if (Ty == Type::LabelTy)
1423 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1424 else
1425 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1426 Val->getType()->getDescription() + "'");
1427 return 0;
1428 }
1429
1430 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1431 P.Error(Loc, "invalid use of a non-first-class type");
1432 return 0;
1433 }
1434
1435 // Otherwise, create a new forward reference for this value and remember it.
1436 Value *FwdVal;
1437 if (Ty == Type::LabelTy)
1438 FwdVal = BasicBlock::Create("", &F);
1439 else
1440 FwdVal = new Argument(Ty);
1441
1442 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1443 return FwdVal;
1444}
1445
1446/// SetInstName - After an instruction is parsed and inserted into its
1447/// basic block, this installs its name.
1448bool LLParser::PerFunctionState::SetInstName(int NameID,
1449 const std::string &NameStr,
1450 LocTy NameLoc, Instruction *Inst) {
1451 // If this instruction has void type, it cannot have a name or ID specified.
1452 if (Inst->getType() == Type::VoidTy) {
1453 if (NameID != -1 || !NameStr.empty())
1454 return P.Error(NameLoc, "instructions returning void cannot have a name");
1455 return false;
1456 }
1457
1458 // If this was a numbered instruction, verify that the instruction is the
1459 // expected value and resolve any forward references.
1460 if (NameStr.empty()) {
1461 // If neither a name nor an ID was specified, just use the next ID.
1462 if (NameID == -1)
1463 NameID = NumberedVals.size();
1464
1465 if (unsigned(NameID) != NumberedVals.size())
1466 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1467 utostr(NumberedVals.size()) + "'");
1468
1469 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1470 ForwardRefValIDs.find(NameID);
1471 if (FI != ForwardRefValIDs.end()) {
1472 if (FI->second.first->getType() != Inst->getType())
1473 return P.Error(NameLoc, "instruction forward referenced with type '" +
1474 FI->second.first->getType()->getDescription() + "'");
1475 FI->second.first->replaceAllUsesWith(Inst);
1476 ForwardRefValIDs.erase(FI);
1477 }
1478
1479 NumberedVals.push_back(Inst);
1480 return false;
1481 }
1482
1483 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1484 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1485 FI = ForwardRefVals.find(NameStr);
1486 if (FI != ForwardRefVals.end()) {
1487 if (FI->second.first->getType() != Inst->getType())
1488 return P.Error(NameLoc, "instruction forward referenced with type '" +
1489 FI->second.first->getType()->getDescription() + "'");
1490 FI->second.first->replaceAllUsesWith(Inst);
1491 ForwardRefVals.erase(FI);
1492 }
1493
1494 // Set the name on the instruction.
1495 Inst->setName(NameStr);
1496
1497 if (Inst->getNameStr() != NameStr)
1498 return P.Error(NameLoc, "multiple definition of local value named '" +
1499 NameStr + "'");
1500 return false;
1501}
1502
1503/// GetBB - Get a basic block with the specified name or ID, creating a
1504/// forward reference record if needed.
1505BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1506 LocTy Loc) {
1507 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1508}
1509
1510BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1511 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1512}
1513
1514/// DefineBB - Define the specified basic block, which is either named or
1515/// unnamed. If there is an error, this returns null otherwise it returns
1516/// the block being defined.
1517BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1518 LocTy Loc) {
1519 BasicBlock *BB;
1520 if (Name.empty())
1521 BB = GetBB(NumberedVals.size(), Loc);
1522 else
1523 BB = GetBB(Name, Loc);
1524 if (BB == 0) return 0; // Already diagnosed error.
1525
1526 // Move the block to the end of the function. Forward ref'd blocks are
1527 // inserted wherever they happen to be referenced.
1528 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1529
1530 // Remove the block from forward ref sets.
1531 if (Name.empty()) {
1532 ForwardRefValIDs.erase(NumberedVals.size());
1533 NumberedVals.push_back(BB);
1534 } else {
1535 // BB forward references are already in the function symbol table.
1536 ForwardRefVals.erase(Name);
1537 }
1538
1539 return BB;
1540}
1541
1542//===----------------------------------------------------------------------===//
1543// Constants.
1544//===----------------------------------------------------------------------===//
1545
1546/// ParseValID - Parse an abstract value that doesn't necessarily have a
1547/// type implied. For example, if we parse "4" we don't know what integer type
1548/// it has. The value will later be combined with its type and checked for
1549/// sanity.
1550bool LLParser::ParseValID(ValID &ID) {
1551 ID.Loc = Lex.getLoc();
1552 switch (Lex.getKind()) {
1553 default: return TokError("expected value token");
1554 case lltok::GlobalID: // @42
1555 ID.UIntVal = Lex.getUIntVal();
1556 ID.Kind = ValID::t_GlobalID;
1557 break;
1558 case lltok::GlobalVar: // @foo
1559 ID.StrVal = Lex.getStrVal();
1560 ID.Kind = ValID::t_GlobalName;
1561 break;
1562 case lltok::LocalVarID: // %42
1563 ID.UIntVal = Lex.getUIntVal();
1564 ID.Kind = ValID::t_LocalID;
1565 break;
1566 case lltok::LocalVar: // %foo
1567 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1568 ID.StrVal = Lex.getStrVal();
1569 ID.Kind = ValID::t_LocalName;
1570 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001571 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1572 ID.Kind = ValID::t_Constant;
1573 Lex.Lex();
1574 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001575 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001576 if (ParseMDNodeVector(Elts) ||
1577 ParseToken(lltok::rbrace, "expected end of metadata node"))
1578 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001579
Jay Foade3e51c02009-05-21 09:52:38 +00001580 ID.ConstantVal = MDNode::get(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001581 return false;
1582 }
1583
1584 // MDString:
1585 // ::= '!' STRINGCONSTANT
1586 std::string Str;
1587 if (ParseStringConstant(Str)) return true;
1588
1589 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1590 return false;
1591 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 case lltok::APSInt:
1593 ID.APSIntVal = Lex.getAPSIntVal();
1594 ID.Kind = ValID::t_APSInt;
1595 break;
1596 case lltok::APFloat:
1597 ID.APFloatVal = Lex.getAPFloatVal();
1598 ID.Kind = ValID::t_APFloat;
1599 break;
1600 case lltok::kw_true:
1601 ID.ConstantVal = ConstantInt::getTrue();
1602 ID.Kind = ValID::t_Constant;
1603 break;
1604 case lltok::kw_false:
1605 ID.ConstantVal = ConstantInt::getFalse();
1606 ID.Kind = ValID::t_Constant;
1607 break;
1608 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1609 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1610 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1611
1612 case lltok::lbrace: {
1613 // ValID ::= '{' ConstVector '}'
1614 Lex.Lex();
1615 SmallVector<Constant*, 16> Elts;
1616 if (ParseGlobalValueVector(Elts) ||
1617 ParseToken(lltok::rbrace, "expected end of struct constant"))
1618 return true;
1619
Jay Foade3e51c02009-05-21 09:52:38 +00001620 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001621 ID.Kind = ValID::t_Constant;
1622 return false;
1623 }
1624 case lltok::less: {
1625 // ValID ::= '<' ConstVector '>' --> Vector.
1626 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1627 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001628 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001629
1630 SmallVector<Constant*, 16> Elts;
1631 LocTy FirstEltLoc = Lex.getLoc();
1632 if (ParseGlobalValueVector(Elts) ||
1633 (isPackedStruct &&
1634 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1635 ParseToken(lltok::greater, "expected end of constant"))
1636 return true;
1637
1638 if (isPackedStruct) {
Jay Foade3e51c02009-05-21 09:52:38 +00001639 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 ID.Kind = ValID::t_Constant;
1641 return false;
1642 }
1643
1644 if (Elts.empty())
1645 return Error(ID.Loc, "constant vector must not be empty");
1646
1647 if (!Elts[0]->getType()->isInteger() &&
1648 !Elts[0]->getType()->isFloatingPoint())
1649 return Error(FirstEltLoc,
1650 "vector elements must have integer or floating point type");
1651
1652 // Verify that all the vector elements have the same type.
1653 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1654 if (Elts[i]->getType() != Elts[0]->getType())
1655 return Error(FirstEltLoc,
1656 "vector element #" + utostr(i) +
1657 " is not of type '" + Elts[0]->getType()->getDescription());
1658
Jay Foade3e51c02009-05-21 09:52:38 +00001659 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001660 ID.Kind = ValID::t_Constant;
1661 return false;
1662 }
1663 case lltok::lsquare: { // Array Constant
1664 Lex.Lex();
1665 SmallVector<Constant*, 16> Elts;
1666 LocTy FirstEltLoc = Lex.getLoc();
1667 if (ParseGlobalValueVector(Elts) ||
1668 ParseToken(lltok::rsquare, "expected end of array constant"))
1669 return true;
1670
1671 // Handle empty element.
1672 if (Elts.empty()) {
1673 // Use undef instead of an array because it's inconvenient to determine
1674 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001675 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 return false;
1677 }
1678
1679 if (!Elts[0]->getType()->isFirstClassType())
1680 return Error(FirstEltLoc, "invalid array element type: " +
1681 Elts[0]->getType()->getDescription());
1682
1683 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1684
1685 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001686 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001687 if (Elts[i]->getType() != Elts[0]->getType())
1688 return Error(FirstEltLoc,
1689 "array element #" + utostr(i) +
1690 " is not of type '" +Elts[0]->getType()->getDescription());
1691 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001692
Jay Foade3e51c02009-05-21 09:52:38 +00001693 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 ID.Kind = ValID::t_Constant;
1695 return false;
1696 }
1697 case lltok::kw_c: // c "foo"
1698 Lex.Lex();
1699 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1700 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1701 ID.Kind = ValID::t_Constant;
1702 return false;
1703
1704 case lltok::kw_asm: {
1705 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1706 bool HasSideEffect;
1707 Lex.Lex();
1708 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001709 ParseStringConstant(ID.StrVal) ||
1710 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 ParseToken(lltok::StringConstant, "expected constraint string"))
1712 return true;
1713 ID.StrVal2 = Lex.getStrVal();
1714 ID.UIntVal = HasSideEffect;
1715 ID.Kind = ValID::t_InlineAsm;
1716 return false;
1717 }
1718
1719 case lltok::kw_trunc:
1720 case lltok::kw_zext:
1721 case lltok::kw_sext:
1722 case lltok::kw_fptrunc:
1723 case lltok::kw_fpext:
1724 case lltok::kw_bitcast:
1725 case lltok::kw_uitofp:
1726 case lltok::kw_sitofp:
1727 case lltok::kw_fptoui:
1728 case lltok::kw_fptosi:
1729 case lltok::kw_inttoptr:
1730 case lltok::kw_ptrtoint: {
1731 unsigned Opc = Lex.getUIntVal();
1732 PATypeHolder DestTy(Type::VoidTy);
1733 Constant *SrcVal;
1734 Lex.Lex();
1735 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1736 ParseGlobalTypeAndValue(SrcVal) ||
1737 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1738 ParseType(DestTy) ||
1739 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1740 return true;
1741 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1742 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1743 SrcVal->getType()->getDescription() + "' to '" +
1744 DestTy->getDescription() + "'");
1745 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1746 DestTy);
1747 ID.Kind = ValID::t_Constant;
1748 return false;
1749 }
1750 case lltok::kw_extractvalue: {
1751 Lex.Lex();
1752 Constant *Val;
1753 SmallVector<unsigned, 4> Indices;
1754 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1755 ParseGlobalTypeAndValue(Val) ||
1756 ParseIndexList(Indices) ||
1757 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1758 return true;
1759 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1760 return Error(ID.Loc, "extractvalue operand must be array or struct");
1761 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1762 Indices.end()))
1763 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001764 ID.ConstantVal =
1765 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001766 ID.Kind = ValID::t_Constant;
1767 return false;
1768 }
1769 case lltok::kw_insertvalue: {
1770 Lex.Lex();
1771 Constant *Val0, *Val1;
1772 SmallVector<unsigned, 4> Indices;
1773 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1774 ParseGlobalTypeAndValue(Val0) ||
1775 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1776 ParseGlobalTypeAndValue(Val1) ||
1777 ParseIndexList(Indices) ||
1778 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1779 return true;
1780 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1781 return Error(ID.Loc, "extractvalue operand must be array or struct");
1782 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1783 Indices.end()))
1784 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001785 ID.ConstantVal =
1786 ConstantExpr::getInsertValue(Val0, Val1, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001787 ID.Kind = ValID::t_Constant;
1788 return false;
1789 }
1790 case lltok::kw_icmp:
1791 case lltok::kw_fcmp:
1792 case lltok::kw_vicmp:
1793 case lltok::kw_vfcmp: {
1794 unsigned PredVal, Opc = Lex.getUIntVal();
1795 Constant *Val0, *Val1;
1796 Lex.Lex();
1797 if (ParseCmpPredicate(PredVal, Opc) ||
1798 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1799 ParseGlobalTypeAndValue(Val0) ||
1800 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1801 ParseGlobalTypeAndValue(Val1) ||
1802 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1803 return true;
1804
1805 if (Val0->getType() != Val1->getType())
1806 return Error(ID.Loc, "compare operands must have the same type");
1807
1808 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1809
1810 if (Opc == Instruction::FCmp) {
1811 if (!Val0->getType()->isFPOrFPVector())
1812 return Error(ID.Loc, "fcmp requires floating point operands");
1813 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1814 } else if (Opc == Instruction::ICmp) {
1815 if (!Val0->getType()->isIntOrIntVector() &&
1816 !isa<PointerType>(Val0->getType()))
1817 return Error(ID.Loc, "icmp requires pointer or integer operands");
1818 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1819 } else if (Opc == Instruction::VFCmp) {
1820 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001821 if (!Val0->getType()->isFPOrFPVector() ||
1822 !isa<VectorType>(Val0->getType()))
1823 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1825 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001826 // FIXME: REMOVE VICMP Support
1827 if (!Val0->getType()->isIntOrIntVector() ||
1828 !isa<VectorType>(Val0->getType()))
1829 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1831 }
1832 ID.Kind = ValID::t_Constant;
1833 return false;
1834 }
1835
1836 // Binary Operators.
1837 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001838 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001839 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001840 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001841 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001842 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001843 case lltok::kw_udiv:
1844 case lltok::kw_sdiv:
1845 case lltok::kw_fdiv:
1846 case lltok::kw_urem:
1847 case lltok::kw_srem:
1848 case lltok::kw_frem: {
1849 unsigned Opc = Lex.getUIntVal();
1850 Constant *Val0, *Val1;
1851 Lex.Lex();
1852 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1853 ParseGlobalTypeAndValue(Val0) ||
1854 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1855 ParseGlobalTypeAndValue(Val1) ||
1856 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1857 return true;
1858 if (Val0->getType() != Val1->getType())
1859 return Error(ID.Loc, "operands of constexpr must have same type");
1860 if (!Val0->getType()->isIntOrIntVector() &&
1861 !Val0->getType()->isFPOrFPVector())
1862 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1863 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1864 ID.Kind = ValID::t_Constant;
1865 return false;
1866 }
1867
1868 // Logical Operations
1869 case lltok::kw_shl:
1870 case lltok::kw_lshr:
1871 case lltok::kw_ashr:
1872 case lltok::kw_and:
1873 case lltok::kw_or:
1874 case lltok::kw_xor: {
1875 unsigned Opc = Lex.getUIntVal();
1876 Constant *Val0, *Val1;
1877 Lex.Lex();
1878 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1879 ParseGlobalTypeAndValue(Val0) ||
1880 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1881 ParseGlobalTypeAndValue(Val1) ||
1882 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1883 return true;
1884 if (Val0->getType() != Val1->getType())
1885 return Error(ID.Loc, "operands of constexpr must have same type");
1886 if (!Val0->getType()->isIntOrIntVector())
1887 return Error(ID.Loc,
1888 "constexpr requires integer or integer vector operands");
1889 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1890 ID.Kind = ValID::t_Constant;
1891 return false;
1892 }
1893
1894 case lltok::kw_getelementptr:
1895 case lltok::kw_shufflevector:
1896 case lltok::kw_insertelement:
1897 case lltok::kw_extractelement:
1898 case lltok::kw_select: {
1899 unsigned Opc = Lex.getUIntVal();
1900 SmallVector<Constant*, 16> Elts;
1901 Lex.Lex();
1902 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1903 ParseGlobalValueVector(Elts) ||
1904 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1905 return true;
1906
1907 if (Opc == Instruction::GetElementPtr) {
1908 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1909 return Error(ID.Loc, "getelementptr requires pointer operand");
1910
1911 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1912 (Value**)&Elts[1], Elts.size()-1))
1913 return Error(ID.Loc, "invalid indices for getelementptr");
1914 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1915 &Elts[1], Elts.size()-1);
1916 } else if (Opc == Instruction::Select) {
1917 if (Elts.size() != 3)
1918 return Error(ID.Loc, "expected three operands to select");
1919 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1920 Elts[2]))
1921 return Error(ID.Loc, Reason);
1922 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1923 } else if (Opc == Instruction::ShuffleVector) {
1924 if (Elts.size() != 3)
1925 return Error(ID.Loc, "expected three operands to shufflevector");
1926 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1927 return Error(ID.Loc, "invalid operands to shufflevector");
1928 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1929 } else if (Opc == Instruction::ExtractElement) {
1930 if (Elts.size() != 2)
1931 return Error(ID.Loc, "expected two operands to extractelement");
1932 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1933 return Error(ID.Loc, "invalid extractelement operands");
1934 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1935 } else {
1936 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1937 if (Elts.size() != 3)
1938 return Error(ID.Loc, "expected three operands to insertelement");
1939 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1940 return Error(ID.Loc, "invalid insertelement operands");
1941 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1942 }
1943
1944 ID.Kind = ValID::t_Constant;
1945 return false;
1946 }
1947 }
1948
1949 Lex.Lex();
1950 return false;
1951}
1952
1953/// ParseGlobalValue - Parse a global value with the specified type.
1954bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1955 V = 0;
1956 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001957 return ParseValID(ID) ||
1958 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001959}
1960
1961/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1962/// constant.
1963bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1964 Constant *&V) {
1965 if (isa<FunctionType>(Ty))
1966 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1967
1968 switch (ID.Kind) {
1969 default: assert(0 && "Unknown ValID!");
1970 case ValID::t_LocalID:
1971 case ValID::t_LocalName:
1972 return Error(ID.Loc, "invalid use of function-local name");
1973 case ValID::t_InlineAsm:
1974 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1975 case ValID::t_GlobalName:
1976 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1977 return V == 0;
1978 case ValID::t_GlobalID:
1979 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1980 return V == 0;
1981 case ValID::t_APSInt:
1982 if (!isa<IntegerType>(Ty))
1983 return Error(ID.Loc, "integer constant must have integer type");
1984 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1985 V = ConstantInt::get(ID.APSIntVal);
1986 return false;
1987 case ValID::t_APFloat:
1988 if (!Ty->isFloatingPoint() ||
1989 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1990 return Error(ID.Loc, "floating point constant invalid for type");
1991
1992 // The lexer has no type info, so builds all float and double FP constants
1993 // as double. Fix this here. Long double does not need this.
1994 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1995 Ty == Type::FloatTy) {
1996 bool Ignored;
1997 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1998 &Ignored);
1999 }
2000 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002001
2002 if (V->getType() != Ty)
2003 return Error(ID.Loc, "floating point constant does not have type '" +
2004 Ty->getDescription() + "'");
2005
Chris Lattnerdf986172009-01-02 07:01:27 +00002006 return false;
2007 case ValID::t_Null:
2008 if (!isa<PointerType>(Ty))
2009 return Error(ID.Loc, "null must be a pointer type");
2010 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2011 return false;
2012 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002013 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002014 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2015 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002016 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 V = UndefValue::get(Ty);
2018 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002019 case ValID::t_EmptyArray:
2020 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2021 return Error(ID.Loc, "invalid empty array initializer");
2022 V = UndefValue::get(Ty);
2023 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002025 // FIXME: LabelTy should not be a first-class type.
2026 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 return Error(ID.Loc, "invalid type for null constant");
2028 V = Constant::getNullValue(Ty);
2029 return false;
2030 case ValID::t_Constant:
2031 if (ID.ConstantVal->getType() != Ty)
2032 return Error(ID.Loc, "constant expression type mismatch");
2033 V = ID.ConstantVal;
2034 return false;
2035 }
2036}
2037
2038bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2039 PATypeHolder Type(Type::VoidTy);
2040 return ParseType(Type) ||
2041 ParseGlobalValue(Type, V);
2042}
2043
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002044/// ParseGlobalValueVector
2045/// ::= /*empty*/
2046/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002047bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2048 // Empty list.
2049 if (Lex.getKind() == lltok::rbrace ||
2050 Lex.getKind() == lltok::rsquare ||
2051 Lex.getKind() == lltok::greater ||
2052 Lex.getKind() == lltok::rparen)
2053 return false;
2054
2055 Constant *C;
2056 if (ParseGlobalTypeAndValue(C)) return true;
2057 Elts.push_back(C);
2058
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002059 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 if (ParseGlobalTypeAndValue(C)) return true;
2061 Elts.push_back(C);
2062 }
2063
2064 return false;
2065}
2066
2067
2068//===----------------------------------------------------------------------===//
2069// Function Parsing.
2070//===----------------------------------------------------------------------===//
2071
2072bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2073 PerFunctionState &PFS) {
2074 if (ID.Kind == ValID::t_LocalID)
2075 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2076 else if (ID.Kind == ValID::t_LocalName)
2077 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002078 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2080 const FunctionType *FTy =
2081 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2082 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2083 return Error(ID.Loc, "invalid type for inline asm constraint string");
2084 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2085 return false;
2086 } else {
2087 Constant *C;
2088 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2089 V = C;
2090 return false;
2091 }
2092
2093 return V == 0;
2094}
2095
2096bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2097 V = 0;
2098 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002099 return ParseValID(ID) ||
2100 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002101}
2102
2103bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2104 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002105 return ParseType(T) ||
2106 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002107}
2108
2109/// FunctionHeader
2110/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2111/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2112/// OptionalAlign OptGC
2113bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2114 // Parse the linkage.
2115 LocTy LinkageLoc = Lex.getLoc();
2116 unsigned Linkage;
2117
2118 unsigned Visibility, CC, RetAttrs;
2119 PATypeHolder RetType(Type::VoidTy);
2120 LocTy RetTypeLoc = Lex.getLoc();
2121 if (ParseOptionalLinkage(Linkage) ||
2122 ParseOptionalVisibility(Visibility) ||
2123 ParseOptionalCallingConv(CC) ||
2124 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002125 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 return true;
2127
2128 // Verify that the linkage is ok.
2129 switch ((GlobalValue::LinkageTypes)Linkage) {
2130 case GlobalValue::ExternalLinkage:
2131 break; // always ok.
2132 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002133 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 if (isDefine)
2135 return Error(LinkageLoc, "invalid linkage for function definition");
2136 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002137 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002139 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002140 case GlobalValue::LinkOnceAnyLinkage:
2141 case GlobalValue::LinkOnceODRLinkage:
2142 case GlobalValue::WeakAnyLinkage:
2143 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 case GlobalValue::DLLExportLinkage:
2145 if (!isDefine)
2146 return Error(LinkageLoc, "invalid linkage for function declaration");
2147 break;
2148 case GlobalValue::AppendingLinkage:
2149 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002150 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 return Error(LinkageLoc, "invalid function linkage type");
2152 }
2153
Chris Lattner99bb3152009-01-05 08:00:30 +00002154 if (!FunctionType::isValidReturnType(RetType) ||
2155 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 return Error(RetTypeLoc, "invalid function return type");
2157
Chris Lattnerdf986172009-01-02 07:01:27 +00002158 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002159
2160 std::string FunctionName;
2161 if (Lex.getKind() == lltok::GlobalVar) {
2162 FunctionName = Lex.getStrVal();
2163 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2164 unsigned NameID = Lex.getUIntVal();
2165
2166 if (NameID != NumberedVals.size())
2167 return TokError("function expected to be numbered '%" +
2168 utostr(NumberedVals.size()) + "'");
2169 } else {
2170 return TokError("expected function name");
2171 }
2172
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002173 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002174
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002175 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 return TokError("expected '(' in function argument list");
2177
2178 std::vector<ArgInfo> ArgList;
2179 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002183 std::string GC;
2184
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002185 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002186 ParseOptionalAttrs(FuncAttrs, 2) ||
2187 (EatIfPresent(lltok::kw_section) &&
2188 ParseStringConstant(Section)) ||
2189 ParseOptionalAlignment(Alignment) ||
2190 (EatIfPresent(lltok::kw_gc) &&
2191 ParseStringConstant(GC)))
2192 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002193
2194 // If the alignment was parsed as an attribute, move to the alignment field.
2195 if (FuncAttrs & Attribute::Alignment) {
2196 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2197 FuncAttrs &= ~Attribute::Alignment;
2198 }
2199
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 // Okay, if we got here, the function is syntactically valid. Convert types
2201 // and do semantic checks.
2202 std::vector<const Type*> ParamTypeList;
2203 SmallVector<AttributeWithIndex, 8> Attrs;
2204 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2205 // attributes.
2206 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2207 if (FuncAttrs & ObsoleteFuncAttrs) {
2208 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2209 FuncAttrs &= ~ObsoleteFuncAttrs;
2210 }
2211
2212 if (RetAttrs != Attribute::None)
2213 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2214
2215 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2216 ParamTypeList.push_back(ArgList[i].Type);
2217 if (ArgList[i].Attrs != Attribute::None)
2218 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2219 }
2220
2221 if (FuncAttrs != Attribute::None)
2222 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2223
2224 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2225
Chris Lattnera9a9e072009-03-09 04:49:14 +00002226 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2227 RetType != Type::VoidTy)
2228 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2229
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2231 const PointerType *PFT = PointerType::getUnqual(FT);
2232
2233 Fn = 0;
2234 if (!FunctionName.empty()) {
2235 // If this was a definition of a forward reference, remove the definition
2236 // from the forward reference table and fill in the forward ref.
2237 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2238 ForwardRefVals.find(FunctionName);
2239 if (FRVI != ForwardRefVals.end()) {
2240 Fn = M->getFunction(FunctionName);
2241 ForwardRefVals.erase(FRVI);
2242 } else if ((Fn = M->getFunction(FunctionName))) {
2243 // If this function already exists in the symbol table, then it is
2244 // multiply defined. We accept a few cases for old backwards compat.
2245 // FIXME: Remove this stuff for LLVM 3.0.
2246 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2247 (!Fn->isDeclaration() && isDefine)) {
2248 // If the redefinition has different type or different attributes,
2249 // reject it. If both have bodies, reject it.
2250 return Error(NameLoc, "invalid redefinition of function '" +
2251 FunctionName + "'");
2252 } else if (Fn->isDeclaration()) {
2253 // Make sure to strip off any argument names so we can't get conflicts.
2254 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2255 AI != AE; ++AI)
2256 AI->setName("");
2257 }
2258 }
2259
2260 } else if (FunctionName.empty()) {
2261 // If this is a definition of a forward referenced function, make sure the
2262 // types agree.
2263 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2264 = ForwardRefValIDs.find(NumberedVals.size());
2265 if (I != ForwardRefValIDs.end()) {
2266 Fn = cast<Function>(I->second.first);
2267 if (Fn->getType() != PFT)
2268 return Error(NameLoc, "type of definition and forward reference of '@" +
2269 utostr(NumberedVals.size()) +"' disagree");
2270 ForwardRefValIDs.erase(I);
2271 }
2272 }
2273
2274 if (Fn == 0)
2275 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2276 else // Move the forward-reference to the correct spot in the module.
2277 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2278
2279 if (FunctionName.empty())
2280 NumberedVals.push_back(Fn);
2281
2282 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2283 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2284 Fn->setCallingConv(CC);
2285 Fn->setAttributes(PAL);
2286 Fn->setAlignment(Alignment);
2287 Fn->setSection(Section);
2288 if (!GC.empty()) Fn->setGC(GC.c_str());
2289
2290 // Add all of the arguments we parsed to the function.
2291 Function::arg_iterator ArgIt = Fn->arg_begin();
2292 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2293 // If the argument has a name, insert it into the argument symbol table.
2294 if (ArgList[i].Name.empty()) continue;
2295
2296 // Set the name, if it conflicted, it will be auto-renamed.
2297 ArgIt->setName(ArgList[i].Name);
2298
2299 if (ArgIt->getNameStr() != ArgList[i].Name)
2300 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2301 ArgList[i].Name + "'");
2302 }
2303
2304 return false;
2305}
2306
2307
2308/// ParseFunctionBody
2309/// ::= '{' BasicBlock+ '}'
2310/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2311///
2312bool LLParser::ParseFunctionBody(Function &Fn) {
2313 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2314 return TokError("expected '{' in function body");
2315 Lex.Lex(); // eat the {.
2316
2317 PerFunctionState PFS(*this, Fn);
2318
2319 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2320 if (ParseBasicBlock(PFS)) return true;
2321
2322 // Eat the }.
2323 Lex.Lex();
2324
2325 // Verify function is ok.
2326 return PFS.VerifyFunctionComplete();
2327}
2328
2329/// ParseBasicBlock
2330/// ::= LabelStr? Instruction*
2331bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2332 // If this basic block starts out with a name, remember it.
2333 std::string Name;
2334 LocTy NameLoc = Lex.getLoc();
2335 if (Lex.getKind() == lltok::LabelStr) {
2336 Name = Lex.getStrVal();
2337 Lex.Lex();
2338 }
2339
2340 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2341 if (BB == 0) return true;
2342
2343 std::string NameStr;
2344
2345 // Parse the instructions in this block until we get a terminator.
2346 Instruction *Inst;
2347 do {
2348 // This instruction may have three possibilities for a name: a) none
2349 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2350 LocTy NameLoc = Lex.getLoc();
2351 int NameID = -1;
2352 NameStr = "";
2353
2354 if (Lex.getKind() == lltok::LocalVarID) {
2355 NameID = Lex.getUIntVal();
2356 Lex.Lex();
2357 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2358 return true;
2359 } else if (Lex.getKind() == lltok::LocalVar ||
2360 // FIXME: REMOVE IN LLVM 3.0
2361 Lex.getKind() == lltok::StringConstant) {
2362 NameStr = Lex.getStrVal();
2363 Lex.Lex();
2364 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2365 return true;
2366 }
2367
2368 if (ParseInstruction(Inst, BB, PFS)) return true;
2369
2370 BB->getInstList().push_back(Inst);
2371
2372 // Set the name on the instruction.
2373 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2374 } while (!isa<TerminatorInst>(Inst));
2375
2376 return false;
2377}
2378
2379//===----------------------------------------------------------------------===//
2380// Instruction Parsing.
2381//===----------------------------------------------------------------------===//
2382
2383/// ParseInstruction - Parse one of the many different instructions.
2384///
2385bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2386 PerFunctionState &PFS) {
2387 lltok::Kind Token = Lex.getKind();
2388 if (Token == lltok::Eof)
2389 return TokError("found end of file when expecting more instructions");
2390 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002391 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 Lex.Lex(); // Eat the keyword.
2393
2394 switch (Token) {
2395 default: return Error(Loc, "expected instruction opcode");
2396 // Terminator Instructions.
2397 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2398 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2399 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2400 case lltok::kw_br: return ParseBr(Inst, PFS);
2401 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2402 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2403 // Binary Operators.
2404 case lltok::kw_add:
2405 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002406 case lltok::kw_mul:
2407 // API compatibility: Accept either integer or floating-point types.
2408 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2409 case lltok::kw_fadd:
2410 case lltok::kw_fsub:
2411 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2412
Chris Lattnerdf986172009-01-02 07:01:27 +00002413 case lltok::kw_udiv:
2414 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002415 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002416 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002417 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002418 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 case lltok::kw_shl:
2420 case lltok::kw_lshr:
2421 case lltok::kw_ashr:
2422 case lltok::kw_and:
2423 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002424 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002425 case lltok::kw_icmp:
2426 case lltok::kw_fcmp:
2427 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002428 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002429 // Casts.
2430 case lltok::kw_trunc:
2431 case lltok::kw_zext:
2432 case lltok::kw_sext:
2433 case lltok::kw_fptrunc:
2434 case lltok::kw_fpext:
2435 case lltok::kw_bitcast:
2436 case lltok::kw_uitofp:
2437 case lltok::kw_sitofp:
2438 case lltok::kw_fptoui:
2439 case lltok::kw_fptosi:
2440 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002441 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 // Other.
2443 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002444 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2446 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2447 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2448 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2449 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2450 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2451 // Memory.
2452 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002453 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002454 case lltok::kw_free: return ParseFree(Inst, PFS);
2455 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2456 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2457 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002458 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002459 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002460 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002461 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002462 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002464 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2465 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2466 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2467 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2468 }
2469}
2470
2471/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2472bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2473 // FIXME: REMOVE vicmp/vfcmp!
2474 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2475 switch (Lex.getKind()) {
2476 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2477 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2478 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2479 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2480 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2481 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2482 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2483 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2484 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2485 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2486 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2487 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2488 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2489 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2490 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2491 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2492 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2493 }
2494 } else {
2495 switch (Lex.getKind()) {
2496 default: TokError("expected icmp predicate (e.g. 'eq')");
2497 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2498 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2499 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2500 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2501 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2502 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2503 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2504 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2505 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2506 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2507 }
2508 }
2509 Lex.Lex();
2510 return false;
2511}
2512
2513//===----------------------------------------------------------------------===//
2514// Terminator Instructions.
2515//===----------------------------------------------------------------------===//
2516
2517/// ParseRet - Parse a return instruction.
2518/// ::= 'ret' void
2519/// ::= 'ret' TypeAndValue
2520/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2521bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2522 PerFunctionState &PFS) {
2523 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002524 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002525
2526 if (Ty == Type::VoidTy) {
2527 Inst = ReturnInst::Create();
2528 return false;
2529 }
2530
2531 Value *RV;
2532 if (ParseValue(Ty, RV, PFS)) return true;
2533
2534 // The normal case is one return value.
2535 if (Lex.getKind() == lltok::comma) {
2536 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2537 // of 'ret {i32,i32} {i32 1, i32 2}'
2538 SmallVector<Value*, 8> RVs;
2539 RVs.push_back(RV);
2540
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002541 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002542 if (ParseTypeAndValue(RV, PFS)) return true;
2543 RVs.push_back(RV);
2544 }
2545
2546 RV = UndefValue::get(PFS.getFunction().getReturnType());
2547 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2548 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2549 BB->getInstList().push_back(I);
2550 RV = I;
2551 }
2552 }
2553 Inst = ReturnInst::Create(RV);
2554 return false;
2555}
2556
2557
2558/// ParseBr
2559/// ::= 'br' TypeAndValue
2560/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2561bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2562 LocTy Loc, Loc2;
2563 Value *Op0, *Op1, *Op2;
2564 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2565
2566 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2567 Inst = BranchInst::Create(BB);
2568 return false;
2569 }
2570
2571 if (Op0->getType() != Type::Int1Ty)
2572 return Error(Loc, "branch condition must have 'i1' type");
2573
2574 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2575 ParseTypeAndValue(Op1, Loc, PFS) ||
2576 ParseToken(lltok::comma, "expected ',' after true destination") ||
2577 ParseTypeAndValue(Op2, Loc2, PFS))
2578 return true;
2579
2580 if (!isa<BasicBlock>(Op1))
2581 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002582 if (!isa<BasicBlock>(Op2))
2583 return Error(Loc2, "true destination of branch must be a basic block");
2584
2585 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2586 return false;
2587}
2588
2589/// ParseSwitch
2590/// Instruction
2591/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2592/// JumpTable
2593/// ::= (TypeAndValue ',' TypeAndValue)*
2594bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2595 LocTy CondLoc, BBLoc;
2596 Value *Cond, *DefaultBB;
2597 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2598 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2599 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2600 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2601 return true;
2602
2603 if (!isa<IntegerType>(Cond->getType()))
2604 return Error(CondLoc, "switch condition must have integer type");
2605 if (!isa<BasicBlock>(DefaultBB))
2606 return Error(BBLoc, "default destination must be a basic block");
2607
2608 // Parse the jump table pairs.
2609 SmallPtrSet<Value*, 32> SeenCases;
2610 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2611 while (Lex.getKind() != lltok::rsquare) {
2612 Value *Constant, *DestBB;
2613
2614 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2615 ParseToken(lltok::comma, "expected ',' after case value") ||
2616 ParseTypeAndValue(DestBB, BBLoc, PFS))
2617 return true;
2618
2619 if (!SeenCases.insert(Constant))
2620 return Error(CondLoc, "duplicate case value in switch");
2621 if (!isa<ConstantInt>(Constant))
2622 return Error(CondLoc, "case value is not a constant integer");
2623 if (!isa<BasicBlock>(DestBB))
2624 return Error(BBLoc, "case destination is not a basic block");
2625
2626 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2627 cast<BasicBlock>(DestBB)));
2628 }
2629
2630 Lex.Lex(); // Eat the ']'.
2631
2632 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2633 Table.size());
2634 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2635 SI->addCase(Table[i].first, Table[i].second);
2636 Inst = SI;
2637 return false;
2638}
2639
2640/// ParseInvoke
2641/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2642/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2643bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2644 LocTy CallLoc = Lex.getLoc();
2645 unsigned CC, RetAttrs, FnAttrs;
2646 PATypeHolder RetType(Type::VoidTy);
2647 LocTy RetTypeLoc;
2648 ValID CalleeID;
2649 SmallVector<ParamInfo, 16> ArgList;
2650
2651 Value *NormalBB, *UnwindBB;
2652 if (ParseOptionalCallingConv(CC) ||
2653 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002654 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 ParseValID(CalleeID) ||
2656 ParseParameterList(ArgList, PFS) ||
2657 ParseOptionalAttrs(FnAttrs, 2) ||
2658 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2659 ParseTypeAndValue(NormalBB, PFS) ||
2660 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2661 ParseTypeAndValue(UnwindBB, PFS))
2662 return true;
2663
2664 if (!isa<BasicBlock>(NormalBB))
2665 return Error(CallLoc, "normal destination is not a basic block");
2666 if (!isa<BasicBlock>(UnwindBB))
2667 return Error(CallLoc, "unwind destination is not a basic block");
2668
2669 // If RetType is a non-function pointer type, then this is the short syntax
2670 // for the call, which means that RetType is just the return type. Infer the
2671 // rest of the function argument types from the arguments that are present.
2672 const PointerType *PFTy = 0;
2673 const FunctionType *Ty = 0;
2674 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2675 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2676 // Pull out the types of all of the arguments...
2677 std::vector<const Type*> ParamTypes;
2678 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2679 ParamTypes.push_back(ArgList[i].V->getType());
2680
2681 if (!FunctionType::isValidReturnType(RetType))
2682 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2683
2684 Ty = FunctionType::get(RetType, ParamTypes, false);
2685 PFTy = PointerType::getUnqual(Ty);
2686 }
2687
2688 // Look up the callee.
2689 Value *Callee;
2690 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2691
2692 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2693 // function attributes.
2694 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2695 if (FnAttrs & ObsoleteFuncAttrs) {
2696 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2697 FnAttrs &= ~ObsoleteFuncAttrs;
2698 }
2699
2700 // Set up the Attributes for the function.
2701 SmallVector<AttributeWithIndex, 8> Attrs;
2702 if (RetAttrs != Attribute::None)
2703 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2704
2705 SmallVector<Value*, 8> Args;
2706
2707 // Loop through FunctionType's arguments and ensure they are specified
2708 // correctly. Also, gather any parameter attributes.
2709 FunctionType::param_iterator I = Ty->param_begin();
2710 FunctionType::param_iterator E = Ty->param_end();
2711 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2712 const Type *ExpectedTy = 0;
2713 if (I != E) {
2714 ExpectedTy = *I++;
2715 } else if (!Ty->isVarArg()) {
2716 return Error(ArgList[i].Loc, "too many arguments specified");
2717 }
2718
2719 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2720 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2721 ExpectedTy->getDescription() + "'");
2722 Args.push_back(ArgList[i].V);
2723 if (ArgList[i].Attrs != Attribute::None)
2724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2725 }
2726
2727 if (I != E)
2728 return Error(CallLoc, "not enough parameters specified for call");
2729
2730 if (FnAttrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2732
2733 // Finish off the Attributes and check them
2734 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2735
2736 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2737 cast<BasicBlock>(UnwindBB),
2738 Args.begin(), Args.end());
2739 II->setCallingConv(CC);
2740 II->setAttributes(PAL);
2741 Inst = II;
2742 return false;
2743}
2744
2745
2746
2747//===----------------------------------------------------------------------===//
2748// Binary Operators.
2749//===----------------------------------------------------------------------===//
2750
2751/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002752/// ::= ArithmeticOps TypeAndValue ',' Value
2753///
2754/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2755/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002756bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002757 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 LocTy Loc; Value *LHS, *RHS;
2759 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2760 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2761 ParseValue(LHS->getType(), RHS, PFS))
2762 return true;
2763
Chris Lattnere914b592009-01-05 08:24:46 +00002764 bool Valid;
2765 switch (OperandType) {
2766 default: assert(0 && "Unknown operand type!");
2767 case 0: // int or FP.
2768 Valid = LHS->getType()->isIntOrIntVector() ||
2769 LHS->getType()->isFPOrFPVector();
2770 break;
2771 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2772 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2773 }
2774
2775 if (!Valid)
2776 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002777
2778 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2779 return false;
2780}
2781
2782/// ParseLogical
2783/// ::= ArithmeticOps TypeAndValue ',' Value {
2784bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2785 unsigned Opc) {
2786 LocTy Loc; Value *LHS, *RHS;
2787 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2788 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2789 ParseValue(LHS->getType(), RHS, PFS))
2790 return true;
2791
2792 if (!LHS->getType()->isIntOrIntVector())
2793 return Error(Loc,"instruction requires integer or integer vector operands");
2794
2795 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2796 return false;
2797}
2798
2799
2800/// ParseCompare
2801/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2802/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2803/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2804/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2805bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2806 unsigned Opc) {
2807 // Parse the integer/fp comparison predicate.
2808 LocTy Loc;
2809 unsigned Pred;
2810 Value *LHS, *RHS;
2811 if (ParseCmpPredicate(Pred, Opc) ||
2812 ParseTypeAndValue(LHS, Loc, PFS) ||
2813 ParseToken(lltok::comma, "expected ',' after compare value") ||
2814 ParseValue(LHS->getType(), RHS, PFS))
2815 return true;
2816
2817 if (Opc == Instruction::FCmp) {
2818 if (!LHS->getType()->isFPOrFPVector())
2819 return Error(Loc, "fcmp requires floating point operands");
2820 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2821 } else if (Opc == Instruction::ICmp) {
2822 if (!LHS->getType()->isIntOrIntVector() &&
2823 !isa<PointerType>(LHS->getType()))
2824 return Error(Loc, "icmp requires integer operands");
2825 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2826 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002827 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2828 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2830 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002831 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2832 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2834 }
2835 return false;
2836}
2837
2838//===----------------------------------------------------------------------===//
2839// Other Instructions.
2840//===----------------------------------------------------------------------===//
2841
2842
2843/// ParseCast
2844/// ::= CastOpc TypeAndValue 'to' Type
2845bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2846 unsigned Opc) {
2847 LocTy Loc; Value *Op;
2848 PATypeHolder DestTy(Type::VoidTy);
2849 if (ParseTypeAndValue(Op, Loc, PFS) ||
2850 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2851 ParseType(DestTy))
2852 return true;
2853
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002854 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2855 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002856 return Error(Loc, "invalid cast opcode for cast from '" +
2857 Op->getType()->getDescription() + "' to '" +
2858 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002859 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2861 return false;
2862}
2863
2864/// ParseSelect
2865/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2866bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2867 LocTy Loc;
2868 Value *Op0, *Op1, *Op2;
2869 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2870 ParseToken(lltok::comma, "expected ',' after select condition") ||
2871 ParseTypeAndValue(Op1, PFS) ||
2872 ParseToken(lltok::comma, "expected ',' after select value") ||
2873 ParseTypeAndValue(Op2, PFS))
2874 return true;
2875
2876 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2877 return Error(Loc, Reason);
2878
2879 Inst = SelectInst::Create(Op0, Op1, Op2);
2880 return false;
2881}
2882
Chris Lattner0088a5c2009-01-05 08:18:44 +00002883/// ParseVA_Arg
2884/// ::= 'va_arg' TypeAndValue ',' Type
2885bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002886 Value *Op;
2887 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002888 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 if (ParseTypeAndValue(Op, PFS) ||
2890 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002891 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002893
2894 if (!EltTy->isFirstClassType())
2895 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002896
2897 Inst = new VAArgInst(Op, EltTy);
2898 return false;
2899}
2900
2901/// ParseExtractElement
2902/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2903bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2904 LocTy Loc;
2905 Value *Op0, *Op1;
2906 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2907 ParseToken(lltok::comma, "expected ',' after extract value") ||
2908 ParseTypeAndValue(Op1, PFS))
2909 return true;
2910
2911 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2912 return Error(Loc, "invalid extractelement operands");
2913
2914 Inst = new ExtractElementInst(Op0, Op1);
2915 return false;
2916}
2917
2918/// ParseInsertElement
2919/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2920bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2921 LocTy Loc;
2922 Value *Op0, *Op1, *Op2;
2923 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2924 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2925 ParseTypeAndValue(Op1, PFS) ||
2926 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2927 ParseTypeAndValue(Op2, PFS))
2928 return true;
2929
2930 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2931 return Error(Loc, "invalid extractelement operands");
2932
2933 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2934 return false;
2935}
2936
2937/// ParseShuffleVector
2938/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2939bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2940 LocTy Loc;
2941 Value *Op0, *Op1, *Op2;
2942 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2943 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2944 ParseTypeAndValue(Op1, PFS) ||
2945 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2946 ParseTypeAndValue(Op2, PFS))
2947 return true;
2948
2949 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2950 return Error(Loc, "invalid extractelement operands");
2951
2952 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2953 return false;
2954}
2955
2956/// ParsePHI
2957/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2958bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2959 PATypeHolder Ty(Type::VoidTy);
2960 Value *Op0, *Op1;
2961 LocTy TypeLoc = Lex.getLoc();
2962
2963 if (ParseType(Ty) ||
2964 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2965 ParseValue(Ty, Op0, PFS) ||
2966 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2967 ParseValue(Type::LabelTy, Op1, PFS) ||
2968 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2969 return true;
2970
2971 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2972 while (1) {
2973 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2974
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002975 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002976 break;
2977
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002978 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002979 ParseValue(Ty, Op0, PFS) ||
2980 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2981 ParseValue(Type::LabelTy, Op1, PFS) ||
2982 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2983 return true;
2984 }
2985
2986 if (!Ty->isFirstClassType())
2987 return Error(TypeLoc, "phi node must have first class type");
2988
2989 PHINode *PN = PHINode::Create(Ty);
2990 PN->reserveOperandSpace(PHIVals.size());
2991 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2992 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2993 Inst = PN;
2994 return false;
2995}
2996
2997/// ParseCall
2998/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2999/// ParameterList OptionalAttrs
3000bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3001 bool isTail) {
3002 unsigned CC, RetAttrs, FnAttrs;
3003 PATypeHolder RetType(Type::VoidTy);
3004 LocTy RetTypeLoc;
3005 ValID CalleeID;
3006 SmallVector<ParamInfo, 16> ArgList;
3007 LocTy CallLoc = Lex.getLoc();
3008
3009 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3010 ParseOptionalCallingConv(CC) ||
3011 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003012 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 ParseValID(CalleeID) ||
3014 ParseParameterList(ArgList, PFS) ||
3015 ParseOptionalAttrs(FnAttrs, 2))
3016 return true;
3017
3018 // If RetType is a non-function pointer type, then this is the short syntax
3019 // for the call, which means that RetType is just the return type. Infer the
3020 // rest of the function argument types from the arguments that are present.
3021 const PointerType *PFTy = 0;
3022 const FunctionType *Ty = 0;
3023 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3024 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3025 // Pull out the types of all of the arguments...
3026 std::vector<const Type*> ParamTypes;
3027 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3028 ParamTypes.push_back(ArgList[i].V->getType());
3029
3030 if (!FunctionType::isValidReturnType(RetType))
3031 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3032
3033 Ty = FunctionType::get(RetType, ParamTypes, false);
3034 PFTy = PointerType::getUnqual(Ty);
3035 }
3036
3037 // Look up the callee.
3038 Value *Callee;
3039 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3040
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3042 // function attributes.
3043 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3044 if (FnAttrs & ObsoleteFuncAttrs) {
3045 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3046 FnAttrs &= ~ObsoleteFuncAttrs;
3047 }
3048
3049 // Set up the Attributes for the function.
3050 SmallVector<AttributeWithIndex, 8> Attrs;
3051 if (RetAttrs != Attribute::None)
3052 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3053
3054 SmallVector<Value*, 8> Args;
3055
3056 // Loop through FunctionType's arguments and ensure they are specified
3057 // correctly. Also, gather any parameter attributes.
3058 FunctionType::param_iterator I = Ty->param_begin();
3059 FunctionType::param_iterator E = Ty->param_end();
3060 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3061 const Type *ExpectedTy = 0;
3062 if (I != E) {
3063 ExpectedTy = *I++;
3064 } else if (!Ty->isVarArg()) {
3065 return Error(ArgList[i].Loc, "too many arguments specified");
3066 }
3067
3068 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3069 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3070 ExpectedTy->getDescription() + "'");
3071 Args.push_back(ArgList[i].V);
3072 if (ArgList[i].Attrs != Attribute::None)
3073 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3074 }
3075
3076 if (I != E)
3077 return Error(CallLoc, "not enough parameters specified for call");
3078
3079 if (FnAttrs != Attribute::None)
3080 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3081
3082 // Finish off the Attributes and check them
3083 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3084
3085 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3086 CI->setTailCall(isTail);
3087 CI->setCallingConv(CC);
3088 CI->setAttributes(PAL);
3089 Inst = CI;
3090 return false;
3091}
3092
3093//===----------------------------------------------------------------------===//
3094// Memory Instructions.
3095//===----------------------------------------------------------------------===//
3096
3097/// ParseAlloc
3098/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3099/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3100bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3101 unsigned Opc) {
3102 PATypeHolder Ty(Type::VoidTy);
3103 Value *Size = 0;
3104 LocTy SizeLoc = 0;
3105 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003106 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003107
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003108 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 if (Lex.getKind() == lltok::kw_align) {
3110 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003111 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3112 ParseOptionalCommaAlignment(Alignment)) {
3113 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003114 }
3115 }
3116
3117 if (Size && Size->getType() != Type::Int32Ty)
3118 return Error(SizeLoc, "element count must be i32");
3119
3120 if (Opc == Instruction::Malloc)
3121 Inst = new MallocInst(Ty, Size, Alignment);
3122 else
3123 Inst = new AllocaInst(Ty, Size, Alignment);
3124 return false;
3125}
3126
3127/// ParseFree
3128/// ::= 'free' TypeAndValue
3129bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3130 Value *Val; LocTy Loc;
3131 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3132 if (!isa<PointerType>(Val->getType()))
3133 return Error(Loc, "operand to free must be a pointer");
3134 Inst = new FreeInst(Val);
3135 return false;
3136}
3137
3138/// ParseLoad
3139/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3140bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3141 bool isVolatile) {
3142 Value *Val; LocTy Loc;
3143 unsigned Alignment;
3144 if (ParseTypeAndValue(Val, Loc, PFS) ||
3145 ParseOptionalCommaAlignment(Alignment))
3146 return true;
3147
3148 if (!isa<PointerType>(Val->getType()) ||
3149 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3150 return Error(Loc, "load operand must be a pointer to a first class type");
3151
3152 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3153 return false;
3154}
3155
3156/// ParseStore
3157/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3158bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3159 bool isVolatile) {
3160 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3161 unsigned Alignment;
3162 if (ParseTypeAndValue(Val, Loc, PFS) ||
3163 ParseToken(lltok::comma, "expected ',' after store operand") ||
3164 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3165 ParseOptionalCommaAlignment(Alignment))
3166 return true;
3167
3168 if (!isa<PointerType>(Ptr->getType()))
3169 return Error(PtrLoc, "store operand must be a pointer");
3170 if (!Val->getType()->isFirstClassType())
3171 return Error(Loc, "store operand must be a first class value");
3172 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3173 return Error(Loc, "stored value and pointer type do not match");
3174
3175 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3176 return false;
3177}
3178
3179/// ParseGetResult
3180/// ::= 'getresult' TypeAndValue ',' uint
3181/// FIXME: Remove support for getresult in LLVM 3.0
3182bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3183 Value *Val; LocTy ValLoc, EltLoc;
3184 unsigned Element;
3185 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3186 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003187 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003188 return true;
3189
3190 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3191 return Error(ValLoc, "getresult inst requires an aggregate operand");
3192 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3193 return Error(EltLoc, "invalid getresult index for value");
3194 Inst = ExtractValueInst::Create(Val, Element);
3195 return false;
3196}
3197
3198/// ParseGetElementPtr
3199/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3200bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3201 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003202 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003203
3204 if (!isa<PointerType>(Ptr->getType()))
3205 return Error(Loc, "base of getelementptr must be a pointer");
3206
3207 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003208 while (EatIfPresent(lltok::comma)) {
3209 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 if (!isa<IntegerType>(Val->getType()))
3211 return Error(EltLoc, "getelementptr index must be an integer");
3212 Indices.push_back(Val);
3213 }
3214
3215 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3216 Indices.begin(), Indices.end()))
3217 return Error(Loc, "invalid getelementptr indices");
3218 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3219 return false;
3220}
3221
3222/// ParseExtractValue
3223/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3224bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3225 Value *Val; LocTy Loc;
3226 SmallVector<unsigned, 4> Indices;
3227 if (ParseTypeAndValue(Val, Loc, PFS) ||
3228 ParseIndexList(Indices))
3229 return true;
3230
3231 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3232 return Error(Loc, "extractvalue operand must be array or struct");
3233
3234 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3235 Indices.end()))
3236 return Error(Loc, "invalid indices for extractvalue");
3237 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3238 return false;
3239}
3240
3241/// ParseInsertValue
3242/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3243bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3244 Value *Val0, *Val1; LocTy Loc0, Loc1;
3245 SmallVector<unsigned, 4> Indices;
3246 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3247 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3248 ParseTypeAndValue(Val1, Loc1, PFS) ||
3249 ParseIndexList(Indices))
3250 return true;
3251
3252 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3253 return Error(Loc0, "extractvalue operand must be array or struct");
3254
3255 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3256 Indices.end()))
3257 return Error(Loc0, "invalid indices for insertvalue");
3258 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3259 return false;
3260}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003261
3262//===----------------------------------------------------------------------===//
3263// Embedded metadata.
3264//===----------------------------------------------------------------------===//
3265
3266/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003267/// ::= Element (',' Element)*
3268/// Element
3269/// ::= 'null' | TypeAndValue
3270bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003271 assert(Lex.getKind() == lltok::lbrace);
3272 Lex.Lex();
3273 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003274 Value *V;
3275 if (Lex.getKind() == lltok::kw_null) {
3276 Lex.Lex();
3277 V = 0;
3278 } else {
3279 Constant *C;
3280 if (ParseGlobalTypeAndValue(C)) return true;
3281 V = C;
3282 }
3283 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003284 } while (EatIfPresent(lltok::comma));
3285
3286 return false;
3287}