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