blob: cb9eb6ad9aa9dbd6321f0625a26de704fdf3611c [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
Chris Lattnerdf986172009-01-02 07:01:27 +0000238 // See if this type was previously referenced.
239 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
240 FI = ForwardRefTypeIDs.find(TypeID);
241 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000242 if (FI->second.first.get() == Ty)
243 return Error(TypeLoc, "self referential type is invalid");
244
Chris Lattnerdf986172009-01-02 07:01:27 +0000245 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
246 Ty = FI->second.first.get();
247 ForwardRefTypeIDs.erase(FI);
248 }
249
250 NumberedTypes.push_back(Ty);
251
252 return false;
253}
254
255/// toplevelentity
256/// ::= LocalVar '=' 'type' type
257bool LLParser::ParseNamedType() {
258 std::string Name = Lex.getStrVal();
259 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000260 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000261
262 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263
264 if (ParseToken(lltok::equal, "expected '=' after name") ||
265 ParseToken(lltok::kw_type, "expected 'type' after name") ||
266 ParseType(Ty))
267 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000268
Chris Lattnerdf986172009-01-02 07:01:27 +0000269 // Set the type name, checking for conflicts as we do so.
270 bool AlreadyExists = M->addTypeName(Name, Ty);
271 if (!AlreadyExists) return false;
272
273 // See if this type is a forward reference. We need to eagerly resolve
274 // types to allow recursive type redefinitions below.
275 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
276 FI = ForwardRefTypes.find(Name);
277 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000278 if (FI->second.first.get() == Ty)
279 return Error(NameLoc, "self referential type is invalid");
280
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
282 Ty = FI->second.first.get();
283 ForwardRefTypes.erase(FI);
284 }
285
286 // Inserting a name that is already defined, get the existing name.
287 const Type *Existing = M->getTypeByName(Name);
288 assert(Existing && "Conflict but no matching type?!");
289
290 // Otherwise, this is an attempt to redefine a type. That's okay if
291 // the redefinition is identical to the original.
292 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
293 if (Existing == Ty) return false;
294
295 // Any other kind of (non-equivalent) redefinition is an error.
296 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
297 Ty->getDescription() + "'");
298}
299
300
301/// toplevelentity
302/// ::= 'declare' FunctionHeader
303bool LLParser::ParseDeclare() {
304 assert(Lex.getKind() == lltok::kw_declare);
305 Lex.Lex();
306
307 Function *F;
308 return ParseFunctionHeader(F, false);
309}
310
311/// toplevelentity
312/// ::= 'define' FunctionHeader '{' ...
313bool LLParser::ParseDefine() {
314 assert(Lex.getKind() == lltok::kw_define);
315 Lex.Lex();
316
317 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000318 return ParseFunctionHeader(F, true) ||
319 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000320}
321
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000322/// ParseGlobalType
323/// ::= 'constant'
324/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000325bool LLParser::ParseGlobalType(bool &IsConstant) {
326 if (Lex.getKind() == lltok::kw_constant)
327 IsConstant = true;
328 else if (Lex.getKind() == lltok::kw_global)
329 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000330 else {
331 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000333 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000334 Lex.Lex();
335 return false;
336}
337
338/// ParseNamedGlobal:
339/// GlobalVar '=' OptionalVisibility ALIAS ...
340/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
341bool LLParser::ParseNamedGlobal() {
342 assert(Lex.getKind() == lltok::GlobalVar);
343 LocTy NameLoc = Lex.getLoc();
344 std::string Name = Lex.getStrVal();
345 Lex.Lex();
346
347 bool HasLinkage;
348 unsigned Linkage, Visibility;
349 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
350 ParseOptionalLinkage(Linkage, HasLinkage) ||
351 ParseOptionalVisibility(Visibility))
352 return true;
353
354 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
355 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
356 return ParseAlias(Name, NameLoc, Visibility);
357}
358
359/// ParseAlias:
360/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
361/// Aliasee
362/// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
363///
364/// Everything through visibility has already been parsed.
365///
366bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
367 unsigned Visibility) {
368 assert(Lex.getKind() == lltok::kw_alias);
369 Lex.Lex();
370 unsigned Linkage;
371 LocTy LinkageLoc = Lex.getLoc();
372 if (ParseOptionalLinkage(Linkage))
373 return true;
374
375 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000376 Linkage != GlobalValue::WeakAnyLinkage &&
377 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000378 Linkage != GlobalValue::InternalLinkage &&
379 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 return Error(LinkageLoc, "invalid linkage type for alias");
381
382 Constant *Aliasee;
383 LocTy AliaseeLoc = Lex.getLoc();
384 if (Lex.getKind() != lltok::kw_bitcast) {
385 if (ParseGlobalTypeAndValue(Aliasee)) return true;
386 } else {
387 // The bitcast dest type is not present, it is implied by the dest type.
388 ValID ID;
389 if (ParseValID(ID)) return true;
390 if (ID.Kind != ValID::t_Constant)
391 return Error(AliaseeLoc, "invalid aliasee");
392 Aliasee = ID.ConstantVal;
393 }
394
395 if (!isa<PointerType>(Aliasee->getType()))
396 return Error(AliaseeLoc, "alias must have pointer type");
397
398 // Okay, create the alias but do not insert it into the module yet.
399 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
400 (GlobalValue::LinkageTypes)Linkage, Name,
401 Aliasee);
402 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
403
404 // See if this value already exists in the symbol table. If so, it is either
405 // a redefinition or a definition of a forward reference.
406 if (GlobalValue *Val =
407 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
408 // See if this was a redefinition. If so, there is no entry in
409 // ForwardRefVals.
410 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
411 I = ForwardRefVals.find(Name);
412 if (I == ForwardRefVals.end())
413 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
414
415 // Otherwise, this was a definition of forward ref. Verify that types
416 // agree.
417 if (Val->getType() != GA->getType())
418 return Error(NameLoc,
419 "forward reference and definition of alias have different types");
420
421 // If they agree, just RAUW the old value with the alias and remove the
422 // forward ref info.
423 Val->replaceAllUsesWith(GA);
424 Val->eraseFromParent();
425 ForwardRefVals.erase(I);
426 }
427
428 // Insert into the module, we know its name won't collide now.
429 M->getAliasList().push_back(GA);
430 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
431
432 return false;
433}
434
435/// ParseGlobal
436/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
437/// OptionalAddrSpace GlobalType Type Const
438/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
439/// OptionalAddrSpace GlobalType Type Const
440///
441/// Everything through visibility has been parsed already.
442///
443bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
444 unsigned Linkage, bool HasLinkage,
445 unsigned Visibility) {
446 unsigned AddrSpace;
447 bool ThreadLocal, IsConstant;
448 LocTy TyLoc;
449
450 PATypeHolder Ty(Type::VoidTy);
451 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
452 ParseOptionalAddrSpace(AddrSpace) ||
453 ParseGlobalType(IsConstant) ||
454 ParseType(Ty, TyLoc))
455 return true;
456
457 // If the linkage is specified and is external, then no initializer is
458 // present.
459 Constant *Init = 0;
460 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000461 Linkage != GlobalValue::ExternalWeakAnyLinkage &&
462 Linkage != GlobalValue::ExternalWeakODRLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000463 Linkage != GlobalValue::ExternalLinkage)) {
464 if (ParseGlobalValue(Ty, Init))
465 return true;
466 }
467
Chris Lattnera9a9e072009-03-09 04:49:14 +0000468 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000469 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000470
471 GlobalVariable *GV = 0;
472
473 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000474 if (!Name.empty()) {
475 if ((GV = M->getGlobalVariable(Name, true)) &&
476 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000477 return Error(NameLoc, "redefinition of global '@" + Name + "'");
478 } else {
479 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
480 I = ForwardRefValIDs.find(NumberedVals.size());
481 if (I != ForwardRefValIDs.end()) {
482 GV = cast<GlobalVariable>(I->second.first);
483 ForwardRefValIDs.erase(I);
484 }
485 }
486
487 if (GV == 0) {
488 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
489 M, false, AddrSpace);
490 } else {
491 if (GV->getType()->getElementType() != Ty)
492 return Error(TyLoc,
493 "forward reference and definition of global have different types");
494
495 // Move the forward-reference to the correct spot in the module.
496 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
497 }
498
499 if (Name.empty())
500 NumberedVals.push_back(GV);
501
502 // Set the parsed properties on the global.
503 if (Init)
504 GV->setInitializer(Init);
505 GV->setConstant(IsConstant);
506 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
507 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
508 GV->setThreadLocal(ThreadLocal);
509
510 // Parse attributes on the global.
511 while (Lex.getKind() == lltok::comma) {
512 Lex.Lex();
513
514 if (Lex.getKind() == lltok::kw_section) {
515 Lex.Lex();
516 GV->setSection(Lex.getStrVal());
517 if (ParseToken(lltok::StringConstant, "expected global section string"))
518 return true;
519 } else if (Lex.getKind() == lltok::kw_align) {
520 unsigned Alignment;
521 if (ParseOptionalAlignment(Alignment)) return true;
522 GV->setAlignment(Alignment);
523 } else {
524 TokError("unknown global variable property!");
525 }
526 }
527
528 return false;
529}
530
531
532//===----------------------------------------------------------------------===//
533// GlobalValue Reference/Resolution Routines.
534//===----------------------------------------------------------------------===//
535
536/// GetGlobalVal - Get a value with the specified name or ID, creating a
537/// forward reference record if needed. This can return null if the value
538/// exists but does not have the right type.
539GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
540 LocTy Loc) {
541 const PointerType *PTy = dyn_cast<PointerType>(Ty);
542 if (PTy == 0) {
543 Error(Loc, "global variable reference must have pointer type");
544 return 0;
545 }
546
547 // Look this name up in the normal function symbol table.
548 GlobalValue *Val =
549 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
550
551 // If this is a forward reference for the value, see if we already created a
552 // forward ref record.
553 if (Val == 0) {
554 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
555 I = ForwardRefVals.find(Name);
556 if (I != ForwardRefVals.end())
557 Val = I->second.first;
558 }
559
560 // If we have the value in the symbol table or fwd-ref table, return it.
561 if (Val) {
562 if (Val->getType() == Ty) return Val;
563 Error(Loc, "'@" + Name + "' defined with type '" +
564 Val->getType()->getDescription() + "'");
565 return 0;
566 }
567
568 // Otherwise, create a new forward reference for this value and remember it.
569 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000570 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
571 // Function types can return opaque but functions can't.
572 if (isa<OpaqueType>(FT->getReturnType())) {
573 Error(Loc, "function may not return opaque type");
574 return 0;
575 }
576
Duncan Sands667d4b82009-03-07 15:45:40 +0000577 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakAnyLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000578 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000579 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000580 GlobalValue::ExternalWeakAnyLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000581 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000582
583 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
584 return FwdVal;
585}
586
587GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
588 const PointerType *PTy = dyn_cast<PointerType>(Ty);
589 if (PTy == 0) {
590 Error(Loc, "global variable reference must have pointer type");
591 return 0;
592 }
593
594 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
595
596 // If this is a forward reference for the value, see if we already created a
597 // forward ref record.
598 if (Val == 0) {
599 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
600 I = ForwardRefValIDs.find(ID);
601 if (I != ForwardRefValIDs.end())
602 Val = I->second.first;
603 }
604
605 // If we have the value in the symbol table or fwd-ref table, return it.
606 if (Val) {
607 if (Val->getType() == Ty) return Val;
608 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
609 Val->getType()->getDescription() + "'");
610 return 0;
611 }
612
613 // Otherwise, create a new forward reference for this value and remember it.
614 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000615 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
616 // Function types can return opaque but functions can't.
617 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000618 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000619 return 0;
620 }
Duncan Sands667d4b82009-03-07 15:45:40 +0000621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakAnyLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000622 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +0000623 FwdVal = new GlobalVariable(PTy->getElementType(), false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000624 GlobalValue::ExternalWeakAnyLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000625 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000626
627 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
628 return FwdVal;
629}
630
631
632//===----------------------------------------------------------------------===//
633// Helper Routines.
634//===----------------------------------------------------------------------===//
635
636/// ParseToken - If the current token has the specified kind, eat it and return
637/// success. Otherwise, emit the specified error and return failure.
638bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
639 if (Lex.getKind() != T)
640 return TokError(ErrMsg);
641 Lex.Lex();
642 return false;
643}
644
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000645/// ParseStringConstant
646/// ::= StringConstant
647bool LLParser::ParseStringConstant(std::string &Result) {
648 if (Lex.getKind() != lltok::StringConstant)
649 return TokError("expected string constant");
650 Result = Lex.getStrVal();
651 Lex.Lex();
652 return false;
653}
654
655/// ParseUInt32
656/// ::= uint32
657bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
659 return TokError("expected integer");
660 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
661 if (Val64 != unsigned(Val64))
662 return TokError("expected 32-bit integer (too large)");
663 Val = Val64;
664 Lex.Lex();
665 return false;
666}
667
668
669/// ParseOptionalAddrSpace
670/// := /*empty*/
671/// := 'addrspace' '(' uint32 ')'
672bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
673 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000674 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000677 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 ParseToken(lltok::rparen, "expected ')' in address space");
679}
680
681/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
682/// indicates what kind of attribute list this is: 0: function arg, 1: result,
683/// 2: function attr.
684bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
685 Attrs = Attribute::None;
686 LocTy AttrLoc = Lex.getLoc();
687
688 while (1) {
689 switch (Lex.getKind()) {
690 case lltok::kw_sext:
691 case lltok::kw_zext:
692 // Treat these as signext/zeroext unless they are function attrs.
693 // FIXME: REMOVE THIS IN LLVM 3.0
694 if (AttrKind != 2) {
695 if (Lex.getKind() == lltok::kw_sext)
696 Attrs |= Attribute::SExt;
697 else
698 Attrs |= Attribute::ZExt;
699 break;
700 }
701 // FALL THROUGH.
702 default: // End of attributes.
703 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
704 return Error(AttrLoc, "invalid use of function-only attribute");
705
706 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
707 return Error(AttrLoc, "invalid use of parameter-only attribute");
708
709 return false;
710 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
711 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
712 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
713 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
714 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
715 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
716 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
717 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
718
719 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
720 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
721 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
722 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
723 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
724 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
725 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
726 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
727 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
728
729
730 case lltok::kw_align: {
731 unsigned Alignment;
732 if (ParseOptionalAlignment(Alignment))
733 return true;
734 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
735 continue;
736 }
737 }
738 Lex.Lex();
739 }
740}
741
742/// ParseOptionalLinkage
743/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000744/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000745/// ::= 'internal'
746/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000747/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000748/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000749/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000750/// ::= 'appending'
751/// ::= 'dllexport'
752/// ::= 'common'
Duncan Sands667d4b82009-03-07 15:45:40 +0000753/// ::= 'common_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000754/// ::= 'dllimport'
755/// ::= 'extern_weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000756/// ::= 'extern_weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000757/// ::= 'external'
758bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
759 HasLinkage = false;
760 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000761 default: Res = GlobalValue::ExternalLinkage; return false;
762 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
763 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
764 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
765 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
766 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
767 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
768 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
769 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
770 case lltok::kw_common: Res = GlobalValue::CommonAnyLinkage; break;
771 case lltok::kw_common_odr: Res = GlobalValue::CommonODRLinkage; break;
772 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
773 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakAnyLinkage; break;
774 case lltok::kw_extern_weak_odr:
775 Res = GlobalValue::ExternalWeakODRLinkage; break;
776 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 }
778 Lex.Lex();
779 HasLinkage = true;
780 return false;
781}
782
783/// ParseOptionalVisibility
784/// ::= /*empty*/
785/// ::= 'default'
786/// ::= 'hidden'
787/// ::= 'protected'
788///
789bool LLParser::ParseOptionalVisibility(unsigned &Res) {
790 switch (Lex.getKind()) {
791 default: Res = GlobalValue::DefaultVisibility; return false;
792 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
793 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
794 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
795 }
796 Lex.Lex();
797 return false;
798}
799
800/// ParseOptionalCallingConv
801/// ::= /*empty*/
802/// ::= 'ccc'
803/// ::= 'fastcc'
804/// ::= 'coldcc'
805/// ::= 'x86_stdcallcc'
806/// ::= 'x86_fastcallcc'
807/// ::= 'cc' UINT
808///
809bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
810 switch (Lex.getKind()) {
811 default: CC = CallingConv::C; return false;
812 case lltok::kw_ccc: CC = CallingConv::C; break;
813 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
814 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
815 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
816 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000817 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000818 }
819 Lex.Lex();
820 return false;
821}
822
823/// ParseOptionalAlignment
824/// ::= /* empty */
825/// ::= 'align' 4
826bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
827 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000828 if (!EatIfPresent(lltok::kw_align))
829 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000830 LocTy AlignLoc = Lex.getLoc();
831 if (ParseUInt32(Alignment)) return true;
832 if (!isPowerOf2_32(Alignment))
833 return Error(AlignLoc, "alignment is not a power of two");
834 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000835}
836
837/// ParseOptionalCommaAlignment
838/// ::= /* empty */
839/// ::= ',' 'align' 4
840bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
841 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000842 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000845 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000846}
847
848/// ParseIndexList
849/// ::= (',' uint32)+
850bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
851 if (Lex.getKind() != lltok::comma)
852 return TokError("expected ',' as start of index list");
853
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000854 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000856 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 Indices.push_back(Idx);
858 }
859
860 return false;
861}
862
863//===----------------------------------------------------------------------===//
864// Type Parsing.
865//===----------------------------------------------------------------------===//
866
867/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000868bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
869 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000870 if (ParseTypeRec(Result)) return true;
871
872 // Verify no unresolved uprefs.
873 if (!UpRefs.empty())
874 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000875
Chris Lattnera9a9e072009-03-09 04:49:14 +0000876 if (!AllowVoid && Result.get() == Type::VoidTy)
877 return Error(TypeLoc, "void type only allowed for function results");
878
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 return false;
880}
881
882/// HandleUpRefs - Every time we finish a new layer of types, this function is
883/// called. It loops through the UpRefs vector, which is a list of the
884/// currently active types. For each type, if the up-reference is contained in
885/// the newly completed type, we decrement the level count. When the level
886/// count reaches zero, the up-referenced type is the type that is passed in:
887/// thus we can complete the cycle.
888///
889PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
890 // If Ty isn't abstract, or if there are no up-references in it, then there is
891 // nothing to resolve here.
892 if (!ty->isAbstract() || UpRefs.empty()) return ty;
893
894 PATypeHolder Ty(ty);
895#if 0
896 errs() << "Type '" << Ty->getDescription()
897 << "' newly formed. Resolving upreferences.\n"
898 << UpRefs.size() << " upreferences active!\n";
899#endif
900
901 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
902 // to zero), we resolve them all together before we resolve them to Ty. At
903 // the end of the loop, if there is anything to resolve to Ty, it will be in
904 // this variable.
905 OpaqueType *TypeToResolve = 0;
906
907 for (unsigned i = 0; i != UpRefs.size(); ++i) {
908 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
909 bool ContainsType =
910 std::find(Ty->subtype_begin(), Ty->subtype_end(),
911 UpRefs[i].LastContainedTy) != Ty->subtype_end();
912
913#if 0
914 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
915 << UpRefs[i].LastContainedTy->getDescription() << ") = "
916 << (ContainsType ? "true" : "false")
917 << " level=" << UpRefs[i].NestingLevel << "\n";
918#endif
919 if (!ContainsType)
920 continue;
921
922 // Decrement level of upreference
923 unsigned Level = --UpRefs[i].NestingLevel;
924 UpRefs[i].LastContainedTy = Ty;
925
926 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
927 if (Level != 0)
928 continue;
929
930#if 0
931 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
932#endif
933 if (!TypeToResolve)
934 TypeToResolve = UpRefs[i].UpRefTy;
935 else
936 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
937 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
938 --i; // Do not skip the next element.
939 }
940
941 if (TypeToResolve)
942 TypeToResolve->refineAbstractTypeTo(Ty);
943
944 return Ty;
945}
946
947
948/// ParseTypeRec - The recursive function used to process the internal
949/// implementation details of types.
950bool LLParser::ParseTypeRec(PATypeHolder &Result) {
951 switch (Lex.getKind()) {
952 default:
953 return TokError("expected type");
954 case lltok::Type:
955 // TypeRec ::= 'float' | 'void' (etc)
956 Result = Lex.getTyVal();
957 Lex.Lex();
958 break;
959 case lltok::kw_opaque:
960 // TypeRec ::= 'opaque'
961 Result = OpaqueType::get();
962 Lex.Lex();
963 break;
964 case lltok::lbrace:
965 // TypeRec ::= '{' ... '}'
966 if (ParseStructType(Result, false))
967 return true;
968 break;
969 case lltok::lsquare:
970 // TypeRec ::= '[' ... ']'
971 Lex.Lex(); // eat the lsquare.
972 if (ParseArrayVectorType(Result, false))
973 return true;
974 break;
975 case lltok::less: // Either vector or packed struct.
976 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000977 Lex.Lex();
978 if (Lex.getKind() == lltok::lbrace) {
979 if (ParseStructType(Result, true) ||
980 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +0000981 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000982 } else if (ParseArrayVectorType(Result, true))
983 return true;
984 break;
985 case lltok::LocalVar:
986 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
987 // TypeRec ::= %foo
988 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
989 Result = T;
990 } else {
991 Result = OpaqueType::get();
992 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
993 std::make_pair(Result,
994 Lex.getLoc())));
995 M->addTypeName(Lex.getStrVal(), Result.get());
996 }
997 Lex.Lex();
998 break;
999
1000 case lltok::LocalVarID:
1001 // TypeRec ::= %4
1002 if (Lex.getUIntVal() < NumberedTypes.size())
1003 Result = NumberedTypes[Lex.getUIntVal()];
1004 else {
1005 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1006 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1007 if (I != ForwardRefTypeIDs.end())
1008 Result = I->second.first;
1009 else {
1010 Result = OpaqueType::get();
1011 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1012 std::make_pair(Result,
1013 Lex.getLoc())));
1014 }
1015 }
1016 Lex.Lex();
1017 break;
1018 case lltok::backslash: {
1019 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001020 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001021 unsigned Val;
1022 if (ParseUInt32(Val)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001023 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1024 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1025 Result = OT;
1026 break;
1027 }
1028 }
1029
1030 // Parse the type suffixes.
1031 while (1) {
1032 switch (Lex.getKind()) {
1033 // End of type.
1034 default: return false;
1035
1036 // TypeRec ::= TypeRec '*'
1037 case lltok::star:
1038 if (Result.get() == Type::LabelTy)
1039 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001040 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001041 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001042 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1043 Lex.Lex();
1044 break;
1045
1046 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1047 case lltok::kw_addrspace: {
1048 if (Result.get() == Type::LabelTy)
1049 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001050 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001051 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattnerdf986172009-01-02 07:01:27 +00001052 unsigned AddrSpace;
1053 if (ParseOptionalAddrSpace(AddrSpace) ||
1054 ParseToken(lltok::star, "expected '*' in address space"))
1055 return true;
1056
1057 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1058 break;
1059 }
1060
1061 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1062 case lltok::lparen:
1063 if (ParseFunctionType(Result))
1064 return true;
1065 break;
1066 }
1067 }
1068}
1069
1070/// ParseParameterList
1071/// ::= '(' ')'
1072/// ::= '(' Arg (',' Arg)* ')'
1073/// Arg
1074/// ::= Type OptionalAttributes Value OptionalAttributes
1075bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1076 PerFunctionState &PFS) {
1077 if (ParseToken(lltok::lparen, "expected '(' in call"))
1078 return true;
1079
1080 while (Lex.getKind() != lltok::rparen) {
1081 // If this isn't the first argument, we need a comma.
1082 if (!ArgList.empty() &&
1083 ParseToken(lltok::comma, "expected ',' in argument list"))
1084 return true;
1085
1086 // Parse the argument.
1087 LocTy ArgLoc;
1088 PATypeHolder ArgTy(Type::VoidTy);
1089 unsigned ArgAttrs1, ArgAttrs2;
1090 Value *V;
1091 if (ParseType(ArgTy, ArgLoc) ||
1092 ParseOptionalAttrs(ArgAttrs1, 0) ||
1093 ParseValue(ArgTy, V, PFS) ||
1094 // FIXME: Should not allow attributes after the argument, remove this in
1095 // LLVM 3.0.
1096 ParseOptionalAttrs(ArgAttrs2, 0))
1097 return true;
1098 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1099 }
1100
1101 Lex.Lex(); // Lex the ')'.
1102 return false;
1103}
1104
1105
1106
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001107/// ParseArgumentList - Parse the argument list for a function type or function
1108/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001109/// ::= '(' ArgTypeListI ')'
1110/// ArgTypeListI
1111/// ::= /*empty*/
1112/// ::= '...'
1113/// ::= ArgTypeList ',' '...'
1114/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001115///
Chris Lattnerdf986172009-01-02 07:01:27 +00001116bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001117 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001118 isVarArg = false;
1119 assert(Lex.getKind() == lltok::lparen);
1120 Lex.Lex(); // eat the (.
1121
1122 if (Lex.getKind() == lltok::rparen) {
1123 // empty
1124 } else if (Lex.getKind() == lltok::dotdotdot) {
1125 isVarArg = true;
1126 Lex.Lex();
1127 } else {
1128 LocTy TypeLoc = Lex.getLoc();
1129 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001130 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001131 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001132
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001133 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1134 // types (such as a function returning a pointer to itself). If parsing a
1135 // function prototype, we require fully resolved types.
1136 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001137 ParseOptionalAttrs(Attrs, 0)) return true;
1138
Chris Lattnera9a9e072009-03-09 04:49:14 +00001139 if (ArgTy == Type::VoidTy)
1140 return Error(TypeLoc, "argument can not have void type");
1141
Chris Lattnerdf986172009-01-02 07:01:27 +00001142 if (Lex.getKind() == lltok::LocalVar ||
1143 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1144 Name = Lex.getStrVal();
1145 Lex.Lex();
1146 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001147
1148 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1149 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001150
1151 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1152
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001153 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001155 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001157 break;
1158 }
1159
1160 // Otherwise must be an argument type.
1161 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001162 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001163 ParseOptionalAttrs(Attrs, 0)) return true;
1164
Chris Lattnera9a9e072009-03-09 04:49:14 +00001165 if (ArgTy == Type::VoidTy)
1166 return Error(TypeLoc, "argument can not have void type");
1167
Chris Lattnerdf986172009-01-02 07:01:27 +00001168 if (Lex.getKind() == lltok::LocalVar ||
1169 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1170 Name = Lex.getStrVal();
1171 Lex.Lex();
1172 } else {
1173 Name = "";
1174 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001175
1176 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1177 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001178
1179 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1180 }
1181 }
1182
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001183 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001184}
1185
1186/// ParseFunctionType
1187/// ::= Type ArgumentList OptionalAttrs
1188bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1189 assert(Lex.getKind() == lltok::lparen);
1190
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001191 if (!FunctionType::isValidReturnType(Result))
1192 return TokError("invalid function return type");
1193
Chris Lattnerdf986172009-01-02 07:01:27 +00001194 std::vector<ArgInfo> ArgList;
1195 bool isVarArg;
1196 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001197 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001198 // FIXME: Allow, but ignore attributes on function types!
1199 // FIXME: Remove in LLVM 3.0
1200 ParseOptionalAttrs(Attrs, 2))
1201 return true;
1202
1203 // Reject names on the arguments lists.
1204 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1205 if (!ArgList[i].Name.empty())
1206 return Error(ArgList[i].Loc, "argument name invalid in function type");
1207 if (!ArgList[i].Attrs != 0) {
1208 // Allow but ignore attributes on function types; this permits
1209 // auto-upgrade.
1210 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1211 }
1212 }
1213
1214 std::vector<const Type*> ArgListTy;
1215 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1216 ArgListTy.push_back(ArgList[i].Type);
1217
1218 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1219 return false;
1220}
1221
1222/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1223/// TypeRec
1224/// ::= '{' '}'
1225/// ::= '{' TypeRec (',' TypeRec)* '}'
1226/// ::= '<' '{' '}' '>'
1227/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1228bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1229 assert(Lex.getKind() == lltok::lbrace);
1230 Lex.Lex(); // Consume the '{'
1231
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001232 if (EatIfPresent(lltok::rbrace)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001233 Result = StructType::get(std::vector<const Type*>(), Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 return false;
1235 }
1236
1237 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001238 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 if (ParseTypeRec(Result)) return true;
1240 ParamsList.push_back(Result);
1241
Chris Lattnera9a9e072009-03-09 04:49:14 +00001242 if (Result == Type::VoidTy)
1243 return Error(EltTyLoc, "struct element can not have void type");
1244
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001245 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001246 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001248
1249 if (Result == Type::VoidTy)
1250 return Error(EltTyLoc, "struct element can not have void type");
1251
Chris Lattnerdf986172009-01-02 07:01:27 +00001252 ParamsList.push_back(Result);
1253 }
1254
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001255 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1256 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001257
1258 std::vector<const Type*> ParamsListTy;
1259 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1260 ParamsListTy.push_back(ParamsList[i].get());
1261 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1262 return false;
1263}
1264
1265/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1266/// token has already been consumed.
1267/// TypeRec
1268/// ::= '[' APSINTVAL 'x' Types ']'
1269/// ::= '<' APSINTVAL 'x' Types '>'
1270bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1271 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1272 Lex.getAPSIntVal().getBitWidth() > 64)
1273 return TokError("expected number in address space");
1274
1275 LocTy SizeLoc = Lex.getLoc();
1276 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001277 Lex.Lex();
1278
1279 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1280 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001281
1282 LocTy TypeLoc = Lex.getLoc();
1283 PATypeHolder EltTy(Type::VoidTy);
1284 if (ParseTypeRec(EltTy)) return true;
1285
Chris Lattnera9a9e072009-03-09 04:49:14 +00001286 if (EltTy == Type::VoidTy)
1287 return Error(TypeLoc, "array and vector element type cannot be void");
1288
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001289 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1290 "expected end of sequential type"))
1291 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001292
1293 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001294 if (Size == 0)
1295 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 if ((unsigned)Size != Size)
1297 return Error(SizeLoc, "size too large for vector");
1298 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1299 return Error(TypeLoc, "vector element type must be fp or integer");
1300 Result = VectorType::get(EltTy, unsigned(Size));
1301 } else {
1302 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1303 return Error(TypeLoc, "invalid array element type");
1304 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1305 }
1306 return false;
1307}
1308
1309//===----------------------------------------------------------------------===//
1310// Function Semantic Analysis.
1311//===----------------------------------------------------------------------===//
1312
1313LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1314 : P(p), F(f) {
1315
1316 // Insert unnamed arguments into the NumberedVals list.
1317 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1318 AI != E; ++AI)
1319 if (!AI->hasName())
1320 NumberedVals.push_back(AI);
1321}
1322
1323LLParser::PerFunctionState::~PerFunctionState() {
1324 // If there were any forward referenced non-basicblock values, delete them.
1325 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1326 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1327 if (!isa<BasicBlock>(I->second.first)) {
1328 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1329 ->getType()));
1330 delete I->second.first;
1331 I->second.first = 0;
1332 }
1333
1334 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1335 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1336 if (!isa<BasicBlock>(I->second.first)) {
1337 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1338 ->getType()));
1339 delete I->second.first;
1340 I->second.first = 0;
1341 }
1342}
1343
1344bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1345 if (!ForwardRefVals.empty())
1346 return P.Error(ForwardRefVals.begin()->second.second,
1347 "use of undefined value '%" + ForwardRefVals.begin()->first +
1348 "'");
1349 if (!ForwardRefValIDs.empty())
1350 return P.Error(ForwardRefValIDs.begin()->second.second,
1351 "use of undefined value '%" +
1352 utostr(ForwardRefValIDs.begin()->first) + "'");
1353 return false;
1354}
1355
1356
1357/// GetVal - Get a value with the specified name or ID, creating a
1358/// forward reference record if needed. This can return null if the value
1359/// exists but does not have the right type.
1360Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1361 const Type *Ty, LocTy Loc) {
1362 // Look this name up in the normal function symbol table.
1363 Value *Val = F.getValueSymbolTable().lookup(Name);
1364
1365 // If this is a forward reference for the value, see if we already created a
1366 // forward ref record.
1367 if (Val == 0) {
1368 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1369 I = ForwardRefVals.find(Name);
1370 if (I != ForwardRefVals.end())
1371 Val = I->second.first;
1372 }
1373
1374 // If we have the value in the symbol table or fwd-ref table, return it.
1375 if (Val) {
1376 if (Val->getType() == Ty) return Val;
1377 if (Ty == Type::LabelTy)
1378 P.Error(Loc, "'%" + Name + "' is not a basic block");
1379 else
1380 P.Error(Loc, "'%" + Name + "' defined with type '" +
1381 Val->getType()->getDescription() + "'");
1382 return 0;
1383 }
1384
1385 // Don't make placeholders with invalid type.
1386 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1387 P.Error(Loc, "invalid use of a non-first-class type");
1388 return 0;
1389 }
1390
1391 // Otherwise, create a new forward reference for this value and remember it.
1392 Value *FwdVal;
1393 if (Ty == Type::LabelTy)
1394 FwdVal = BasicBlock::Create(Name, &F);
1395 else
1396 FwdVal = new Argument(Ty, Name);
1397
1398 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1399 return FwdVal;
1400}
1401
1402Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1403 LocTy Loc) {
1404 // Look this name up in the normal function symbol table.
1405 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1406
1407 // If this is a forward reference for the value, see if we already created a
1408 // forward ref record.
1409 if (Val == 0) {
1410 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1411 I = ForwardRefValIDs.find(ID);
1412 if (I != ForwardRefValIDs.end())
1413 Val = I->second.first;
1414 }
1415
1416 // If we have the value in the symbol table or fwd-ref table, return it.
1417 if (Val) {
1418 if (Val->getType() == Ty) return Val;
1419 if (Ty == Type::LabelTy)
1420 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1421 else
1422 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1423 Val->getType()->getDescription() + "'");
1424 return 0;
1425 }
1426
1427 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1428 P.Error(Loc, "invalid use of a non-first-class type");
1429 return 0;
1430 }
1431
1432 // Otherwise, create a new forward reference for this value and remember it.
1433 Value *FwdVal;
1434 if (Ty == Type::LabelTy)
1435 FwdVal = BasicBlock::Create("", &F);
1436 else
1437 FwdVal = new Argument(Ty);
1438
1439 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1440 return FwdVal;
1441}
1442
1443/// SetInstName - After an instruction is parsed and inserted into its
1444/// basic block, this installs its name.
1445bool LLParser::PerFunctionState::SetInstName(int NameID,
1446 const std::string &NameStr,
1447 LocTy NameLoc, Instruction *Inst) {
1448 // If this instruction has void type, it cannot have a name or ID specified.
1449 if (Inst->getType() == Type::VoidTy) {
1450 if (NameID != -1 || !NameStr.empty())
1451 return P.Error(NameLoc, "instructions returning void cannot have a name");
1452 return false;
1453 }
1454
1455 // If this was a numbered instruction, verify that the instruction is the
1456 // expected value and resolve any forward references.
1457 if (NameStr.empty()) {
1458 // If neither a name nor an ID was specified, just use the next ID.
1459 if (NameID == -1)
1460 NameID = NumberedVals.size();
1461
1462 if (unsigned(NameID) != NumberedVals.size())
1463 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1464 utostr(NumberedVals.size()) + "'");
1465
1466 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1467 ForwardRefValIDs.find(NameID);
1468 if (FI != ForwardRefValIDs.end()) {
1469 if (FI->second.first->getType() != Inst->getType())
1470 return P.Error(NameLoc, "instruction forward referenced with type '" +
1471 FI->second.first->getType()->getDescription() + "'");
1472 FI->second.first->replaceAllUsesWith(Inst);
1473 ForwardRefValIDs.erase(FI);
1474 }
1475
1476 NumberedVals.push_back(Inst);
1477 return false;
1478 }
1479
1480 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1481 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1482 FI = ForwardRefVals.find(NameStr);
1483 if (FI != ForwardRefVals.end()) {
1484 if (FI->second.first->getType() != Inst->getType())
1485 return P.Error(NameLoc, "instruction forward referenced with type '" +
1486 FI->second.first->getType()->getDescription() + "'");
1487 FI->second.first->replaceAllUsesWith(Inst);
1488 ForwardRefVals.erase(FI);
1489 }
1490
1491 // Set the name on the instruction.
1492 Inst->setName(NameStr);
1493
1494 if (Inst->getNameStr() != NameStr)
1495 return P.Error(NameLoc, "multiple definition of local value named '" +
1496 NameStr + "'");
1497 return false;
1498}
1499
1500/// GetBB - Get a basic block with the specified name or ID, creating a
1501/// forward reference record if needed.
1502BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1503 LocTy Loc) {
1504 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1505}
1506
1507BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1508 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1509}
1510
1511/// DefineBB - Define the specified basic block, which is either named or
1512/// unnamed. If there is an error, this returns null otherwise it returns
1513/// the block being defined.
1514BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1515 LocTy Loc) {
1516 BasicBlock *BB;
1517 if (Name.empty())
1518 BB = GetBB(NumberedVals.size(), Loc);
1519 else
1520 BB = GetBB(Name, Loc);
1521 if (BB == 0) return 0; // Already diagnosed error.
1522
1523 // Move the block to the end of the function. Forward ref'd blocks are
1524 // inserted wherever they happen to be referenced.
1525 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1526
1527 // Remove the block from forward ref sets.
1528 if (Name.empty()) {
1529 ForwardRefValIDs.erase(NumberedVals.size());
1530 NumberedVals.push_back(BB);
1531 } else {
1532 // BB forward references are already in the function symbol table.
1533 ForwardRefVals.erase(Name);
1534 }
1535
1536 return BB;
1537}
1538
1539//===----------------------------------------------------------------------===//
1540// Constants.
1541//===----------------------------------------------------------------------===//
1542
1543/// ParseValID - Parse an abstract value that doesn't necessarily have a
1544/// type implied. For example, if we parse "4" we don't know what integer type
1545/// it has. The value will later be combined with its type and checked for
1546/// sanity.
1547bool LLParser::ParseValID(ValID &ID) {
1548 ID.Loc = Lex.getLoc();
1549 switch (Lex.getKind()) {
1550 default: return TokError("expected value token");
1551 case lltok::GlobalID: // @42
1552 ID.UIntVal = Lex.getUIntVal();
1553 ID.Kind = ValID::t_GlobalID;
1554 break;
1555 case lltok::GlobalVar: // @foo
1556 ID.StrVal = Lex.getStrVal();
1557 ID.Kind = ValID::t_GlobalName;
1558 break;
1559 case lltok::LocalVarID: // %42
1560 ID.UIntVal = Lex.getUIntVal();
1561 ID.Kind = ValID::t_LocalID;
1562 break;
1563 case lltok::LocalVar: // %foo
1564 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1565 ID.StrVal = Lex.getStrVal();
1566 ID.Kind = ValID::t_LocalName;
1567 break;
1568 case lltok::APSInt:
1569 ID.APSIntVal = Lex.getAPSIntVal();
1570 ID.Kind = ValID::t_APSInt;
1571 break;
1572 case lltok::APFloat:
1573 ID.APFloatVal = Lex.getAPFloatVal();
1574 ID.Kind = ValID::t_APFloat;
1575 break;
1576 case lltok::kw_true:
1577 ID.ConstantVal = ConstantInt::getTrue();
1578 ID.Kind = ValID::t_Constant;
1579 break;
1580 case lltok::kw_false:
1581 ID.ConstantVal = ConstantInt::getFalse();
1582 ID.Kind = ValID::t_Constant;
1583 break;
1584 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1585 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1586 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1587
1588 case lltok::lbrace: {
1589 // ValID ::= '{' ConstVector '}'
1590 Lex.Lex();
1591 SmallVector<Constant*, 16> Elts;
1592 if (ParseGlobalValueVector(Elts) ||
1593 ParseToken(lltok::rbrace, "expected end of struct constant"))
1594 return true;
1595
1596 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1597 ID.Kind = ValID::t_Constant;
1598 return false;
1599 }
1600 case lltok::less: {
1601 // ValID ::= '<' ConstVector '>' --> Vector.
1602 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1603 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001604 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001605
1606 SmallVector<Constant*, 16> Elts;
1607 LocTy FirstEltLoc = Lex.getLoc();
1608 if (ParseGlobalValueVector(Elts) ||
1609 (isPackedStruct &&
1610 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1611 ParseToken(lltok::greater, "expected end of constant"))
1612 return true;
1613
1614 if (isPackedStruct) {
1615 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1616 ID.Kind = ValID::t_Constant;
1617 return false;
1618 }
1619
1620 if (Elts.empty())
1621 return Error(ID.Loc, "constant vector must not be empty");
1622
1623 if (!Elts[0]->getType()->isInteger() &&
1624 !Elts[0]->getType()->isFloatingPoint())
1625 return Error(FirstEltLoc,
1626 "vector elements must have integer or floating point type");
1627
1628 // Verify that all the vector elements have the same type.
1629 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1630 if (Elts[i]->getType() != Elts[0]->getType())
1631 return Error(FirstEltLoc,
1632 "vector element #" + utostr(i) +
1633 " is not of type '" + Elts[0]->getType()->getDescription());
1634
1635 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1636 ID.Kind = ValID::t_Constant;
1637 return false;
1638 }
1639 case lltok::lsquare: { // Array Constant
1640 Lex.Lex();
1641 SmallVector<Constant*, 16> Elts;
1642 LocTy FirstEltLoc = Lex.getLoc();
1643 if (ParseGlobalValueVector(Elts) ||
1644 ParseToken(lltok::rsquare, "expected end of array constant"))
1645 return true;
1646
1647 // Handle empty element.
1648 if (Elts.empty()) {
1649 // Use undef instead of an array because it's inconvenient to determine
1650 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001651 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 return false;
1653 }
1654
1655 if (!Elts[0]->getType()->isFirstClassType())
1656 return Error(FirstEltLoc, "invalid array element type: " +
1657 Elts[0]->getType()->getDescription());
1658
1659 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1660
1661 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001662 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 if (Elts[i]->getType() != Elts[0]->getType())
1664 return Error(FirstEltLoc,
1665 "array element #" + utostr(i) +
1666 " is not of type '" +Elts[0]->getType()->getDescription());
1667 }
1668
1669 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1670 ID.Kind = ValID::t_Constant;
1671 return false;
1672 }
1673 case lltok::kw_c: // c "foo"
1674 Lex.Lex();
1675 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1676 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1677 ID.Kind = ValID::t_Constant;
1678 return false;
1679
1680 case lltok::kw_asm: {
1681 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1682 bool HasSideEffect;
1683 Lex.Lex();
1684 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001685 ParseStringConstant(ID.StrVal) ||
1686 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001687 ParseToken(lltok::StringConstant, "expected constraint string"))
1688 return true;
1689 ID.StrVal2 = Lex.getStrVal();
1690 ID.UIntVal = HasSideEffect;
1691 ID.Kind = ValID::t_InlineAsm;
1692 return false;
1693 }
1694
1695 case lltok::kw_trunc:
1696 case lltok::kw_zext:
1697 case lltok::kw_sext:
1698 case lltok::kw_fptrunc:
1699 case lltok::kw_fpext:
1700 case lltok::kw_bitcast:
1701 case lltok::kw_uitofp:
1702 case lltok::kw_sitofp:
1703 case lltok::kw_fptoui:
1704 case lltok::kw_fptosi:
1705 case lltok::kw_inttoptr:
1706 case lltok::kw_ptrtoint: {
1707 unsigned Opc = Lex.getUIntVal();
1708 PATypeHolder DestTy(Type::VoidTy);
1709 Constant *SrcVal;
1710 Lex.Lex();
1711 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1712 ParseGlobalTypeAndValue(SrcVal) ||
1713 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1714 ParseType(DestTy) ||
1715 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1716 return true;
1717 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1718 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1719 SrcVal->getType()->getDescription() + "' to '" +
1720 DestTy->getDescription() + "'");
1721 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1722 DestTy);
1723 ID.Kind = ValID::t_Constant;
1724 return false;
1725 }
1726 case lltok::kw_extractvalue: {
1727 Lex.Lex();
1728 Constant *Val;
1729 SmallVector<unsigned, 4> Indices;
1730 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1731 ParseGlobalTypeAndValue(Val) ||
1732 ParseIndexList(Indices) ||
1733 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1734 return true;
1735 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1736 return Error(ID.Loc, "extractvalue operand must be array or struct");
1737 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1738 Indices.end()))
1739 return Error(ID.Loc, "invalid indices for extractvalue");
1740 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1741 &Indices[0], Indices.size());
1742 ID.Kind = ValID::t_Constant;
1743 return false;
1744 }
1745 case lltok::kw_insertvalue: {
1746 Lex.Lex();
1747 Constant *Val0, *Val1;
1748 SmallVector<unsigned, 4> Indices;
1749 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1750 ParseGlobalTypeAndValue(Val0) ||
1751 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1752 ParseGlobalTypeAndValue(Val1) ||
1753 ParseIndexList(Indices) ||
1754 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1755 return true;
1756 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1757 return Error(ID.Loc, "extractvalue operand must be array or struct");
1758 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1759 Indices.end()))
1760 return Error(ID.Loc, "invalid indices for insertvalue");
1761 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1762 &Indices[0], Indices.size());
1763 ID.Kind = ValID::t_Constant;
1764 return false;
1765 }
1766 case lltok::kw_icmp:
1767 case lltok::kw_fcmp:
1768 case lltok::kw_vicmp:
1769 case lltok::kw_vfcmp: {
1770 unsigned PredVal, Opc = Lex.getUIntVal();
1771 Constant *Val0, *Val1;
1772 Lex.Lex();
1773 if (ParseCmpPredicate(PredVal, Opc) ||
1774 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1775 ParseGlobalTypeAndValue(Val0) ||
1776 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1777 ParseGlobalTypeAndValue(Val1) ||
1778 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1779 return true;
1780
1781 if (Val0->getType() != Val1->getType())
1782 return Error(ID.Loc, "compare operands must have the same type");
1783
1784 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1785
1786 if (Opc == Instruction::FCmp) {
1787 if (!Val0->getType()->isFPOrFPVector())
1788 return Error(ID.Loc, "fcmp requires floating point operands");
1789 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1790 } else if (Opc == Instruction::ICmp) {
1791 if (!Val0->getType()->isIntOrIntVector() &&
1792 !isa<PointerType>(Val0->getType()))
1793 return Error(ID.Loc, "icmp requires pointer or integer operands");
1794 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1795 } else if (Opc == Instruction::VFCmp) {
1796 // FIXME: REMOVE VFCMP Support
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001797 if (!Val0->getType()->isFPOrFPVector() ||
1798 !isa<VectorType>(Val0->getType()))
1799 return Error(ID.Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1801 } else if (Opc == Instruction::VICmp) {
Chris Lattnerd0f9c732009-01-05 08:26:05 +00001802 // FIXME: REMOVE VICMP Support
1803 if (!Val0->getType()->isIntOrIntVector() ||
1804 !isa<VectorType>(Val0->getType()))
1805 return Error(ID.Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1807 }
1808 ID.Kind = ValID::t_Constant;
1809 return false;
1810 }
1811
1812 // Binary Operators.
1813 case lltok::kw_add:
1814 case lltok::kw_sub:
1815 case lltok::kw_mul:
1816 case lltok::kw_udiv:
1817 case lltok::kw_sdiv:
1818 case lltok::kw_fdiv:
1819 case lltok::kw_urem:
1820 case lltok::kw_srem:
1821 case lltok::kw_frem: {
1822 unsigned Opc = Lex.getUIntVal();
1823 Constant *Val0, *Val1;
1824 Lex.Lex();
1825 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1826 ParseGlobalTypeAndValue(Val0) ||
1827 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1828 ParseGlobalTypeAndValue(Val1) ||
1829 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1830 return true;
1831 if (Val0->getType() != Val1->getType())
1832 return Error(ID.Loc, "operands of constexpr must have same type");
1833 if (!Val0->getType()->isIntOrIntVector() &&
1834 !Val0->getType()->isFPOrFPVector())
1835 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1836 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1837 ID.Kind = ValID::t_Constant;
1838 return false;
1839 }
1840
1841 // Logical Operations
1842 case lltok::kw_shl:
1843 case lltok::kw_lshr:
1844 case lltok::kw_ashr:
1845 case lltok::kw_and:
1846 case lltok::kw_or:
1847 case lltok::kw_xor: {
1848 unsigned Opc = Lex.getUIntVal();
1849 Constant *Val0, *Val1;
1850 Lex.Lex();
1851 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1852 ParseGlobalTypeAndValue(Val0) ||
1853 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1854 ParseGlobalTypeAndValue(Val1) ||
1855 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1856 return true;
1857 if (Val0->getType() != Val1->getType())
1858 return Error(ID.Loc, "operands of constexpr must have same type");
1859 if (!Val0->getType()->isIntOrIntVector())
1860 return Error(ID.Loc,
1861 "constexpr requires integer or integer vector operands");
1862 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1863 ID.Kind = ValID::t_Constant;
1864 return false;
1865 }
1866
1867 case lltok::kw_getelementptr:
1868 case lltok::kw_shufflevector:
1869 case lltok::kw_insertelement:
1870 case lltok::kw_extractelement:
1871 case lltok::kw_select: {
1872 unsigned Opc = Lex.getUIntVal();
1873 SmallVector<Constant*, 16> Elts;
1874 Lex.Lex();
1875 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1876 ParseGlobalValueVector(Elts) ||
1877 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1878 return true;
1879
1880 if (Opc == Instruction::GetElementPtr) {
1881 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1882 return Error(ID.Loc, "getelementptr requires pointer operand");
1883
1884 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1885 (Value**)&Elts[1], Elts.size()-1))
1886 return Error(ID.Loc, "invalid indices for getelementptr");
1887 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1888 &Elts[1], Elts.size()-1);
1889 } else if (Opc == Instruction::Select) {
1890 if (Elts.size() != 3)
1891 return Error(ID.Loc, "expected three operands to select");
1892 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1893 Elts[2]))
1894 return Error(ID.Loc, Reason);
1895 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1896 } else if (Opc == Instruction::ShuffleVector) {
1897 if (Elts.size() != 3)
1898 return Error(ID.Loc, "expected three operands to shufflevector");
1899 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1900 return Error(ID.Loc, "invalid operands to shufflevector");
1901 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1902 } else if (Opc == Instruction::ExtractElement) {
1903 if (Elts.size() != 2)
1904 return Error(ID.Loc, "expected two operands to extractelement");
1905 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1906 return Error(ID.Loc, "invalid extractelement operands");
1907 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1908 } else {
1909 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1910 if (Elts.size() != 3)
1911 return Error(ID.Loc, "expected three operands to insertelement");
1912 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1913 return Error(ID.Loc, "invalid insertelement operands");
1914 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1915 }
1916
1917 ID.Kind = ValID::t_Constant;
1918 return false;
1919 }
1920 }
1921
1922 Lex.Lex();
1923 return false;
1924}
1925
1926/// ParseGlobalValue - Parse a global value with the specified type.
1927bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1928 V = 0;
1929 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001930 return ParseValID(ID) ||
1931 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00001932}
1933
1934/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1935/// constant.
1936bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1937 Constant *&V) {
1938 if (isa<FunctionType>(Ty))
1939 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1940
1941 switch (ID.Kind) {
1942 default: assert(0 && "Unknown ValID!");
1943 case ValID::t_LocalID:
1944 case ValID::t_LocalName:
1945 return Error(ID.Loc, "invalid use of function-local name");
1946 case ValID::t_InlineAsm:
1947 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1948 case ValID::t_GlobalName:
1949 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1950 return V == 0;
1951 case ValID::t_GlobalID:
1952 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1953 return V == 0;
1954 case ValID::t_APSInt:
1955 if (!isa<IntegerType>(Ty))
1956 return Error(ID.Loc, "integer constant must have integer type");
1957 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1958 V = ConstantInt::get(ID.APSIntVal);
1959 return false;
1960 case ValID::t_APFloat:
1961 if (!Ty->isFloatingPoint() ||
1962 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1963 return Error(ID.Loc, "floating point constant invalid for type");
1964
1965 // The lexer has no type info, so builds all float and double FP constants
1966 // as double. Fix this here. Long double does not need this.
1967 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1968 Ty == Type::FloatTy) {
1969 bool Ignored;
1970 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1971 &Ignored);
1972 }
1973 V = ConstantFP::get(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00001974
1975 if (V->getType() != Ty)
1976 return Error(ID.Loc, "floating point constant does not have type '" +
1977 Ty->getDescription() + "'");
1978
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 return false;
1980 case ValID::t_Null:
1981 if (!isa<PointerType>(Ty))
1982 return Error(ID.Loc, "null must be a pointer type");
1983 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1984 return false;
1985 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001986 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00001987 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1988 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001989 return Error(ID.Loc, "invalid type for undef constant");
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 V = UndefValue::get(Ty);
1991 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00001992 case ValID::t_EmptyArray:
1993 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1994 return Error(ID.Loc, "invalid empty array initializer");
1995 V = UndefValue::get(Ty);
1996 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001997 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00001998 // FIXME: LabelTy should not be a first-class type.
1999 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002000 return Error(ID.Loc, "invalid type for null constant");
2001 V = Constant::getNullValue(Ty);
2002 return false;
2003 case ValID::t_Constant:
2004 if (ID.ConstantVal->getType() != Ty)
2005 return Error(ID.Loc, "constant expression type mismatch");
2006 V = ID.ConstantVal;
2007 return false;
2008 }
2009}
2010
2011bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2012 PATypeHolder Type(Type::VoidTy);
2013 return ParseType(Type) ||
2014 ParseGlobalValue(Type, V);
2015}
2016
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002017/// ParseGlobalValueVector
2018/// ::= /*empty*/
2019/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002020bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2021 // Empty list.
2022 if (Lex.getKind() == lltok::rbrace ||
2023 Lex.getKind() == lltok::rsquare ||
2024 Lex.getKind() == lltok::greater ||
2025 Lex.getKind() == lltok::rparen)
2026 return false;
2027
2028 Constant *C;
2029 if (ParseGlobalTypeAndValue(C)) return true;
2030 Elts.push_back(C);
2031
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002032 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 if (ParseGlobalTypeAndValue(C)) return true;
2034 Elts.push_back(C);
2035 }
2036
2037 return false;
2038}
2039
2040
2041//===----------------------------------------------------------------------===//
2042// Function Parsing.
2043//===----------------------------------------------------------------------===//
2044
2045bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2046 PerFunctionState &PFS) {
2047 if (ID.Kind == ValID::t_LocalID)
2048 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2049 else if (ID.Kind == ValID::t_LocalName)
2050 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002051 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2053 const FunctionType *FTy =
2054 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2055 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2056 return Error(ID.Loc, "invalid type for inline asm constraint string");
2057 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2058 return false;
2059 } else {
2060 Constant *C;
2061 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2062 V = C;
2063 return false;
2064 }
2065
2066 return V == 0;
2067}
2068
2069bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2070 V = 0;
2071 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002072 return ParseValID(ID) ||
2073 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002074}
2075
2076bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2077 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002078 return ParseType(T) ||
2079 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002080}
2081
2082/// FunctionHeader
2083/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2084/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2085/// OptionalAlign OptGC
2086bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2087 // Parse the linkage.
2088 LocTy LinkageLoc = Lex.getLoc();
2089 unsigned Linkage;
2090
2091 unsigned Visibility, CC, RetAttrs;
2092 PATypeHolder RetType(Type::VoidTy);
2093 LocTy RetTypeLoc = Lex.getLoc();
2094 if (ParseOptionalLinkage(Linkage) ||
2095 ParseOptionalVisibility(Visibility) ||
2096 ParseOptionalCallingConv(CC) ||
2097 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002098 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 return true;
2100
2101 // Verify that the linkage is ok.
2102 switch ((GlobalValue::LinkageTypes)Linkage) {
2103 case GlobalValue::ExternalLinkage:
2104 break; // always ok.
2105 case GlobalValue::DLLImportLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002106 case GlobalValue::ExternalWeakAnyLinkage:
2107 case GlobalValue::ExternalWeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 if (isDefine)
2109 return Error(LinkageLoc, "invalid linkage for function definition");
2110 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002111 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002112 case GlobalValue::InternalLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002113 case GlobalValue::LinkOnceAnyLinkage:
2114 case GlobalValue::LinkOnceODRLinkage:
2115 case GlobalValue::WeakAnyLinkage:
2116 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 case GlobalValue::DLLExportLinkage:
2118 if (!isDefine)
2119 return Error(LinkageLoc, "invalid linkage for function declaration");
2120 break;
2121 case GlobalValue::AppendingLinkage:
2122 case GlobalValue::GhostLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002123 case GlobalValue::CommonAnyLinkage:
2124 case GlobalValue::CommonODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002125 return Error(LinkageLoc, "invalid function linkage type");
2126 }
2127
Chris Lattner99bb3152009-01-05 08:00:30 +00002128 if (!FunctionType::isValidReturnType(RetType) ||
2129 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 return Error(RetTypeLoc, "invalid function return type");
2131
Chris Lattnerdf986172009-01-02 07:01:27 +00002132 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002133
2134 std::string FunctionName;
2135 if (Lex.getKind() == lltok::GlobalVar) {
2136 FunctionName = Lex.getStrVal();
2137 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2138 unsigned NameID = Lex.getUIntVal();
2139
2140 if (NameID != NumberedVals.size())
2141 return TokError("function expected to be numbered '%" +
2142 utostr(NumberedVals.size()) + "'");
2143 } else {
2144 return TokError("expected function name");
2145 }
2146
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002147 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002148
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002149 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 return TokError("expected '(' in function argument list");
2151
2152 std::vector<ArgInfo> ArgList;
2153 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002155 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002157 std::string GC;
2158
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002159 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002160 ParseOptionalAttrs(FuncAttrs, 2) ||
2161 (EatIfPresent(lltok::kw_section) &&
2162 ParseStringConstant(Section)) ||
2163 ParseOptionalAlignment(Alignment) ||
2164 (EatIfPresent(lltok::kw_gc) &&
2165 ParseStringConstant(GC)))
2166 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002167
2168 // If the alignment was parsed as an attribute, move to the alignment field.
2169 if (FuncAttrs & Attribute::Alignment) {
2170 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2171 FuncAttrs &= ~Attribute::Alignment;
2172 }
2173
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 // Okay, if we got here, the function is syntactically valid. Convert types
2175 // and do semantic checks.
2176 std::vector<const Type*> ParamTypeList;
2177 SmallVector<AttributeWithIndex, 8> Attrs;
2178 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2179 // attributes.
2180 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2181 if (FuncAttrs & ObsoleteFuncAttrs) {
2182 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2183 FuncAttrs &= ~ObsoleteFuncAttrs;
2184 }
2185
2186 if (RetAttrs != Attribute::None)
2187 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2188
2189 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2190 ParamTypeList.push_back(ArgList[i].Type);
2191 if (ArgList[i].Attrs != Attribute::None)
2192 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2193 }
2194
2195 if (FuncAttrs != Attribute::None)
2196 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2197
2198 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2199
Chris Lattnera9a9e072009-03-09 04:49:14 +00002200 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2201 RetType != Type::VoidTy)
2202 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2203
Chris Lattnerdf986172009-01-02 07:01:27 +00002204 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2205 const PointerType *PFT = PointerType::getUnqual(FT);
2206
2207 Fn = 0;
2208 if (!FunctionName.empty()) {
2209 // If this was a definition of a forward reference, remove the definition
2210 // from the forward reference table and fill in the forward ref.
2211 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2212 ForwardRefVals.find(FunctionName);
2213 if (FRVI != ForwardRefVals.end()) {
2214 Fn = M->getFunction(FunctionName);
2215 ForwardRefVals.erase(FRVI);
2216 } else if ((Fn = M->getFunction(FunctionName))) {
2217 // If this function already exists in the symbol table, then it is
2218 // multiply defined. We accept a few cases for old backwards compat.
2219 // FIXME: Remove this stuff for LLVM 3.0.
2220 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2221 (!Fn->isDeclaration() && isDefine)) {
2222 // If the redefinition has different type or different attributes,
2223 // reject it. If both have bodies, reject it.
2224 return Error(NameLoc, "invalid redefinition of function '" +
2225 FunctionName + "'");
2226 } else if (Fn->isDeclaration()) {
2227 // Make sure to strip off any argument names so we can't get conflicts.
2228 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2229 AI != AE; ++AI)
2230 AI->setName("");
2231 }
2232 }
2233
2234 } else if (FunctionName.empty()) {
2235 // If this is a definition of a forward referenced function, make sure the
2236 // types agree.
2237 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2238 = ForwardRefValIDs.find(NumberedVals.size());
2239 if (I != ForwardRefValIDs.end()) {
2240 Fn = cast<Function>(I->second.first);
2241 if (Fn->getType() != PFT)
2242 return Error(NameLoc, "type of definition and forward reference of '@" +
2243 utostr(NumberedVals.size()) +"' disagree");
2244 ForwardRefValIDs.erase(I);
2245 }
2246 }
2247
2248 if (Fn == 0)
2249 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2250 else // Move the forward-reference to the correct spot in the module.
2251 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2252
2253 if (FunctionName.empty())
2254 NumberedVals.push_back(Fn);
2255
2256 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2257 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2258 Fn->setCallingConv(CC);
2259 Fn->setAttributes(PAL);
2260 Fn->setAlignment(Alignment);
2261 Fn->setSection(Section);
2262 if (!GC.empty()) Fn->setGC(GC.c_str());
2263
2264 // Add all of the arguments we parsed to the function.
2265 Function::arg_iterator ArgIt = Fn->arg_begin();
2266 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2267 // If the argument has a name, insert it into the argument symbol table.
2268 if (ArgList[i].Name.empty()) continue;
2269
2270 // Set the name, if it conflicted, it will be auto-renamed.
2271 ArgIt->setName(ArgList[i].Name);
2272
2273 if (ArgIt->getNameStr() != ArgList[i].Name)
2274 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2275 ArgList[i].Name + "'");
2276 }
2277
2278 return false;
2279}
2280
2281
2282/// ParseFunctionBody
2283/// ::= '{' BasicBlock+ '}'
2284/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2285///
2286bool LLParser::ParseFunctionBody(Function &Fn) {
2287 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2288 return TokError("expected '{' in function body");
2289 Lex.Lex(); // eat the {.
2290
2291 PerFunctionState PFS(*this, Fn);
2292
2293 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2294 if (ParseBasicBlock(PFS)) return true;
2295
2296 // Eat the }.
2297 Lex.Lex();
2298
2299 // Verify function is ok.
2300 return PFS.VerifyFunctionComplete();
2301}
2302
2303/// ParseBasicBlock
2304/// ::= LabelStr? Instruction*
2305bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2306 // If this basic block starts out with a name, remember it.
2307 std::string Name;
2308 LocTy NameLoc = Lex.getLoc();
2309 if (Lex.getKind() == lltok::LabelStr) {
2310 Name = Lex.getStrVal();
2311 Lex.Lex();
2312 }
2313
2314 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2315 if (BB == 0) return true;
2316
2317 std::string NameStr;
2318
2319 // Parse the instructions in this block until we get a terminator.
2320 Instruction *Inst;
2321 do {
2322 // This instruction may have three possibilities for a name: a) none
2323 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2324 LocTy NameLoc = Lex.getLoc();
2325 int NameID = -1;
2326 NameStr = "";
2327
2328 if (Lex.getKind() == lltok::LocalVarID) {
2329 NameID = Lex.getUIntVal();
2330 Lex.Lex();
2331 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2332 return true;
2333 } else if (Lex.getKind() == lltok::LocalVar ||
2334 // FIXME: REMOVE IN LLVM 3.0
2335 Lex.getKind() == lltok::StringConstant) {
2336 NameStr = Lex.getStrVal();
2337 Lex.Lex();
2338 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2339 return true;
2340 }
2341
2342 if (ParseInstruction(Inst, BB, PFS)) return true;
2343
2344 BB->getInstList().push_back(Inst);
2345
2346 // Set the name on the instruction.
2347 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2348 } while (!isa<TerminatorInst>(Inst));
2349
2350 return false;
2351}
2352
2353//===----------------------------------------------------------------------===//
2354// Instruction Parsing.
2355//===----------------------------------------------------------------------===//
2356
2357/// ParseInstruction - Parse one of the many different instructions.
2358///
2359bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2360 PerFunctionState &PFS) {
2361 lltok::Kind Token = Lex.getKind();
2362 if (Token == lltok::Eof)
2363 return TokError("found end of file when expecting more instructions");
2364 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002365 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 Lex.Lex(); // Eat the keyword.
2367
2368 switch (Token) {
2369 default: return Error(Loc, "expected instruction opcode");
2370 // Terminator Instructions.
2371 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2372 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2373 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2374 case lltok::kw_br: return ParseBr(Inst, PFS);
2375 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2376 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2377 // Binary Operators.
2378 case lltok::kw_add:
2379 case lltok::kw_sub:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002380 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
Chris Lattnere914b592009-01-05 08:24:46 +00002381
Chris Lattnerdf986172009-01-02 07:01:27 +00002382 case lltok::kw_udiv:
2383 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002385 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002386 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002387 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 case lltok::kw_shl:
2389 case lltok::kw_lshr:
2390 case lltok::kw_ashr:
2391 case lltok::kw_and:
2392 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002393 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 case lltok::kw_icmp:
2395 case lltok::kw_fcmp:
2396 case lltok::kw_vicmp:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002397 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 // Casts.
2399 case lltok::kw_trunc:
2400 case lltok::kw_zext:
2401 case lltok::kw_sext:
2402 case lltok::kw_fptrunc:
2403 case lltok::kw_fpext:
2404 case lltok::kw_bitcast:
2405 case lltok::kw_uitofp:
2406 case lltok::kw_sitofp:
2407 case lltok::kw_fptoui:
2408 case lltok::kw_fptosi:
2409 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002410 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 // Other.
2412 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002413 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2415 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2416 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2417 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2418 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2419 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2420 // Memory.
2421 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002422 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 case lltok::kw_free: return ParseFree(Inst, PFS);
2424 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2425 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2426 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002427 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002428 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002429 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002431 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2434 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2435 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2436 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2437 }
2438}
2439
2440/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2441bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2442 // FIXME: REMOVE vicmp/vfcmp!
2443 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2444 switch (Lex.getKind()) {
2445 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2446 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2447 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2448 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2449 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2450 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2451 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2452 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2453 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2454 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2455 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2456 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2457 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2458 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2459 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2460 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2461 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2462 }
2463 } else {
2464 switch (Lex.getKind()) {
2465 default: TokError("expected icmp predicate (e.g. 'eq')");
2466 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2467 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2468 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2469 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2470 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2471 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2472 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2473 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2474 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2475 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2476 }
2477 }
2478 Lex.Lex();
2479 return false;
2480}
2481
2482//===----------------------------------------------------------------------===//
2483// Terminator Instructions.
2484//===----------------------------------------------------------------------===//
2485
2486/// ParseRet - Parse a return instruction.
2487/// ::= 'ret' void
2488/// ::= 'ret' TypeAndValue
2489/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2490bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2491 PerFunctionState &PFS) {
2492 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002493 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002494
2495 if (Ty == Type::VoidTy) {
2496 Inst = ReturnInst::Create();
2497 return false;
2498 }
2499
2500 Value *RV;
2501 if (ParseValue(Ty, RV, PFS)) return true;
2502
2503 // The normal case is one return value.
2504 if (Lex.getKind() == lltok::comma) {
2505 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2506 // of 'ret {i32,i32} {i32 1, i32 2}'
2507 SmallVector<Value*, 8> RVs;
2508 RVs.push_back(RV);
2509
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002510 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002511 if (ParseTypeAndValue(RV, PFS)) return true;
2512 RVs.push_back(RV);
2513 }
2514
2515 RV = UndefValue::get(PFS.getFunction().getReturnType());
2516 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2517 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2518 BB->getInstList().push_back(I);
2519 RV = I;
2520 }
2521 }
2522 Inst = ReturnInst::Create(RV);
2523 return false;
2524}
2525
2526
2527/// ParseBr
2528/// ::= 'br' TypeAndValue
2529/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2530bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2531 LocTy Loc, Loc2;
2532 Value *Op0, *Op1, *Op2;
2533 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2534
2535 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2536 Inst = BranchInst::Create(BB);
2537 return false;
2538 }
2539
2540 if (Op0->getType() != Type::Int1Ty)
2541 return Error(Loc, "branch condition must have 'i1' type");
2542
2543 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2544 ParseTypeAndValue(Op1, Loc, PFS) ||
2545 ParseToken(lltok::comma, "expected ',' after true destination") ||
2546 ParseTypeAndValue(Op2, Loc2, PFS))
2547 return true;
2548
2549 if (!isa<BasicBlock>(Op1))
2550 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002551 if (!isa<BasicBlock>(Op2))
2552 return Error(Loc2, "true destination of branch must be a basic block");
2553
2554 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2555 return false;
2556}
2557
2558/// ParseSwitch
2559/// Instruction
2560/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2561/// JumpTable
2562/// ::= (TypeAndValue ',' TypeAndValue)*
2563bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2564 LocTy CondLoc, BBLoc;
2565 Value *Cond, *DefaultBB;
2566 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2567 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2568 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2569 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2570 return true;
2571
2572 if (!isa<IntegerType>(Cond->getType()))
2573 return Error(CondLoc, "switch condition must have integer type");
2574 if (!isa<BasicBlock>(DefaultBB))
2575 return Error(BBLoc, "default destination must be a basic block");
2576
2577 // Parse the jump table pairs.
2578 SmallPtrSet<Value*, 32> SeenCases;
2579 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2580 while (Lex.getKind() != lltok::rsquare) {
2581 Value *Constant, *DestBB;
2582
2583 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2584 ParseToken(lltok::comma, "expected ',' after case value") ||
2585 ParseTypeAndValue(DestBB, BBLoc, PFS))
2586 return true;
2587
2588 if (!SeenCases.insert(Constant))
2589 return Error(CondLoc, "duplicate case value in switch");
2590 if (!isa<ConstantInt>(Constant))
2591 return Error(CondLoc, "case value is not a constant integer");
2592 if (!isa<BasicBlock>(DestBB))
2593 return Error(BBLoc, "case destination is not a basic block");
2594
2595 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2596 cast<BasicBlock>(DestBB)));
2597 }
2598
2599 Lex.Lex(); // Eat the ']'.
2600
2601 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2602 Table.size());
2603 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2604 SI->addCase(Table[i].first, Table[i].second);
2605 Inst = SI;
2606 return false;
2607}
2608
2609/// ParseInvoke
2610/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2611/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2612bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2613 LocTy CallLoc = Lex.getLoc();
2614 unsigned CC, RetAttrs, FnAttrs;
2615 PATypeHolder RetType(Type::VoidTy);
2616 LocTy RetTypeLoc;
2617 ValID CalleeID;
2618 SmallVector<ParamInfo, 16> ArgList;
2619
2620 Value *NormalBB, *UnwindBB;
2621 if (ParseOptionalCallingConv(CC) ||
2622 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002623 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 ParseValID(CalleeID) ||
2625 ParseParameterList(ArgList, PFS) ||
2626 ParseOptionalAttrs(FnAttrs, 2) ||
2627 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2628 ParseTypeAndValue(NormalBB, PFS) ||
2629 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2630 ParseTypeAndValue(UnwindBB, PFS))
2631 return true;
2632
2633 if (!isa<BasicBlock>(NormalBB))
2634 return Error(CallLoc, "normal destination is not a basic block");
2635 if (!isa<BasicBlock>(UnwindBB))
2636 return Error(CallLoc, "unwind destination is not a basic block");
2637
2638 // If RetType is a non-function pointer type, then this is the short syntax
2639 // for the call, which means that RetType is just the return type. Infer the
2640 // rest of the function argument types from the arguments that are present.
2641 const PointerType *PFTy = 0;
2642 const FunctionType *Ty = 0;
2643 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2644 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2645 // Pull out the types of all of the arguments...
2646 std::vector<const Type*> ParamTypes;
2647 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2648 ParamTypes.push_back(ArgList[i].V->getType());
2649
2650 if (!FunctionType::isValidReturnType(RetType))
2651 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2652
2653 Ty = FunctionType::get(RetType, ParamTypes, false);
2654 PFTy = PointerType::getUnqual(Ty);
2655 }
2656
2657 // Look up the callee.
2658 Value *Callee;
2659 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2660
2661 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2662 // function attributes.
2663 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2664 if (FnAttrs & ObsoleteFuncAttrs) {
2665 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2666 FnAttrs &= ~ObsoleteFuncAttrs;
2667 }
2668
2669 // Set up the Attributes for the function.
2670 SmallVector<AttributeWithIndex, 8> Attrs;
2671 if (RetAttrs != Attribute::None)
2672 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2673
2674 SmallVector<Value*, 8> Args;
2675
2676 // Loop through FunctionType's arguments and ensure they are specified
2677 // correctly. Also, gather any parameter attributes.
2678 FunctionType::param_iterator I = Ty->param_begin();
2679 FunctionType::param_iterator E = Ty->param_end();
2680 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2681 const Type *ExpectedTy = 0;
2682 if (I != E) {
2683 ExpectedTy = *I++;
2684 } else if (!Ty->isVarArg()) {
2685 return Error(ArgList[i].Loc, "too many arguments specified");
2686 }
2687
2688 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2689 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2690 ExpectedTy->getDescription() + "'");
2691 Args.push_back(ArgList[i].V);
2692 if (ArgList[i].Attrs != Attribute::None)
2693 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2694 }
2695
2696 if (I != E)
2697 return Error(CallLoc, "not enough parameters specified for call");
2698
2699 if (FnAttrs != Attribute::None)
2700 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2701
2702 // Finish off the Attributes and check them
2703 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2704
2705 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2706 cast<BasicBlock>(UnwindBB),
2707 Args.begin(), Args.end());
2708 II->setCallingConv(CC);
2709 II->setAttributes(PAL);
2710 Inst = II;
2711 return false;
2712}
2713
2714
2715
2716//===----------------------------------------------------------------------===//
2717// Binary Operators.
2718//===----------------------------------------------------------------------===//
2719
2720/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002721/// ::= ArithmeticOps TypeAndValue ',' Value
2722///
2723/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2724/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002725bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002726 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 LocTy Loc; Value *LHS, *RHS;
2728 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2729 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2730 ParseValue(LHS->getType(), RHS, PFS))
2731 return true;
2732
Chris Lattnere914b592009-01-05 08:24:46 +00002733 bool Valid;
2734 switch (OperandType) {
2735 default: assert(0 && "Unknown operand type!");
2736 case 0: // int or FP.
2737 Valid = LHS->getType()->isIntOrIntVector() ||
2738 LHS->getType()->isFPOrFPVector();
2739 break;
2740 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2741 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2742 }
2743
2744 if (!Valid)
2745 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002746
2747 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2748 return false;
2749}
2750
2751/// ParseLogical
2752/// ::= ArithmeticOps TypeAndValue ',' Value {
2753bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2754 unsigned Opc) {
2755 LocTy Loc; Value *LHS, *RHS;
2756 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2757 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2758 ParseValue(LHS->getType(), RHS, PFS))
2759 return true;
2760
2761 if (!LHS->getType()->isIntOrIntVector())
2762 return Error(Loc,"instruction requires integer or integer vector operands");
2763
2764 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2765 return false;
2766}
2767
2768
2769/// ParseCompare
2770/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2771/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2772/// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2773/// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2774bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2775 unsigned Opc) {
2776 // Parse the integer/fp comparison predicate.
2777 LocTy Loc;
2778 unsigned Pred;
2779 Value *LHS, *RHS;
2780 if (ParseCmpPredicate(Pred, Opc) ||
2781 ParseTypeAndValue(LHS, Loc, PFS) ||
2782 ParseToken(lltok::comma, "expected ',' after compare value") ||
2783 ParseValue(LHS->getType(), RHS, PFS))
2784 return true;
2785
2786 if (Opc == Instruction::FCmp) {
2787 if (!LHS->getType()->isFPOrFPVector())
2788 return Error(Loc, "fcmp requires floating point operands");
2789 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2790 } else if (Opc == Instruction::ICmp) {
2791 if (!LHS->getType()->isIntOrIntVector() &&
2792 !isa<PointerType>(LHS->getType()))
2793 return Error(Loc, "icmp requires integer operands");
2794 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2795 } else if (Opc == Instruction::VFCmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002796 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2797 return Error(Loc, "vfcmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2799 } else if (Opc == Instruction::VICmp) {
Chris Lattner4a1c4a42009-01-05 08:09:48 +00002800 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2801 return Error(Loc, "vicmp requires vector floating point operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00002802 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2803 }
2804 return false;
2805}
2806
2807//===----------------------------------------------------------------------===//
2808// Other Instructions.
2809//===----------------------------------------------------------------------===//
2810
2811
2812/// ParseCast
2813/// ::= CastOpc TypeAndValue 'to' Type
2814bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2815 unsigned Opc) {
2816 LocTy Loc; Value *Op;
2817 PATypeHolder DestTy(Type::VoidTy);
2818 if (ParseTypeAndValue(Op, Loc, PFS) ||
2819 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2820 ParseType(DestTy))
2821 return true;
2822
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002823 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2824 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002825 return Error(Loc, "invalid cast opcode for cast from '" +
2826 Op->getType()->getDescription() + "' to '" +
2827 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002828 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2830 return false;
2831}
2832
2833/// ParseSelect
2834/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2835bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2836 LocTy Loc;
2837 Value *Op0, *Op1, *Op2;
2838 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2839 ParseToken(lltok::comma, "expected ',' after select condition") ||
2840 ParseTypeAndValue(Op1, PFS) ||
2841 ParseToken(lltok::comma, "expected ',' after select value") ||
2842 ParseTypeAndValue(Op2, PFS))
2843 return true;
2844
2845 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2846 return Error(Loc, Reason);
2847
2848 Inst = SelectInst::Create(Op0, Op1, Op2);
2849 return false;
2850}
2851
Chris Lattner0088a5c2009-01-05 08:18:44 +00002852/// ParseVA_Arg
2853/// ::= 'va_arg' TypeAndValue ',' Type
2854bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 Value *Op;
2856 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002857 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002858 if (ParseTypeAndValue(Op, PFS) ||
2859 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002860 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002861 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002862
2863 if (!EltTy->isFirstClassType())
2864 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002865
2866 Inst = new VAArgInst(Op, EltTy);
2867 return false;
2868}
2869
2870/// ParseExtractElement
2871/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2872bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2873 LocTy Loc;
2874 Value *Op0, *Op1;
2875 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2876 ParseToken(lltok::comma, "expected ',' after extract value") ||
2877 ParseTypeAndValue(Op1, PFS))
2878 return true;
2879
2880 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2881 return Error(Loc, "invalid extractelement operands");
2882
2883 Inst = new ExtractElementInst(Op0, Op1);
2884 return false;
2885}
2886
2887/// ParseInsertElement
2888/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2889bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2890 LocTy Loc;
2891 Value *Op0, *Op1, *Op2;
2892 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2893 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2894 ParseTypeAndValue(Op1, PFS) ||
2895 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2896 ParseTypeAndValue(Op2, PFS))
2897 return true;
2898
2899 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2900 return Error(Loc, "invalid extractelement operands");
2901
2902 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2903 return false;
2904}
2905
2906/// ParseShuffleVector
2907/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2908bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2909 LocTy Loc;
2910 Value *Op0, *Op1, *Op2;
2911 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2912 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2913 ParseTypeAndValue(Op1, PFS) ||
2914 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2915 ParseTypeAndValue(Op2, PFS))
2916 return true;
2917
2918 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2919 return Error(Loc, "invalid extractelement operands");
2920
2921 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2922 return false;
2923}
2924
2925/// ParsePHI
2926/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2927bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2928 PATypeHolder Ty(Type::VoidTy);
2929 Value *Op0, *Op1;
2930 LocTy TypeLoc = Lex.getLoc();
2931
2932 if (ParseType(Ty) ||
2933 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2934 ParseValue(Ty, Op0, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2936 ParseValue(Type::LabelTy, Op1, PFS) ||
2937 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2938 return true;
2939
2940 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2941 while (1) {
2942 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2943
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002944 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00002945 break;
2946
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002947 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002948 ParseValue(Ty, Op0, PFS) ||
2949 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2950 ParseValue(Type::LabelTy, Op1, PFS) ||
2951 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2952 return true;
2953 }
2954
2955 if (!Ty->isFirstClassType())
2956 return Error(TypeLoc, "phi node must have first class type");
2957
2958 PHINode *PN = PHINode::Create(Ty);
2959 PN->reserveOperandSpace(PHIVals.size());
2960 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2961 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2962 Inst = PN;
2963 return false;
2964}
2965
2966/// ParseCall
2967/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2968/// ParameterList OptionalAttrs
2969bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2970 bool isTail) {
2971 unsigned CC, RetAttrs, FnAttrs;
2972 PATypeHolder RetType(Type::VoidTy);
2973 LocTy RetTypeLoc;
2974 ValID CalleeID;
2975 SmallVector<ParamInfo, 16> ArgList;
2976 LocTy CallLoc = Lex.getLoc();
2977
2978 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2979 ParseOptionalCallingConv(CC) ||
2980 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002981 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002982 ParseValID(CalleeID) ||
2983 ParseParameterList(ArgList, PFS) ||
2984 ParseOptionalAttrs(FnAttrs, 2))
2985 return true;
2986
2987 // If RetType is a non-function pointer type, then this is the short syntax
2988 // for the call, which means that RetType is just the return type. Infer the
2989 // rest of the function argument types from the arguments that are present.
2990 const PointerType *PFTy = 0;
2991 const FunctionType *Ty = 0;
2992 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2993 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2994 // Pull out the types of all of the arguments...
2995 std::vector<const Type*> ParamTypes;
2996 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2997 ParamTypes.push_back(ArgList[i].V->getType());
2998
2999 if (!FunctionType::isValidReturnType(RetType))
3000 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3001
3002 Ty = FunctionType::get(RetType, ParamTypes, false);
3003 PFTy = PointerType::getUnqual(Ty);
3004 }
3005
3006 // Look up the callee.
3007 Value *Callee;
3008 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3009
Chris Lattnerdf986172009-01-02 07:01:27 +00003010 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3011 // function attributes.
3012 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3013 if (FnAttrs & ObsoleteFuncAttrs) {
3014 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3015 FnAttrs &= ~ObsoleteFuncAttrs;
3016 }
3017
3018 // Set up the Attributes for the function.
3019 SmallVector<AttributeWithIndex, 8> Attrs;
3020 if (RetAttrs != Attribute::None)
3021 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3022
3023 SmallVector<Value*, 8> Args;
3024
3025 // Loop through FunctionType's arguments and ensure they are specified
3026 // correctly. Also, gather any parameter attributes.
3027 FunctionType::param_iterator I = Ty->param_begin();
3028 FunctionType::param_iterator E = Ty->param_end();
3029 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3030 const Type *ExpectedTy = 0;
3031 if (I != E) {
3032 ExpectedTy = *I++;
3033 } else if (!Ty->isVarArg()) {
3034 return Error(ArgList[i].Loc, "too many arguments specified");
3035 }
3036
3037 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3038 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3039 ExpectedTy->getDescription() + "'");
3040 Args.push_back(ArgList[i].V);
3041 if (ArgList[i].Attrs != Attribute::None)
3042 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3043 }
3044
3045 if (I != E)
3046 return Error(CallLoc, "not enough parameters specified for call");
3047
3048 if (FnAttrs != Attribute::None)
3049 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3050
3051 // Finish off the Attributes and check them
3052 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3053
3054 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3055 CI->setTailCall(isTail);
3056 CI->setCallingConv(CC);
3057 CI->setAttributes(PAL);
3058 Inst = CI;
3059 return false;
3060}
3061
3062//===----------------------------------------------------------------------===//
3063// Memory Instructions.
3064//===----------------------------------------------------------------------===//
3065
3066/// ParseAlloc
3067/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3068/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3069bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3070 unsigned Opc) {
3071 PATypeHolder Ty(Type::VoidTy);
3072 Value *Size = 0;
3073 LocTy SizeLoc = 0;
3074 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003075 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003076
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003077 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 if (Lex.getKind() == lltok::kw_align) {
3079 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003080 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3081 ParseOptionalCommaAlignment(Alignment)) {
3082 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 }
3084 }
3085
3086 if (Size && Size->getType() != Type::Int32Ty)
3087 return Error(SizeLoc, "element count must be i32");
3088
3089 if (Opc == Instruction::Malloc)
3090 Inst = new MallocInst(Ty, Size, Alignment);
3091 else
3092 Inst = new AllocaInst(Ty, Size, Alignment);
3093 return false;
3094}
3095
3096/// ParseFree
3097/// ::= 'free' TypeAndValue
3098bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3099 Value *Val; LocTy Loc;
3100 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3101 if (!isa<PointerType>(Val->getType()))
3102 return Error(Loc, "operand to free must be a pointer");
3103 Inst = new FreeInst(Val);
3104 return false;
3105}
3106
3107/// ParseLoad
3108/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3109bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3110 bool isVolatile) {
3111 Value *Val; LocTy Loc;
3112 unsigned Alignment;
3113 if (ParseTypeAndValue(Val, Loc, PFS) ||
3114 ParseOptionalCommaAlignment(Alignment))
3115 return true;
3116
3117 if (!isa<PointerType>(Val->getType()) ||
3118 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3119 return Error(Loc, "load operand must be a pointer to a first class type");
3120
3121 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3122 return false;
3123}
3124
3125/// ParseStore
3126/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3127bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3128 bool isVolatile) {
3129 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3130 unsigned Alignment;
3131 if (ParseTypeAndValue(Val, Loc, PFS) ||
3132 ParseToken(lltok::comma, "expected ',' after store operand") ||
3133 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3134 ParseOptionalCommaAlignment(Alignment))
3135 return true;
3136
3137 if (!isa<PointerType>(Ptr->getType()))
3138 return Error(PtrLoc, "store operand must be a pointer");
3139 if (!Val->getType()->isFirstClassType())
3140 return Error(Loc, "store operand must be a first class value");
3141 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3142 return Error(Loc, "stored value and pointer type do not match");
3143
3144 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3145 return false;
3146}
3147
3148/// ParseGetResult
3149/// ::= 'getresult' TypeAndValue ',' uint
3150/// FIXME: Remove support for getresult in LLVM 3.0
3151bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3152 Value *Val; LocTy ValLoc, EltLoc;
3153 unsigned Element;
3154 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3155 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003156 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 return true;
3158
3159 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3160 return Error(ValLoc, "getresult inst requires an aggregate operand");
3161 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3162 return Error(EltLoc, "invalid getresult index for value");
3163 Inst = ExtractValueInst::Create(Val, Element);
3164 return false;
3165}
3166
3167/// ParseGetElementPtr
3168/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3169bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3170 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003171 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003172
3173 if (!isa<PointerType>(Ptr->getType()))
3174 return Error(Loc, "base of getelementptr must be a pointer");
3175
3176 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003177 while (EatIfPresent(lltok::comma)) {
3178 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 if (!isa<IntegerType>(Val->getType()))
3180 return Error(EltLoc, "getelementptr index must be an integer");
3181 Indices.push_back(Val);
3182 }
3183
3184 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3185 Indices.begin(), Indices.end()))
3186 return Error(Loc, "invalid getelementptr indices");
3187 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3188 return false;
3189}
3190
3191/// ParseExtractValue
3192/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3193bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3194 Value *Val; LocTy Loc;
3195 SmallVector<unsigned, 4> Indices;
3196 if (ParseTypeAndValue(Val, Loc, PFS) ||
3197 ParseIndexList(Indices))
3198 return true;
3199
3200 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3201 return Error(Loc, "extractvalue operand must be array or struct");
3202
3203 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3204 Indices.end()))
3205 return Error(Loc, "invalid indices for extractvalue");
3206 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3207 return false;
3208}
3209
3210/// ParseInsertValue
3211/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3212bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3213 Value *Val0, *Val1; LocTy Loc0, Loc1;
3214 SmallVector<unsigned, 4> Indices;
3215 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3216 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3217 ParseTypeAndValue(Val1, Loc1, PFS) ||
3218 ParseIndexList(Indices))
3219 return true;
3220
3221 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3222 return Error(Loc0, "extractvalue operand must be array or struct");
3223
3224 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3225 Indices.end()))
3226 return Error(Loc0, "invalid indices for insertvalue");
3227 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3228 return false;
3229}