blob: 8092d577794625e74cdb729c7f3dac523565337a [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"
Owen Andersonfba933c2009-07-01 23:57:11 +000021#include "llvm/LLVMContext.h"
Nick Lewyckycb337992009-05-10 20:57:05 +000022#include "llvm/MDNode.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000028#include "llvm/Support/raw_ostream.h"
29using namespace llvm;
30
Chris Lattnerdf986172009-01-02 07:01:27 +000031namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 /// ValID - Represents a reference of a definition of some sort with no type.
33 /// There are several cases where we have to parse the value but where the
34 /// type can depend on later context. This may either be a numeric reference
35 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000036 struct ValID {
37 enum {
38 t_LocalID, t_GlobalID, // ID in UIntVal.
39 t_LocalName, t_GlobalName, // Name in StrVal.
40 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
41 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000042 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000043 t_Constant, // Value in ConstantVal.
44 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
45 } Kind;
46
47 LLParser::LocTy Loc;
48 unsigned UIntVal;
49 std::string StrVal, StrVal2;
50 APSInt APSIntVal;
51 APFloat APFloatVal;
52 Constant *ConstantVal;
53 ValID() : APFloatVal(0.0) {}
54 };
55}
56
Chris Lattner3ed88ef2009-01-02 08:05:26 +000057/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000058bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000059 // Prime the lexer.
60 Lex.Lex();
61
Chris Lattnerad7d1e22009-01-04 20:44:11 +000062 return ParseTopLevelEntities() ||
63 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000064}
65
66/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
67/// module.
68bool LLParser::ValidateEndOfModule() {
69 if (!ForwardRefTypes.empty())
70 return Error(ForwardRefTypes.begin()->second.second,
71 "use of undefined type named '" +
72 ForwardRefTypes.begin()->first + "'");
73 if (!ForwardRefTypeIDs.empty())
74 return Error(ForwardRefTypeIDs.begin()->second.second,
75 "use of undefined type '%" +
76 utostr(ForwardRefTypeIDs.begin()->first) + "'");
77
78 if (!ForwardRefVals.empty())
79 return Error(ForwardRefVals.begin()->second.second,
80 "use of undefined value '@" + ForwardRefVals.begin()->first +
81 "'");
82
83 if (!ForwardRefValIDs.empty())
84 return Error(ForwardRefValIDs.begin()->second.second,
85 "use of undefined value '@" +
86 utostr(ForwardRefValIDs.begin()->first) + "'");
87
Devang Patel1c7eea62009-07-08 19:23:54 +000088 if (!ForwardRefMDNodes.empty())
89 return Error(ForwardRefMDNodes.begin()->second.second,
90 "use of undefined metadata '!" +
91 utostr(ForwardRefMDNodes.begin()->first) + "'");
92
93
Chris Lattnerdf986172009-01-02 07:01:27 +000094 // Look for intrinsic functions and CallInst that need to be upgraded
95 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
96 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
97
98 return false;
99}
100
101//===----------------------------------------------------------------------===//
102// Top-Level Entities
103//===----------------------------------------------------------------------===//
104
105bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000106 while (1) {
107 switch (Lex.getKind()) {
108 default: return TokError("expected top-level entity");
109 case lltok::Eof: return false;
110 //case lltok::kw_define:
111 case lltok::kw_declare: if (ParseDeclare()) return true; break;
112 case lltok::kw_define: if (ParseDefine()) return true; break;
113 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
114 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
115 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
116 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
117 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
118 case lltok::LocalVar: if (ParseNamedType()) return true; break;
119 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000120 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000121
122 // The Global variable production with no name can have many different
123 // optional leading prefixes, the production is:
124 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
125 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000126 case lltok::kw_private : // OptionalLinkage
127 case lltok::kw_linker_private: // OptionalLinkage
128 case lltok::kw_internal: // OptionalLinkage
129 case lltok::kw_weak: // OptionalLinkage
130 case lltok::kw_weak_odr: // OptionalLinkage
131 case lltok::kw_linkonce: // OptionalLinkage
132 case lltok::kw_linkonce_odr: // OptionalLinkage
133 case lltok::kw_appending: // OptionalLinkage
134 case lltok::kw_dllexport: // OptionalLinkage
135 case lltok::kw_common: // OptionalLinkage
136 case lltok::kw_dllimport: // OptionalLinkage
137 case lltok::kw_extern_weak: // OptionalLinkage
138 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000139 unsigned Linkage, Visibility;
140 if (ParseOptionalLinkage(Linkage) ||
141 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000142 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000143 return true;
144 break;
145 }
146 case lltok::kw_default: // OptionalVisibility
147 case lltok::kw_hidden: // OptionalVisibility
148 case lltok::kw_protected: { // OptionalVisibility
149 unsigned Visibility;
150 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000151 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000152 return true;
153 break;
154 }
155
156 case lltok::kw_thread_local: // OptionalThreadLocal
157 case lltok::kw_addrspace: // OptionalAddrSpace
158 case lltok::kw_constant: // GlobalType
159 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000160 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000161 break;
162 }
163 }
164}
165
166
167/// toplevelentity
168/// ::= 'module' 'asm' STRINGCONSTANT
169bool LLParser::ParseModuleAsm() {
170 assert(Lex.getKind() == lltok::kw_module);
171 Lex.Lex();
172
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000173 std::string AsmStr;
174 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
175 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000176
177 const std::string &AsmSoFar = M->getModuleInlineAsm();
178 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000180 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000181 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000182 return false;
183}
184
185/// toplevelentity
186/// ::= 'target' 'triple' '=' STRINGCONSTANT
187/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
188bool LLParser::ParseTargetDefinition() {
189 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000190 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 switch (Lex.Lex()) {
192 default: return TokError("unknown target property");
193 case lltok::kw_triple:
194 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000195 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
196 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000197 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000198 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 return false;
200 case lltok::kw_datalayout:
201 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000202 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
203 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000205 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000206 return false;
207 }
208}
209
210/// toplevelentity
211/// ::= 'deplibs' '=' '[' ']'
212/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
213bool LLParser::ParseDepLibs() {
214 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000215 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000216 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
217 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
218 return true;
219
220 if (EatIfPresent(lltok::rsquare))
221 return false;
222
223 std::string Str;
224 if (ParseStringConstant(Str)) return true;
225 M->addLibrary(Str);
226
227 while (EatIfPresent(lltok::comma)) {
228 if (ParseStringConstant(Str)) return true;
229 M->addLibrary(Str);
230 }
231
232 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000233}
234
235/// toplevelentity
236/// ::= 'type' type
237bool LLParser::ParseUnnamedType() {
238 assert(Lex.getKind() == lltok::kw_type);
239 LocTy TypeLoc = Lex.getLoc();
240 Lex.Lex(); // eat kw_type
241
242 PATypeHolder Ty(Type::VoidTy);
243 if (ParseType(Ty)) return true;
244
245 unsigned TypeID = NumberedTypes.size();
246
Chris Lattnerdf986172009-01-02 07:01:27 +0000247 // See if this type was previously referenced.
248 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
249 FI = ForwardRefTypeIDs.find(TypeID);
250 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000251 if (FI->second.first.get() == Ty)
252 return Error(TypeLoc, "self referential type is invalid");
253
Chris Lattnerdf986172009-01-02 07:01:27 +0000254 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
255 Ty = FI->second.first.get();
256 ForwardRefTypeIDs.erase(FI);
257 }
258
259 NumberedTypes.push_back(Ty);
260
261 return false;
262}
263
264/// toplevelentity
265/// ::= LocalVar '=' 'type' type
266bool LLParser::ParseNamedType() {
267 std::string Name = Lex.getStrVal();
268 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000269 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000270
271 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272
273 if (ParseToken(lltok::equal, "expected '=' after name") ||
274 ParseToken(lltok::kw_type, "expected 'type' after name") ||
275 ParseType(Ty))
276 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000277
Chris Lattnerdf986172009-01-02 07:01:27 +0000278 // Set the type name, checking for conflicts as we do so.
279 bool AlreadyExists = M->addTypeName(Name, Ty);
280 if (!AlreadyExists) return false;
281
282 // See if this type is a forward reference. We need to eagerly resolve
283 // types to allow recursive type redefinitions below.
284 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
285 FI = ForwardRefTypes.find(Name);
286 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000287 if (FI->second.first.get() == Ty)
288 return Error(NameLoc, "self referential type is invalid");
289
Chris Lattnerdf986172009-01-02 07:01:27 +0000290 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
291 Ty = FI->second.first.get();
292 ForwardRefTypes.erase(FI);
293 }
294
295 // Inserting a name that is already defined, get the existing name.
296 const Type *Existing = M->getTypeByName(Name);
297 assert(Existing && "Conflict but no matching type?!");
298
299 // Otherwise, this is an attempt to redefine a type. That's okay if
300 // the redefinition is identical to the original.
301 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
302 if (Existing == Ty) return false;
303
304 // Any other kind of (non-equivalent) redefinition is an error.
305 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
306 Ty->getDescription() + "'");
307}
308
309
310/// toplevelentity
311/// ::= 'declare' FunctionHeader
312bool LLParser::ParseDeclare() {
313 assert(Lex.getKind() == lltok::kw_declare);
314 Lex.Lex();
315
316 Function *F;
317 return ParseFunctionHeader(F, false);
318}
319
320/// toplevelentity
321/// ::= 'define' FunctionHeader '{' ...
322bool LLParser::ParseDefine() {
323 assert(Lex.getKind() == lltok::kw_define);
324 Lex.Lex();
325
326 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000327 return ParseFunctionHeader(F, true) ||
328 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000329}
330
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000331/// ParseGlobalType
332/// ::= 'constant'
333/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000334bool LLParser::ParseGlobalType(bool &IsConstant) {
335 if (Lex.getKind() == lltok::kw_constant)
336 IsConstant = true;
337 else if (Lex.getKind() == lltok::kw_global)
338 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000339 else {
340 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000342 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000343 Lex.Lex();
344 return false;
345}
346
347/// ParseNamedGlobal:
348/// GlobalVar '=' OptionalVisibility ALIAS ...
349/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
350bool LLParser::ParseNamedGlobal() {
351 assert(Lex.getKind() == lltok::GlobalVar);
352 LocTy NameLoc = Lex.getLoc();
353 std::string Name = Lex.getStrVal();
354 Lex.Lex();
355
356 bool HasLinkage;
357 unsigned Linkage, Visibility;
358 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
359 ParseOptionalLinkage(Linkage, HasLinkage) ||
360 ParseOptionalVisibility(Visibility))
361 return true;
362
363 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
364 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
365 return ParseAlias(Name, NameLoc, Visibility);
366}
367
Devang Patel923078c2009-07-01 19:21:12 +0000368/// ParseStandaloneMetadata:
369/// !42 = !{...}
370bool LLParser::ParseStandaloneMetadata() {
371 assert(Lex.getKind() == lltok::Metadata);
372 Lex.Lex();
373 unsigned MetadataID = 0;
374 if (ParseUInt32(MetadataID))
375 return true;
376 if (MetadataCache.find(MetadataID) != MetadataCache.end())
377 return TokError("Metadata id is already used");
378 if (ParseToken(lltok::equal, "expected '=' here"))
379 return true;
380
381 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000382 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000383 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000384 return true;
385
386 Constant *Init = 0;
387 if (ParseGlobalValue(Ty, Init))
388 return true;
389
390 MetadataCache[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000391 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
392 FI = ForwardRefMDNodes.find(MetadataID);
393 if (FI != ForwardRefMDNodes.end()) {
394 Constant *FwdNode = FI->second.first;
395 FwdNode->replaceAllUsesWith(Init);
396 ForwardRefMDNodes.erase(FI);
397 }
398
Devang Patel923078c2009-07-01 19:21:12 +0000399 return false;
400}
401
Chris Lattnerdf986172009-01-02 07:01:27 +0000402/// ParseAlias:
403/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
404/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000405/// ::= TypeAndValue
406/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
407/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000408///
409/// Everything through visibility has already been parsed.
410///
411bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
412 unsigned Visibility) {
413 assert(Lex.getKind() == lltok::kw_alias);
414 Lex.Lex();
415 unsigned Linkage;
416 LocTy LinkageLoc = Lex.getLoc();
417 if (ParseOptionalLinkage(Linkage))
418 return true;
419
420 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000421 Linkage != GlobalValue::WeakAnyLinkage &&
422 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000423 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000424 Linkage != GlobalValue::PrivateLinkage &&
425 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 return Error(LinkageLoc, "invalid linkage type for alias");
427
428 Constant *Aliasee;
429 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000430 if (Lex.getKind() != lltok::kw_bitcast &&
431 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000432 if (ParseGlobalTypeAndValue(Aliasee)) return true;
433 } else {
434 // The bitcast dest type is not present, it is implied by the dest type.
435 ValID ID;
436 if (ParseValID(ID)) return true;
437 if (ID.Kind != ValID::t_Constant)
438 return Error(AliaseeLoc, "invalid aliasee");
439 Aliasee = ID.ConstantVal;
440 }
441
442 if (!isa<PointerType>(Aliasee->getType()))
443 return Error(AliaseeLoc, "alias must have pointer type");
444
445 // Okay, create the alias but do not insert it into the module yet.
446 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
447 (GlobalValue::LinkageTypes)Linkage, Name,
448 Aliasee);
449 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
450
451 // See if this value already exists in the symbol table. If so, it is either
452 // a redefinition or a definition of a forward reference.
453 if (GlobalValue *Val =
454 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
455 // See if this was a redefinition. If so, there is no entry in
456 // ForwardRefVals.
457 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
458 I = ForwardRefVals.find(Name);
459 if (I == ForwardRefVals.end())
460 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
461
462 // Otherwise, this was a definition of forward ref. Verify that types
463 // agree.
464 if (Val->getType() != GA->getType())
465 return Error(NameLoc,
466 "forward reference and definition of alias have different types");
467
468 // If they agree, just RAUW the old value with the alias and remove the
469 // forward ref info.
470 Val->replaceAllUsesWith(GA);
471 Val->eraseFromParent();
472 ForwardRefVals.erase(I);
473 }
474
475 // Insert into the module, we know its name won't collide now.
476 M->getAliasList().push_back(GA);
477 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
478
479 return false;
480}
481
482/// ParseGlobal
483/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
484/// OptionalAddrSpace GlobalType Type Const
485/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
486/// OptionalAddrSpace GlobalType Type Const
487///
488/// Everything through visibility has been parsed already.
489///
490bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
491 unsigned Linkage, bool HasLinkage,
492 unsigned Visibility) {
493 unsigned AddrSpace;
494 bool ThreadLocal, IsConstant;
495 LocTy TyLoc;
496
497 PATypeHolder Ty(Type::VoidTy);
498 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
499 ParseOptionalAddrSpace(AddrSpace) ||
500 ParseGlobalType(IsConstant) ||
501 ParseType(Ty, TyLoc))
502 return true;
503
504 // If the linkage is specified and is external, then no initializer is
505 // present.
506 Constant *Init = 0;
507 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000508 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000509 Linkage != GlobalValue::ExternalLinkage)) {
510 if (ParseGlobalValue(Ty, Init))
511 return true;
512 }
513
Chris Lattnera9a9e072009-03-09 04:49:14 +0000514 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000515 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000516
517 GlobalVariable *GV = 0;
518
519 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000520 if (!Name.empty()) {
521 if ((GV = M->getGlobalVariable(Name, true)) &&
522 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000523 return Error(NameLoc, "redefinition of global '@" + Name + "'");
524 } else {
525 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
526 I = ForwardRefValIDs.find(NumberedVals.size());
527 if (I != ForwardRefValIDs.end()) {
528 GV = cast<GlobalVariable>(I->second.first);
529 ForwardRefValIDs.erase(I);
530 }
531 }
532
533 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000534 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
535 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000536 } else {
537 if (GV->getType()->getElementType() != Ty)
538 return Error(TyLoc,
539 "forward reference and definition of global have different types");
540
541 // Move the forward-reference to the correct spot in the module.
542 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
543 }
544
545 if (Name.empty())
546 NumberedVals.push_back(GV);
547
548 // Set the parsed properties on the global.
549 if (Init)
550 GV->setInitializer(Init);
551 GV->setConstant(IsConstant);
552 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
553 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
554 GV->setThreadLocal(ThreadLocal);
555
556 // Parse attributes on the global.
557 while (Lex.getKind() == lltok::comma) {
558 Lex.Lex();
559
560 if (Lex.getKind() == lltok::kw_section) {
561 Lex.Lex();
562 GV->setSection(Lex.getStrVal());
563 if (ParseToken(lltok::StringConstant, "expected global section string"))
564 return true;
565 } else if (Lex.getKind() == lltok::kw_align) {
566 unsigned Alignment;
567 if (ParseOptionalAlignment(Alignment)) return true;
568 GV->setAlignment(Alignment);
569 } else {
570 TokError("unknown global variable property!");
571 }
572 }
573
574 return false;
575}
576
577
578//===----------------------------------------------------------------------===//
579// GlobalValue Reference/Resolution Routines.
580//===----------------------------------------------------------------------===//
581
582/// GetGlobalVal - Get a value with the specified name or ID, creating a
583/// forward reference record if needed. This can return null if the value
584/// exists but does not have the right type.
585GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
586 LocTy Loc) {
587 const PointerType *PTy = dyn_cast<PointerType>(Ty);
588 if (PTy == 0) {
589 Error(Loc, "global variable reference must have pointer type");
590 return 0;
591 }
592
593 // Look this name up in the normal function symbol table.
594 GlobalValue *Val =
595 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
596
597 // If this is a forward reference for the value, see if we already created a
598 // forward ref record.
599 if (Val == 0) {
600 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
601 I = ForwardRefVals.find(Name);
602 if (I != ForwardRefVals.end())
603 Val = I->second.first;
604 }
605
606 // If we have the value in the symbol table or fwd-ref table, return it.
607 if (Val) {
608 if (Val->getType() == Ty) return Val;
609 Error(Loc, "'@" + Name + "' defined with type '" +
610 Val->getType()->getDescription() + "'");
611 return 0;
612 }
613
614 // Otherwise, create a new forward reference for this value and remember it.
615 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000616 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
617 // Function types can return opaque but functions can't.
618 if (isa<OpaqueType>(FT->getReturnType())) {
619 Error(Loc, "function may not return opaque type");
620 return 0;
621 }
622
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000623 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000624 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000625 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
626 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000627 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000628
629 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
630 return FwdVal;
631}
632
633GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
634 const PointerType *PTy = dyn_cast<PointerType>(Ty);
635 if (PTy == 0) {
636 Error(Loc, "global variable reference must have pointer type");
637 return 0;
638 }
639
640 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
641
642 // If this is a forward reference for the value, see if we already created a
643 // forward ref record.
644 if (Val == 0) {
645 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
646 I = ForwardRefValIDs.find(ID);
647 if (I != ForwardRefValIDs.end())
648 Val = I->second.first;
649 }
650
651 // If we have the value in the symbol table or fwd-ref table, return it.
652 if (Val) {
653 if (Val->getType() == Ty) return Val;
654 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
655 Val->getType()->getDescription() + "'");
656 return 0;
657 }
658
659 // Otherwise, create a new forward reference for this value and remember it.
660 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000661 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
662 // Function types can return opaque but functions can't.
663 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000664 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000665 return 0;
666 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000667 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000668 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000669 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
670 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000671 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000672
673 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
674 return FwdVal;
675}
676
677
678//===----------------------------------------------------------------------===//
679// Helper Routines.
680//===----------------------------------------------------------------------===//
681
682/// ParseToken - If the current token has the specified kind, eat it and return
683/// success. Otherwise, emit the specified error and return failure.
684bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
685 if (Lex.getKind() != T)
686 return TokError(ErrMsg);
687 Lex.Lex();
688 return false;
689}
690
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000691/// ParseStringConstant
692/// ::= StringConstant
693bool LLParser::ParseStringConstant(std::string &Result) {
694 if (Lex.getKind() != lltok::StringConstant)
695 return TokError("expected string constant");
696 Result = Lex.getStrVal();
697 Lex.Lex();
698 return false;
699}
700
701/// ParseUInt32
702/// ::= uint32
703bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000704 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
705 return TokError("expected integer");
706 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
707 if (Val64 != unsigned(Val64))
708 return TokError("expected 32-bit integer (too large)");
709 Val = Val64;
710 Lex.Lex();
711 return false;
712}
713
714
715/// ParseOptionalAddrSpace
716/// := /*empty*/
717/// := 'addrspace' '(' uint32 ')'
718bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
719 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000720 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000721 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000723 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 ParseToken(lltok::rparen, "expected ')' in address space");
725}
726
727/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
728/// indicates what kind of attribute list this is: 0: function arg, 1: result,
729/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000730/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000731bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
732 Attrs = Attribute::None;
733 LocTy AttrLoc = Lex.getLoc();
734
735 while (1) {
736 switch (Lex.getKind()) {
737 case lltok::kw_sext:
738 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000739 // Treat these as signext/zeroext if they occur in the argument list after
740 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
741 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
742 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000743 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000744 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 if (Lex.getKind() == lltok::kw_sext)
746 Attrs |= Attribute::SExt;
747 else
748 Attrs |= Attribute::ZExt;
749 break;
750 }
751 // FALL THROUGH.
752 default: // End of attributes.
753 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
754 return Error(AttrLoc, "invalid use of function-only attribute");
755
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000756 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000757 return Error(AttrLoc, "invalid use of parameter-only attribute");
758
759 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000760 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
761 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
762 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
763 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
764 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
765 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
766 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
767 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000768
Devang Patel578efa92009-06-05 21:57:13 +0000769 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
770 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
771 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
772 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
773 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
774 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
775 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
776 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
777 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
778 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
779 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000780 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000781
782 case lltok::kw_align: {
783 unsigned Alignment;
784 if (ParseOptionalAlignment(Alignment))
785 return true;
786 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
787 continue;
788 }
789 }
790 Lex.Lex();
791 }
792}
793
794/// ParseOptionalLinkage
795/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000796/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000797/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000798/// ::= 'internal'
799/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000800/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000801/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000802/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000803/// ::= 'appending'
804/// ::= 'dllexport'
805/// ::= 'common'
806/// ::= 'dllimport'
807/// ::= 'extern_weak'
808/// ::= 'external'
809bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
810 HasLinkage = false;
811 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000812 default: Res=GlobalValue::ExternalLinkage; return false;
813 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
814 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
815 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
816 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
817 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
818 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
819 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000820 case lltok::kw_available_externally:
821 Res = GlobalValue::AvailableExternallyLinkage;
822 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000823 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
824 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
825 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
826 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
827 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
828 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000829 }
830 Lex.Lex();
831 HasLinkage = true;
832 return false;
833}
834
835/// ParseOptionalVisibility
836/// ::= /*empty*/
837/// ::= 'default'
838/// ::= 'hidden'
839/// ::= 'protected'
840///
841bool LLParser::ParseOptionalVisibility(unsigned &Res) {
842 switch (Lex.getKind()) {
843 default: Res = GlobalValue::DefaultVisibility; return false;
844 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
845 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
846 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
847 }
848 Lex.Lex();
849 return false;
850}
851
852/// ParseOptionalCallingConv
853/// ::= /*empty*/
854/// ::= 'ccc'
855/// ::= 'fastcc'
856/// ::= 'coldcc'
857/// ::= 'x86_stdcallcc'
858/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000859/// ::= 'arm_apcscc'
860/// ::= 'arm_aapcscc'
861/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000862/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000863///
Chris Lattnerdf986172009-01-02 07:01:27 +0000864bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
865 switch (Lex.getKind()) {
866 default: CC = CallingConv::C; return false;
867 case lltok::kw_ccc: CC = CallingConv::C; break;
868 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
869 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
870 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
871 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000872 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
873 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
874 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000875 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000876 }
877 Lex.Lex();
878 return false;
879}
880
881/// ParseOptionalAlignment
882/// ::= /* empty */
883/// ::= 'align' 4
884bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
885 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000886 if (!EatIfPresent(lltok::kw_align))
887 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000888 LocTy AlignLoc = Lex.getLoc();
889 if (ParseUInt32(Alignment)) return true;
890 if (!isPowerOf2_32(Alignment))
891 return Error(AlignLoc, "alignment is not a power of two");
892 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000893}
894
895/// ParseOptionalCommaAlignment
896/// ::= /* empty */
897/// ::= ',' 'align' 4
898bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
899 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000900 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000901 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000902 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000903 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000904}
905
906/// ParseIndexList
907/// ::= (',' uint32)+
908bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
909 if (Lex.getKind() != lltok::comma)
910 return TokError("expected ',' as start of index list");
911
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000912 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000914 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 Indices.push_back(Idx);
916 }
917
918 return false;
919}
920
921//===----------------------------------------------------------------------===//
922// Type Parsing.
923//===----------------------------------------------------------------------===//
924
925/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000926bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
927 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000928 if (ParseTypeRec(Result)) return true;
929
930 // Verify no unresolved uprefs.
931 if (!UpRefs.empty())
932 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000933
Chris Lattnera9a9e072009-03-09 04:49:14 +0000934 if (!AllowVoid && Result.get() == Type::VoidTy)
935 return Error(TypeLoc, "void type only allowed for function results");
936
Chris Lattnerdf986172009-01-02 07:01:27 +0000937 return false;
938}
939
940/// HandleUpRefs - Every time we finish a new layer of types, this function is
941/// called. It loops through the UpRefs vector, which is a list of the
942/// currently active types. For each type, if the up-reference is contained in
943/// the newly completed type, we decrement the level count. When the level
944/// count reaches zero, the up-referenced type is the type that is passed in:
945/// thus we can complete the cycle.
946///
947PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
948 // If Ty isn't abstract, or if there are no up-references in it, then there is
949 // nothing to resolve here.
950 if (!ty->isAbstract() || UpRefs.empty()) return ty;
951
952 PATypeHolder Ty(ty);
953#if 0
954 errs() << "Type '" << Ty->getDescription()
955 << "' newly formed. Resolving upreferences.\n"
956 << UpRefs.size() << " upreferences active!\n";
957#endif
958
959 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
960 // to zero), we resolve them all together before we resolve them to Ty. At
961 // the end of the loop, if there is anything to resolve to Ty, it will be in
962 // this variable.
963 OpaqueType *TypeToResolve = 0;
964
965 for (unsigned i = 0; i != UpRefs.size(); ++i) {
966 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
967 bool ContainsType =
968 std::find(Ty->subtype_begin(), Ty->subtype_end(),
969 UpRefs[i].LastContainedTy) != Ty->subtype_end();
970
971#if 0
972 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
973 << UpRefs[i].LastContainedTy->getDescription() << ") = "
974 << (ContainsType ? "true" : "false")
975 << " level=" << UpRefs[i].NestingLevel << "\n";
976#endif
977 if (!ContainsType)
978 continue;
979
980 // Decrement level of upreference
981 unsigned Level = --UpRefs[i].NestingLevel;
982 UpRefs[i].LastContainedTy = Ty;
983
984 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
985 if (Level != 0)
986 continue;
987
988#if 0
989 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
990#endif
991 if (!TypeToResolve)
992 TypeToResolve = UpRefs[i].UpRefTy;
993 else
994 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
995 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
996 --i; // Do not skip the next element.
997 }
998
999 if (TypeToResolve)
1000 TypeToResolve->refineAbstractTypeTo(Ty);
1001
1002 return Ty;
1003}
1004
1005
1006/// ParseTypeRec - The recursive function used to process the internal
1007/// implementation details of types.
1008bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1009 switch (Lex.getKind()) {
1010 default:
1011 return TokError("expected type");
1012 case lltok::Type:
1013 // TypeRec ::= 'float' | 'void' (etc)
1014 Result = Lex.getTyVal();
1015 Lex.Lex();
1016 break;
1017 case lltok::kw_opaque:
1018 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001019 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001020 Lex.Lex();
1021 break;
1022 case lltok::lbrace:
1023 // TypeRec ::= '{' ... '}'
1024 if (ParseStructType(Result, false))
1025 return true;
1026 break;
1027 case lltok::lsquare:
1028 // TypeRec ::= '[' ... ']'
1029 Lex.Lex(); // eat the lsquare.
1030 if (ParseArrayVectorType(Result, false))
1031 return true;
1032 break;
1033 case lltok::less: // Either vector or packed struct.
1034 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001035 Lex.Lex();
1036 if (Lex.getKind() == lltok::lbrace) {
1037 if (ParseStructType(Result, true) ||
1038 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001039 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001040 } else if (ParseArrayVectorType(Result, true))
1041 return true;
1042 break;
1043 case lltok::LocalVar:
1044 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1045 // TypeRec ::= %foo
1046 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1047 Result = T;
1048 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001049 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001050 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1051 std::make_pair(Result,
1052 Lex.getLoc())));
1053 M->addTypeName(Lex.getStrVal(), Result.get());
1054 }
1055 Lex.Lex();
1056 break;
1057
1058 case lltok::LocalVarID:
1059 // TypeRec ::= %4
1060 if (Lex.getUIntVal() < NumberedTypes.size())
1061 Result = NumberedTypes[Lex.getUIntVal()];
1062 else {
1063 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1064 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1065 if (I != ForwardRefTypeIDs.end())
1066 Result = I->second.first;
1067 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001068 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001069 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1070 std::make_pair(Result,
1071 Lex.getLoc())));
1072 }
1073 }
1074 Lex.Lex();
1075 break;
1076 case lltok::backslash: {
1077 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001078 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001079 unsigned Val;
1080 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001081 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001082 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1083 Result = OT;
1084 break;
1085 }
1086 }
1087
1088 // Parse the type suffixes.
1089 while (1) {
1090 switch (Lex.getKind()) {
1091 // End of type.
1092 default: return false;
1093
1094 // TypeRec ::= TypeRec '*'
1095 case lltok::star:
1096 if (Result.get() == Type::LabelTy)
1097 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001098 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001099 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001100 if (!PointerType::isValidElementType(Result.get()))
1101 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001102 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001103 Lex.Lex();
1104 break;
1105
1106 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1107 case lltok::kw_addrspace: {
1108 if (Result.get() == Type::LabelTy)
1109 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001110 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001111 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001112 if (!PointerType::isValidElementType(Result.get()))
1113 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 unsigned AddrSpace;
1115 if (ParseOptionalAddrSpace(AddrSpace) ||
1116 ParseToken(lltok::star, "expected '*' in address space"))
1117 return true;
1118
Owen Andersonfba933c2009-07-01 23:57:11 +00001119 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 break;
1121 }
1122
1123 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1124 case lltok::lparen:
1125 if (ParseFunctionType(Result))
1126 return true;
1127 break;
1128 }
1129 }
1130}
1131
1132/// ParseParameterList
1133/// ::= '(' ')'
1134/// ::= '(' Arg (',' Arg)* ')'
1135/// Arg
1136/// ::= Type OptionalAttributes Value OptionalAttributes
1137bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1138 PerFunctionState &PFS) {
1139 if (ParseToken(lltok::lparen, "expected '(' in call"))
1140 return true;
1141
1142 while (Lex.getKind() != lltok::rparen) {
1143 // If this isn't the first argument, we need a comma.
1144 if (!ArgList.empty() &&
1145 ParseToken(lltok::comma, "expected ',' in argument list"))
1146 return true;
1147
1148 // Parse the argument.
1149 LocTy ArgLoc;
1150 PATypeHolder ArgTy(Type::VoidTy);
1151 unsigned ArgAttrs1, ArgAttrs2;
1152 Value *V;
1153 if (ParseType(ArgTy, ArgLoc) ||
1154 ParseOptionalAttrs(ArgAttrs1, 0) ||
1155 ParseValue(ArgTy, V, PFS) ||
1156 // FIXME: Should not allow attributes after the argument, remove this in
1157 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001158 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001159 return true;
1160 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1161 }
1162
1163 Lex.Lex(); // Lex the ')'.
1164 return false;
1165}
1166
1167
1168
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001169/// ParseArgumentList - Parse the argument list for a function type or function
1170/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001171/// ::= '(' ArgTypeListI ')'
1172/// ArgTypeListI
1173/// ::= /*empty*/
1174/// ::= '...'
1175/// ::= ArgTypeList ',' '...'
1176/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001177///
Chris Lattnerdf986172009-01-02 07:01:27 +00001178bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001179 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001180 isVarArg = false;
1181 assert(Lex.getKind() == lltok::lparen);
1182 Lex.Lex(); // eat the (.
1183
1184 if (Lex.getKind() == lltok::rparen) {
1185 // empty
1186 } else if (Lex.getKind() == lltok::dotdotdot) {
1187 isVarArg = true;
1188 Lex.Lex();
1189 } else {
1190 LocTy TypeLoc = Lex.getLoc();
1191 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001192 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001193 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001194
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001195 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1196 // types (such as a function returning a pointer to itself). If parsing a
1197 // function prototype, we require fully resolved types.
1198 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001199 ParseOptionalAttrs(Attrs, 0)) return true;
1200
Chris Lattnera9a9e072009-03-09 04:49:14 +00001201 if (ArgTy == Type::VoidTy)
1202 return Error(TypeLoc, "argument can not have void type");
1203
Chris Lattnerdf986172009-01-02 07:01:27 +00001204 if (Lex.getKind() == lltok::LocalVar ||
1205 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1206 Name = Lex.getStrVal();
1207 Lex.Lex();
1208 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001209
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001210 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001211 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001212
1213 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1214
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001215 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001217 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001219 break;
1220 }
1221
1222 // Otherwise must be an argument type.
1223 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001224 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001225 ParseOptionalAttrs(Attrs, 0)) return true;
1226
Chris Lattnera9a9e072009-03-09 04:49:14 +00001227 if (ArgTy == Type::VoidTy)
1228 return Error(TypeLoc, "argument can not have void type");
1229
Chris Lattnerdf986172009-01-02 07:01:27 +00001230 if (Lex.getKind() == lltok::LocalVar ||
1231 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1232 Name = Lex.getStrVal();
1233 Lex.Lex();
1234 } else {
1235 Name = "";
1236 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001237
1238 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1239 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001240
1241 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1242 }
1243 }
1244
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001245 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001246}
1247
1248/// ParseFunctionType
1249/// ::= Type ArgumentList OptionalAttrs
1250bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1251 assert(Lex.getKind() == lltok::lparen);
1252
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001253 if (!FunctionType::isValidReturnType(Result))
1254 return TokError("invalid function return type");
1255
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 std::vector<ArgInfo> ArgList;
1257 bool isVarArg;
1258 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001259 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001260 // FIXME: Allow, but ignore attributes on function types!
1261 // FIXME: Remove in LLVM 3.0
1262 ParseOptionalAttrs(Attrs, 2))
1263 return true;
1264
1265 // Reject names on the arguments lists.
1266 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1267 if (!ArgList[i].Name.empty())
1268 return Error(ArgList[i].Loc, "argument name invalid in function type");
1269 if (!ArgList[i].Attrs != 0) {
1270 // Allow but ignore attributes on function types; this permits
1271 // auto-upgrade.
1272 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1273 }
1274 }
1275
1276 std::vector<const Type*> ArgListTy;
1277 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1278 ArgListTy.push_back(ArgList[i].Type);
1279
Owen Andersonfba933c2009-07-01 23:57:11 +00001280 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1281 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001282 return false;
1283}
1284
1285/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1286/// TypeRec
1287/// ::= '{' '}'
1288/// ::= '{' TypeRec (',' TypeRec)* '}'
1289/// ::= '<' '{' '}' '>'
1290/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1291bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1292 assert(Lex.getKind() == lltok::lbrace);
1293 Lex.Lex(); // Consume the '{'
1294
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001295 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001296 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 return false;
1298 }
1299
1300 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001301 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 if (ParseTypeRec(Result)) return true;
1303 ParamsList.push_back(Result);
1304
Chris Lattnera9a9e072009-03-09 04:49:14 +00001305 if (Result == Type::VoidTy)
1306 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001307 if (!StructType::isValidElementType(Result))
1308 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001309
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001310 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001311 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001313
1314 if (Result == Type::VoidTy)
1315 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001316 if (!StructType::isValidElementType(Result))
1317 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001318
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 ParamsList.push_back(Result);
1320 }
1321
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001322 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1323 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001324
1325 std::vector<const Type*> ParamsListTy;
1326 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1327 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001328 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 return false;
1330}
1331
1332/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1333/// token has already been consumed.
1334/// TypeRec
1335/// ::= '[' APSINTVAL 'x' Types ']'
1336/// ::= '<' APSINTVAL 'x' Types '>'
1337bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1338 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1339 Lex.getAPSIntVal().getBitWidth() > 64)
1340 return TokError("expected number in address space");
1341
1342 LocTy SizeLoc = Lex.getLoc();
1343 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001344 Lex.Lex();
1345
1346 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1347 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001348
1349 LocTy TypeLoc = Lex.getLoc();
1350 PATypeHolder EltTy(Type::VoidTy);
1351 if (ParseTypeRec(EltTy)) return true;
1352
Chris Lattnera9a9e072009-03-09 04:49:14 +00001353 if (EltTy == Type::VoidTy)
1354 return Error(TypeLoc, "array and vector element type cannot be void");
1355
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001356 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1357 "expected end of sequential type"))
1358 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001359
1360 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001361 if (Size == 0)
1362 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 if ((unsigned)Size != Size)
1364 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001365 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001367 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001368 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001369 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001370 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001371 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001372 }
1373 return false;
1374}
1375
1376//===----------------------------------------------------------------------===//
1377// Function Semantic Analysis.
1378//===----------------------------------------------------------------------===//
1379
1380LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1381 : P(p), F(f) {
1382
1383 // Insert unnamed arguments into the NumberedVals list.
1384 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1385 AI != E; ++AI)
1386 if (!AI->hasName())
1387 NumberedVals.push_back(AI);
1388}
1389
1390LLParser::PerFunctionState::~PerFunctionState() {
1391 // If there were any forward referenced non-basicblock values, delete them.
1392 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1393 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1394 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001395 I->second.first->replaceAllUsesWith(
1396 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001397 delete I->second.first;
1398 I->second.first = 0;
1399 }
1400
1401 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1402 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1403 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001404 I->second.first->replaceAllUsesWith(
1405 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 delete I->second.first;
1407 I->second.first = 0;
1408 }
1409}
1410
1411bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1412 if (!ForwardRefVals.empty())
1413 return P.Error(ForwardRefVals.begin()->second.second,
1414 "use of undefined value '%" + ForwardRefVals.begin()->first +
1415 "'");
1416 if (!ForwardRefValIDs.empty())
1417 return P.Error(ForwardRefValIDs.begin()->second.second,
1418 "use of undefined value '%" +
1419 utostr(ForwardRefValIDs.begin()->first) + "'");
1420 return false;
1421}
1422
1423
1424/// GetVal - Get a value with the specified name or ID, creating a
1425/// forward reference record if needed. This can return null if the value
1426/// exists but does not have the right type.
1427Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1428 const Type *Ty, LocTy Loc) {
1429 // Look this name up in the normal function symbol table.
1430 Value *Val = F.getValueSymbolTable().lookup(Name);
1431
1432 // If this is a forward reference for the value, see if we already created a
1433 // forward ref record.
1434 if (Val == 0) {
1435 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1436 I = ForwardRefVals.find(Name);
1437 if (I != ForwardRefVals.end())
1438 Val = I->second.first;
1439 }
1440
1441 // If we have the value in the symbol table or fwd-ref table, return it.
1442 if (Val) {
1443 if (Val->getType() == Ty) return Val;
1444 if (Ty == Type::LabelTy)
1445 P.Error(Loc, "'%" + Name + "' is not a basic block");
1446 else
1447 P.Error(Loc, "'%" + Name + "' defined with type '" +
1448 Val->getType()->getDescription() + "'");
1449 return 0;
1450 }
1451
1452 // Don't make placeholders with invalid type.
1453 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1454 P.Error(Loc, "invalid use of a non-first-class type");
1455 return 0;
1456 }
1457
1458 // Otherwise, create a new forward reference for this value and remember it.
1459 Value *FwdVal;
1460 if (Ty == Type::LabelTy)
1461 FwdVal = BasicBlock::Create(Name, &F);
1462 else
1463 FwdVal = new Argument(Ty, Name);
1464
1465 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1466 return FwdVal;
1467}
1468
1469Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1470 LocTy Loc) {
1471 // Look this name up in the normal function symbol table.
1472 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1473
1474 // If this is a forward reference for the value, see if we already created a
1475 // forward ref record.
1476 if (Val == 0) {
1477 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1478 I = ForwardRefValIDs.find(ID);
1479 if (I != ForwardRefValIDs.end())
1480 Val = I->second.first;
1481 }
1482
1483 // If we have the value in the symbol table or fwd-ref table, return it.
1484 if (Val) {
1485 if (Val->getType() == Ty) return Val;
1486 if (Ty == Type::LabelTy)
1487 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1488 else
1489 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1490 Val->getType()->getDescription() + "'");
1491 return 0;
1492 }
1493
1494 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1495 P.Error(Loc, "invalid use of a non-first-class type");
1496 return 0;
1497 }
1498
1499 // Otherwise, create a new forward reference for this value and remember it.
1500 Value *FwdVal;
1501 if (Ty == Type::LabelTy)
1502 FwdVal = BasicBlock::Create("", &F);
1503 else
1504 FwdVal = new Argument(Ty);
1505
1506 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1507 return FwdVal;
1508}
1509
1510/// SetInstName - After an instruction is parsed and inserted into its
1511/// basic block, this installs its name.
1512bool LLParser::PerFunctionState::SetInstName(int NameID,
1513 const std::string &NameStr,
1514 LocTy NameLoc, Instruction *Inst) {
1515 // If this instruction has void type, it cannot have a name or ID specified.
1516 if (Inst->getType() == Type::VoidTy) {
1517 if (NameID != -1 || !NameStr.empty())
1518 return P.Error(NameLoc, "instructions returning void cannot have a name");
1519 return false;
1520 }
1521
1522 // If this was a numbered instruction, verify that the instruction is the
1523 // expected value and resolve any forward references.
1524 if (NameStr.empty()) {
1525 // If neither a name nor an ID was specified, just use the next ID.
1526 if (NameID == -1)
1527 NameID = NumberedVals.size();
1528
1529 if (unsigned(NameID) != NumberedVals.size())
1530 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1531 utostr(NumberedVals.size()) + "'");
1532
1533 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1534 ForwardRefValIDs.find(NameID);
1535 if (FI != ForwardRefValIDs.end()) {
1536 if (FI->second.first->getType() != Inst->getType())
1537 return P.Error(NameLoc, "instruction forward referenced with type '" +
1538 FI->second.first->getType()->getDescription() + "'");
1539 FI->second.first->replaceAllUsesWith(Inst);
1540 ForwardRefValIDs.erase(FI);
1541 }
1542
1543 NumberedVals.push_back(Inst);
1544 return false;
1545 }
1546
1547 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1548 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1549 FI = ForwardRefVals.find(NameStr);
1550 if (FI != ForwardRefVals.end()) {
1551 if (FI->second.first->getType() != Inst->getType())
1552 return P.Error(NameLoc, "instruction forward referenced with type '" +
1553 FI->second.first->getType()->getDescription() + "'");
1554 FI->second.first->replaceAllUsesWith(Inst);
1555 ForwardRefVals.erase(FI);
1556 }
1557
1558 // Set the name on the instruction.
1559 Inst->setName(NameStr);
1560
1561 if (Inst->getNameStr() != NameStr)
1562 return P.Error(NameLoc, "multiple definition of local value named '" +
1563 NameStr + "'");
1564 return false;
1565}
1566
1567/// GetBB - Get a basic block with the specified name or ID, creating a
1568/// forward reference record if needed.
1569BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1570 LocTy Loc) {
1571 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1572}
1573
1574BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1575 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1576}
1577
1578/// DefineBB - Define the specified basic block, which is either named or
1579/// unnamed. If there is an error, this returns null otherwise it returns
1580/// the block being defined.
1581BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1582 LocTy Loc) {
1583 BasicBlock *BB;
1584 if (Name.empty())
1585 BB = GetBB(NumberedVals.size(), Loc);
1586 else
1587 BB = GetBB(Name, Loc);
1588 if (BB == 0) return 0; // Already diagnosed error.
1589
1590 // Move the block to the end of the function. Forward ref'd blocks are
1591 // inserted wherever they happen to be referenced.
1592 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1593
1594 // Remove the block from forward ref sets.
1595 if (Name.empty()) {
1596 ForwardRefValIDs.erase(NumberedVals.size());
1597 NumberedVals.push_back(BB);
1598 } else {
1599 // BB forward references are already in the function symbol table.
1600 ForwardRefVals.erase(Name);
1601 }
1602
1603 return BB;
1604}
1605
1606//===----------------------------------------------------------------------===//
1607// Constants.
1608//===----------------------------------------------------------------------===//
1609
1610/// ParseValID - Parse an abstract value that doesn't necessarily have a
1611/// type implied. For example, if we parse "4" we don't know what integer type
1612/// it has. The value will later be combined with its type and checked for
1613/// sanity.
1614bool LLParser::ParseValID(ValID &ID) {
1615 ID.Loc = Lex.getLoc();
1616 switch (Lex.getKind()) {
1617 default: return TokError("expected value token");
1618 case lltok::GlobalID: // @42
1619 ID.UIntVal = Lex.getUIntVal();
1620 ID.Kind = ValID::t_GlobalID;
1621 break;
1622 case lltok::GlobalVar: // @foo
1623 ID.StrVal = Lex.getStrVal();
1624 ID.Kind = ValID::t_GlobalName;
1625 break;
1626 case lltok::LocalVarID: // %42
1627 ID.UIntVal = Lex.getUIntVal();
1628 ID.Kind = ValID::t_LocalID;
1629 break;
1630 case lltok::LocalVar: // %foo
1631 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1632 ID.StrVal = Lex.getStrVal();
1633 ID.Kind = ValID::t_LocalName;
1634 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001635 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1636 ID.Kind = ValID::t_Constant;
1637 Lex.Lex();
1638 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001639 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001640 if (ParseMDNodeVector(Elts) ||
1641 ParseToken(lltok::rbrace, "expected end of metadata node"))
1642 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001643
Owen Andersone951bdf2009-07-02 17:20:28 +00001644 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001645 return false;
1646 }
1647
Devang Patel923078c2009-07-01 19:21:12 +00001648 // Standalone metadata reference
1649 // !{ ..., !42, ... }
1650 unsigned MID = 0;
1651 if (!ParseUInt32(MID)) {
1652 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001653 if (I != MetadataCache.end())
1654 ID.ConstantVal = I->second;
1655 else {
1656 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1657 FI = ForwardRefMDNodes.find(MID);
1658 if (FI != ForwardRefMDNodes.end())
1659 ID.ConstantVal = FI->second.first;
1660 else {
1661 // Create MDNode forward reference
1662 SmallVector<Value *, 1> Elts;
Devang Pateld1095402009-07-08 22:25:56 +00001663 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001664 Elts.push_back(Context.getMDString(FwdRefName));
1665 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1666 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1667 ID.ConstantVal = FwdNode;
1668 }
1669 }
1670
Devang Patel923078c2009-07-01 19:21:12 +00001671 return false;
1672 }
1673
Nick Lewycky21cc4462009-04-04 07:22:01 +00001674 // MDString:
1675 // ::= '!' STRINGCONSTANT
1676 std::string Str;
1677 if (ParseStringConstant(Str)) return true;
1678
Owen Anderson12c99d82009-07-02 17:28:30 +00001679 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001680 return false;
1681 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 case lltok::APSInt:
1683 ID.APSIntVal = Lex.getAPSIntVal();
1684 ID.Kind = ValID::t_APSInt;
1685 break;
1686 case lltok::APFloat:
1687 ID.APFloatVal = Lex.getAPFloatVal();
1688 ID.Kind = ValID::t_APFloat;
1689 break;
1690 case lltok::kw_true:
Owen Andersonfba933c2009-07-01 23:57:11 +00001691 ID.ConstantVal = Context.getConstantIntTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 ID.Kind = ValID::t_Constant;
1693 break;
1694 case lltok::kw_false:
Owen Andersonfba933c2009-07-01 23:57:11 +00001695 ID.ConstantVal = Context.getConstantIntFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001696 ID.Kind = ValID::t_Constant;
1697 break;
1698 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1699 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1700 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1701
1702 case lltok::lbrace: {
1703 // ValID ::= '{' ConstVector '}'
1704 Lex.Lex();
1705 SmallVector<Constant*, 16> Elts;
1706 if (ParseGlobalValueVector(Elts) ||
1707 ParseToken(lltok::rbrace, "expected end of struct constant"))
1708 return true;
1709
Owen Andersonfba933c2009-07-01 23:57:11 +00001710 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001711 ID.Kind = ValID::t_Constant;
1712 return false;
1713 }
1714 case lltok::less: {
1715 // ValID ::= '<' ConstVector '>' --> Vector.
1716 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1717 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001718 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001719
1720 SmallVector<Constant*, 16> Elts;
1721 LocTy FirstEltLoc = Lex.getLoc();
1722 if (ParseGlobalValueVector(Elts) ||
1723 (isPackedStruct &&
1724 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1725 ParseToken(lltok::greater, "expected end of constant"))
1726 return true;
1727
1728 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001729 ID.ConstantVal =
1730 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001731 ID.Kind = ValID::t_Constant;
1732 return false;
1733 }
1734
1735 if (Elts.empty())
1736 return Error(ID.Loc, "constant vector must not be empty");
1737
1738 if (!Elts[0]->getType()->isInteger() &&
1739 !Elts[0]->getType()->isFloatingPoint())
1740 return Error(FirstEltLoc,
1741 "vector elements must have integer or floating point type");
1742
1743 // Verify that all the vector elements have the same type.
1744 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1745 if (Elts[i]->getType() != Elts[0]->getType())
1746 return Error(FirstEltLoc,
1747 "vector element #" + utostr(i) +
1748 " is not of type '" + Elts[0]->getType()->getDescription());
1749
Owen Andersonfba933c2009-07-01 23:57:11 +00001750 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001751 ID.Kind = ValID::t_Constant;
1752 return false;
1753 }
1754 case lltok::lsquare: { // Array Constant
1755 Lex.Lex();
1756 SmallVector<Constant*, 16> Elts;
1757 LocTy FirstEltLoc = Lex.getLoc();
1758 if (ParseGlobalValueVector(Elts) ||
1759 ParseToken(lltok::rsquare, "expected end of array constant"))
1760 return true;
1761
1762 // Handle empty element.
1763 if (Elts.empty()) {
1764 // Use undef instead of an array because it's inconvenient to determine
1765 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001766 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 return false;
1768 }
1769
1770 if (!Elts[0]->getType()->isFirstClassType())
1771 return Error(FirstEltLoc, "invalid array element type: " +
1772 Elts[0]->getType()->getDescription());
1773
Owen Andersonfba933c2009-07-01 23:57:11 +00001774 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001775
1776 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001777 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 if (Elts[i]->getType() != Elts[0]->getType())
1779 return Error(FirstEltLoc,
1780 "array element #" + utostr(i) +
1781 " is not of type '" +Elts[0]->getType()->getDescription());
1782 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001783
Owen Andersonfba933c2009-07-01 23:57:11 +00001784 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 ID.Kind = ValID::t_Constant;
1786 return false;
1787 }
1788 case lltok::kw_c: // c "foo"
1789 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001790 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1792 ID.Kind = ValID::t_Constant;
1793 return false;
1794
1795 case lltok::kw_asm: {
1796 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1797 bool HasSideEffect;
1798 Lex.Lex();
1799 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001800 ParseStringConstant(ID.StrVal) ||
1801 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 ParseToken(lltok::StringConstant, "expected constraint string"))
1803 return true;
1804 ID.StrVal2 = Lex.getStrVal();
1805 ID.UIntVal = HasSideEffect;
1806 ID.Kind = ValID::t_InlineAsm;
1807 return false;
1808 }
1809
1810 case lltok::kw_trunc:
1811 case lltok::kw_zext:
1812 case lltok::kw_sext:
1813 case lltok::kw_fptrunc:
1814 case lltok::kw_fpext:
1815 case lltok::kw_bitcast:
1816 case lltok::kw_uitofp:
1817 case lltok::kw_sitofp:
1818 case lltok::kw_fptoui:
1819 case lltok::kw_fptosi:
1820 case lltok::kw_inttoptr:
1821 case lltok::kw_ptrtoint: {
1822 unsigned Opc = Lex.getUIntVal();
1823 PATypeHolder DestTy(Type::VoidTy);
1824 Constant *SrcVal;
1825 Lex.Lex();
1826 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1827 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001828 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 ParseType(DestTy) ||
1830 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1831 return true;
1832 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1833 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1834 SrcVal->getType()->getDescription() + "' to '" +
1835 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001836 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1837 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 ID.Kind = ValID::t_Constant;
1839 return false;
1840 }
1841 case lltok::kw_extractvalue: {
1842 Lex.Lex();
1843 Constant *Val;
1844 SmallVector<unsigned, 4> Indices;
1845 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1846 ParseGlobalTypeAndValue(Val) ||
1847 ParseIndexList(Indices) ||
1848 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1849 return true;
1850 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1851 return Error(ID.Loc, "extractvalue operand must be array or struct");
1852 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1853 Indices.end()))
1854 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001855 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001856 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 ID.Kind = ValID::t_Constant;
1858 return false;
1859 }
1860 case lltok::kw_insertvalue: {
1861 Lex.Lex();
1862 Constant *Val0, *Val1;
1863 SmallVector<unsigned, 4> Indices;
1864 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1865 ParseGlobalTypeAndValue(Val0) ||
1866 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1867 ParseGlobalTypeAndValue(Val1) ||
1868 ParseIndexList(Indices) ||
1869 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1870 return true;
1871 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1872 return Error(ID.Loc, "extractvalue operand must be array or struct");
1873 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1874 Indices.end()))
1875 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001876 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1877 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 ID.Kind = ValID::t_Constant;
1879 return false;
1880 }
1881 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001882 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 unsigned PredVal, Opc = Lex.getUIntVal();
1884 Constant *Val0, *Val1;
1885 Lex.Lex();
1886 if (ParseCmpPredicate(PredVal, Opc) ||
1887 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1888 ParseGlobalTypeAndValue(Val0) ||
1889 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1890 ParseGlobalTypeAndValue(Val1) ||
1891 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1892 return true;
1893
1894 if (Val0->getType() != Val1->getType())
1895 return Error(ID.Loc, "compare operands must have the same type");
1896
1897 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1898
1899 if (Opc == Instruction::FCmp) {
1900 if (!Val0->getType()->isFPOrFPVector())
1901 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001902 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001903 } else {
1904 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001905 if (!Val0->getType()->isIntOrIntVector() &&
1906 !isa<PointerType>(Val0->getType()))
1907 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001908 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 }
1910 ID.Kind = ValID::t_Constant;
1911 return false;
1912 }
1913
1914 // Binary Operators.
1915 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001916 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001918 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001920 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 case lltok::kw_udiv:
1922 case lltok::kw_sdiv:
1923 case lltok::kw_fdiv:
1924 case lltok::kw_urem:
1925 case lltok::kw_srem:
1926 case lltok::kw_frem: {
1927 unsigned Opc = Lex.getUIntVal();
1928 Constant *Val0, *Val1;
1929 Lex.Lex();
1930 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1931 ParseGlobalTypeAndValue(Val0) ||
1932 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1933 ParseGlobalTypeAndValue(Val1) ||
1934 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1935 return true;
1936 if (Val0->getType() != Val1->getType())
1937 return Error(ID.Loc, "operands of constexpr must have same type");
1938 if (!Val0->getType()->isIntOrIntVector() &&
1939 !Val0->getType()->isFPOrFPVector())
1940 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001941 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 ID.Kind = ValID::t_Constant;
1943 return false;
1944 }
1945
1946 // Logical Operations
1947 case lltok::kw_shl:
1948 case lltok::kw_lshr:
1949 case lltok::kw_ashr:
1950 case lltok::kw_and:
1951 case lltok::kw_or:
1952 case lltok::kw_xor: {
1953 unsigned Opc = Lex.getUIntVal();
1954 Constant *Val0, *Val1;
1955 Lex.Lex();
1956 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1957 ParseGlobalTypeAndValue(Val0) ||
1958 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1959 ParseGlobalTypeAndValue(Val1) ||
1960 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1961 return true;
1962 if (Val0->getType() != Val1->getType())
1963 return Error(ID.Loc, "operands of constexpr must have same type");
1964 if (!Val0->getType()->isIntOrIntVector())
1965 return Error(ID.Loc,
1966 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001967 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001968 ID.Kind = ValID::t_Constant;
1969 return false;
1970 }
1971
1972 case lltok::kw_getelementptr:
1973 case lltok::kw_shufflevector:
1974 case lltok::kw_insertelement:
1975 case lltok::kw_extractelement:
1976 case lltok::kw_select: {
1977 unsigned Opc = Lex.getUIntVal();
1978 SmallVector<Constant*, 16> Elts;
1979 Lex.Lex();
1980 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1981 ParseGlobalValueVector(Elts) ||
1982 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1983 return true;
1984
1985 if (Opc == Instruction::GetElementPtr) {
1986 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1987 return Error(ID.Loc, "getelementptr requires pointer operand");
1988
1989 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1990 (Value**)&Elts[1], Elts.size()-1))
1991 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00001992 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 &Elts[1], Elts.size()-1);
1994 } else if (Opc == Instruction::Select) {
1995 if (Elts.size() != 3)
1996 return Error(ID.Loc, "expected three operands to select");
1997 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1998 Elts[2]))
1999 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00002000 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002001 } else if (Opc == Instruction::ShuffleVector) {
2002 if (Elts.size() != 3)
2003 return Error(ID.Loc, "expected three operands to shufflevector");
2004 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2005 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002006 ID.ConstantVal =
2007 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 } else if (Opc == Instruction::ExtractElement) {
2009 if (Elts.size() != 2)
2010 return Error(ID.Loc, "expected two operands to extractelement");
2011 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2012 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002013 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002014 } else {
2015 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2016 if (Elts.size() != 3)
2017 return Error(ID.Loc, "expected three operands to insertelement");
2018 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2019 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002020 ID.ConstantVal =
2021 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 }
2023
2024 ID.Kind = ValID::t_Constant;
2025 return false;
2026 }
2027 }
2028
2029 Lex.Lex();
2030 return false;
2031}
2032
2033/// ParseGlobalValue - Parse a global value with the specified type.
2034bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2035 V = 0;
2036 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002037 return ParseValID(ID) ||
2038 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002039}
2040
2041/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2042/// constant.
2043bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2044 Constant *&V) {
2045 if (isa<FunctionType>(Ty))
2046 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2047
2048 switch (ID.Kind) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002049 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002050 case ValID::t_LocalID:
2051 case ValID::t_LocalName:
2052 return Error(ID.Loc, "invalid use of function-local name");
2053 case ValID::t_InlineAsm:
2054 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2055 case ValID::t_GlobalName:
2056 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2057 return V == 0;
2058 case ValID::t_GlobalID:
2059 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2060 return V == 0;
2061 case ValID::t_APSInt:
2062 if (!isa<IntegerType>(Ty))
2063 return Error(ID.Loc, "integer constant must have integer type");
2064 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002065 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 return false;
2067 case ValID::t_APFloat:
2068 if (!Ty->isFloatingPoint() ||
2069 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2070 return Error(ID.Loc, "floating point constant invalid for type");
2071
2072 // The lexer has no type info, so builds all float and double FP constants
2073 // as double. Fix this here. Long double does not need this.
2074 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2075 Ty == Type::FloatTy) {
2076 bool Ignored;
2077 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2078 &Ignored);
2079 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002080 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002081
2082 if (V->getType() != Ty)
2083 return Error(ID.Loc, "floating point constant does not have type '" +
2084 Ty->getDescription() + "'");
2085
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 return false;
2087 case ValID::t_Null:
2088 if (!isa<PointerType>(Ty))
2089 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002090 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 return false;
2092 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002093 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002094 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2095 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002096 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002097 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002099 case ValID::t_EmptyArray:
2100 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2101 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002102 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002103 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002105 // FIXME: LabelTy should not be a first-class type.
2106 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002108 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002109 return false;
2110 case ValID::t_Constant:
2111 if (ID.ConstantVal->getType() != Ty)
2112 return Error(ID.Loc, "constant expression type mismatch");
2113 V = ID.ConstantVal;
2114 return false;
2115 }
2116}
2117
2118bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2119 PATypeHolder Type(Type::VoidTy);
2120 return ParseType(Type) ||
2121 ParseGlobalValue(Type, V);
2122}
2123
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002124/// ParseGlobalValueVector
2125/// ::= /*empty*/
2126/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002127bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2128 // Empty list.
2129 if (Lex.getKind() == lltok::rbrace ||
2130 Lex.getKind() == lltok::rsquare ||
2131 Lex.getKind() == lltok::greater ||
2132 Lex.getKind() == lltok::rparen)
2133 return false;
2134
2135 Constant *C;
2136 if (ParseGlobalTypeAndValue(C)) return true;
2137 Elts.push_back(C);
2138
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002139 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 if (ParseGlobalTypeAndValue(C)) return true;
2141 Elts.push_back(C);
2142 }
2143
2144 return false;
2145}
2146
2147
2148//===----------------------------------------------------------------------===//
2149// Function Parsing.
2150//===----------------------------------------------------------------------===//
2151
2152bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2153 PerFunctionState &PFS) {
2154 if (ID.Kind == ValID::t_LocalID)
2155 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2156 else if (ID.Kind == ValID::t_LocalName)
2157 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002158 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2160 const FunctionType *FTy =
2161 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2162 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2163 return Error(ID.Loc, "invalid type for inline asm constraint string");
2164 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2165 return false;
2166 } else {
2167 Constant *C;
2168 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2169 V = C;
2170 return false;
2171 }
2172
2173 return V == 0;
2174}
2175
2176bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2177 V = 0;
2178 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002179 return ParseValID(ID) ||
2180 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002181}
2182
2183bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2184 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002185 return ParseType(T) ||
2186 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002187}
2188
2189/// FunctionHeader
2190/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2191/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2192/// OptionalAlign OptGC
2193bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2194 // Parse the linkage.
2195 LocTy LinkageLoc = Lex.getLoc();
2196 unsigned Linkage;
2197
2198 unsigned Visibility, CC, RetAttrs;
2199 PATypeHolder RetType(Type::VoidTy);
2200 LocTy RetTypeLoc = Lex.getLoc();
2201 if (ParseOptionalLinkage(Linkage) ||
2202 ParseOptionalVisibility(Visibility) ||
2203 ParseOptionalCallingConv(CC) ||
2204 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002205 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 return true;
2207
2208 // Verify that the linkage is ok.
2209 switch ((GlobalValue::LinkageTypes)Linkage) {
2210 case GlobalValue::ExternalLinkage:
2211 break; // always ok.
2212 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002213 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002214 if (isDefine)
2215 return Error(LinkageLoc, "invalid linkage for function definition");
2216 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002217 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002218 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002220 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002221 case GlobalValue::LinkOnceAnyLinkage:
2222 case GlobalValue::LinkOnceODRLinkage:
2223 case GlobalValue::WeakAnyLinkage:
2224 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 case GlobalValue::DLLExportLinkage:
2226 if (!isDefine)
2227 return Error(LinkageLoc, "invalid linkage for function declaration");
2228 break;
2229 case GlobalValue::AppendingLinkage:
2230 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002231 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 return Error(LinkageLoc, "invalid function linkage type");
2233 }
2234
Chris Lattner99bb3152009-01-05 08:00:30 +00002235 if (!FunctionType::isValidReturnType(RetType) ||
2236 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 return Error(RetTypeLoc, "invalid function return type");
2238
Chris Lattnerdf986172009-01-02 07:01:27 +00002239 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002240
2241 std::string FunctionName;
2242 if (Lex.getKind() == lltok::GlobalVar) {
2243 FunctionName = Lex.getStrVal();
2244 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2245 unsigned NameID = Lex.getUIntVal();
2246
2247 if (NameID != NumberedVals.size())
2248 return TokError("function expected to be numbered '%" +
2249 utostr(NumberedVals.size()) + "'");
2250 } else {
2251 return TokError("expected function name");
2252 }
2253
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002254 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002255
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002256 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 return TokError("expected '(' in function argument list");
2258
2259 std::vector<ArgInfo> ArgList;
2260 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002264 std::string GC;
2265
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002266 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002267 ParseOptionalAttrs(FuncAttrs, 2) ||
2268 (EatIfPresent(lltok::kw_section) &&
2269 ParseStringConstant(Section)) ||
2270 ParseOptionalAlignment(Alignment) ||
2271 (EatIfPresent(lltok::kw_gc) &&
2272 ParseStringConstant(GC)))
2273 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002274
2275 // If the alignment was parsed as an attribute, move to the alignment field.
2276 if (FuncAttrs & Attribute::Alignment) {
2277 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2278 FuncAttrs &= ~Attribute::Alignment;
2279 }
2280
Chris Lattnerdf986172009-01-02 07:01:27 +00002281 // Okay, if we got here, the function is syntactically valid. Convert types
2282 // and do semantic checks.
2283 std::vector<const Type*> ParamTypeList;
2284 SmallVector<AttributeWithIndex, 8> Attrs;
2285 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2286 // attributes.
2287 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2288 if (FuncAttrs & ObsoleteFuncAttrs) {
2289 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2290 FuncAttrs &= ~ObsoleteFuncAttrs;
2291 }
2292
2293 if (RetAttrs != Attribute::None)
2294 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2295
2296 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2297 ParamTypeList.push_back(ArgList[i].Type);
2298 if (ArgList[i].Attrs != Attribute::None)
2299 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2300 }
2301
2302 if (FuncAttrs != Attribute::None)
2303 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2304
2305 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2306
Chris Lattnera9a9e072009-03-09 04:49:14 +00002307 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2308 RetType != Type::VoidTy)
2309 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2310
Owen Andersonfba933c2009-07-01 23:57:11 +00002311 const FunctionType *FT =
2312 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2313 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002314
2315 Fn = 0;
2316 if (!FunctionName.empty()) {
2317 // If this was a definition of a forward reference, remove the definition
2318 // from the forward reference table and fill in the forward ref.
2319 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2320 ForwardRefVals.find(FunctionName);
2321 if (FRVI != ForwardRefVals.end()) {
2322 Fn = M->getFunction(FunctionName);
2323 ForwardRefVals.erase(FRVI);
2324 } else if ((Fn = M->getFunction(FunctionName))) {
2325 // If this function already exists in the symbol table, then it is
2326 // multiply defined. We accept a few cases for old backwards compat.
2327 // FIXME: Remove this stuff for LLVM 3.0.
2328 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2329 (!Fn->isDeclaration() && isDefine)) {
2330 // If the redefinition has different type or different attributes,
2331 // reject it. If both have bodies, reject it.
2332 return Error(NameLoc, "invalid redefinition of function '" +
2333 FunctionName + "'");
2334 } else if (Fn->isDeclaration()) {
2335 // Make sure to strip off any argument names so we can't get conflicts.
2336 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2337 AI != AE; ++AI)
2338 AI->setName("");
2339 }
2340 }
2341
2342 } else if (FunctionName.empty()) {
2343 // If this is a definition of a forward referenced function, make sure the
2344 // types agree.
2345 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2346 = ForwardRefValIDs.find(NumberedVals.size());
2347 if (I != ForwardRefValIDs.end()) {
2348 Fn = cast<Function>(I->second.first);
2349 if (Fn->getType() != PFT)
2350 return Error(NameLoc, "type of definition and forward reference of '@" +
2351 utostr(NumberedVals.size()) +"' disagree");
2352 ForwardRefValIDs.erase(I);
2353 }
2354 }
2355
2356 if (Fn == 0)
2357 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2358 else // Move the forward-reference to the correct spot in the module.
2359 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2360
2361 if (FunctionName.empty())
2362 NumberedVals.push_back(Fn);
2363
2364 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2365 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2366 Fn->setCallingConv(CC);
2367 Fn->setAttributes(PAL);
2368 Fn->setAlignment(Alignment);
2369 Fn->setSection(Section);
2370 if (!GC.empty()) Fn->setGC(GC.c_str());
2371
2372 // Add all of the arguments we parsed to the function.
2373 Function::arg_iterator ArgIt = Fn->arg_begin();
2374 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2375 // If the argument has a name, insert it into the argument symbol table.
2376 if (ArgList[i].Name.empty()) continue;
2377
2378 // Set the name, if it conflicted, it will be auto-renamed.
2379 ArgIt->setName(ArgList[i].Name);
2380
2381 if (ArgIt->getNameStr() != ArgList[i].Name)
2382 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2383 ArgList[i].Name + "'");
2384 }
2385
2386 return false;
2387}
2388
2389
2390/// ParseFunctionBody
2391/// ::= '{' BasicBlock+ '}'
2392/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2393///
2394bool LLParser::ParseFunctionBody(Function &Fn) {
2395 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2396 return TokError("expected '{' in function body");
2397 Lex.Lex(); // eat the {.
2398
2399 PerFunctionState PFS(*this, Fn);
2400
2401 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2402 if (ParseBasicBlock(PFS)) return true;
2403
2404 // Eat the }.
2405 Lex.Lex();
2406
2407 // Verify function is ok.
2408 return PFS.VerifyFunctionComplete();
2409}
2410
2411/// ParseBasicBlock
2412/// ::= LabelStr? Instruction*
2413bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2414 // If this basic block starts out with a name, remember it.
2415 std::string Name;
2416 LocTy NameLoc = Lex.getLoc();
2417 if (Lex.getKind() == lltok::LabelStr) {
2418 Name = Lex.getStrVal();
2419 Lex.Lex();
2420 }
2421
2422 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2423 if (BB == 0) return true;
2424
2425 std::string NameStr;
2426
2427 // Parse the instructions in this block until we get a terminator.
2428 Instruction *Inst;
2429 do {
2430 // This instruction may have three possibilities for a name: a) none
2431 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2432 LocTy NameLoc = Lex.getLoc();
2433 int NameID = -1;
2434 NameStr = "";
2435
2436 if (Lex.getKind() == lltok::LocalVarID) {
2437 NameID = Lex.getUIntVal();
2438 Lex.Lex();
2439 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2440 return true;
2441 } else if (Lex.getKind() == lltok::LocalVar ||
2442 // FIXME: REMOVE IN LLVM 3.0
2443 Lex.getKind() == lltok::StringConstant) {
2444 NameStr = Lex.getStrVal();
2445 Lex.Lex();
2446 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2447 return true;
2448 }
2449
2450 if (ParseInstruction(Inst, BB, PFS)) return true;
2451
2452 BB->getInstList().push_back(Inst);
2453
2454 // Set the name on the instruction.
2455 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2456 } while (!isa<TerminatorInst>(Inst));
2457
2458 return false;
2459}
2460
2461//===----------------------------------------------------------------------===//
2462// Instruction Parsing.
2463//===----------------------------------------------------------------------===//
2464
2465/// ParseInstruction - Parse one of the many different instructions.
2466///
2467bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2468 PerFunctionState &PFS) {
2469 lltok::Kind Token = Lex.getKind();
2470 if (Token == lltok::Eof)
2471 return TokError("found end of file when expecting more instructions");
2472 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002473 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002474 Lex.Lex(); // Eat the keyword.
2475
2476 switch (Token) {
2477 default: return Error(Loc, "expected instruction opcode");
2478 // Terminator Instructions.
2479 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2480 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2481 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2482 case lltok::kw_br: return ParseBr(Inst, PFS);
2483 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2484 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2485 // Binary Operators.
2486 case lltok::kw_add:
2487 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002488 case lltok::kw_mul:
2489 // API compatibility: Accept either integer or floating-point types.
2490 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2491 case lltok::kw_fadd:
2492 case lltok::kw_fsub:
2493 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2494
Chris Lattnerdf986172009-01-02 07:01:27 +00002495 case lltok::kw_udiv:
2496 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002497 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002498 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002499 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002500 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002501 case lltok::kw_shl:
2502 case lltok::kw_lshr:
2503 case lltok::kw_ashr:
2504 case lltok::kw_and:
2505 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002506 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002507 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002508 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002509 // Casts.
2510 case lltok::kw_trunc:
2511 case lltok::kw_zext:
2512 case lltok::kw_sext:
2513 case lltok::kw_fptrunc:
2514 case lltok::kw_fpext:
2515 case lltok::kw_bitcast:
2516 case lltok::kw_uitofp:
2517 case lltok::kw_sitofp:
2518 case lltok::kw_fptoui:
2519 case lltok::kw_fptosi:
2520 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002521 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002522 // Other.
2523 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002524 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2526 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2527 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2528 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2529 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2530 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2531 // Memory.
2532 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002533 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002534 case lltok::kw_free: return ParseFree(Inst, PFS);
2535 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2536 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2537 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002538 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002539 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002540 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002541 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002542 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002543 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2545 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2546 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2547 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2548 }
2549}
2550
2551/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2552bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002553 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 switch (Lex.getKind()) {
2555 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2556 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2557 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2558 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2559 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2560 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2561 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2562 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2563 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2564 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2565 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2566 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2567 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2568 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2569 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2570 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2571 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2572 }
2573 } else {
2574 switch (Lex.getKind()) {
2575 default: TokError("expected icmp predicate (e.g. 'eq')");
2576 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2577 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2578 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2579 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2580 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2581 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2582 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2583 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2584 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2585 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2586 }
2587 }
2588 Lex.Lex();
2589 return false;
2590}
2591
2592//===----------------------------------------------------------------------===//
2593// Terminator Instructions.
2594//===----------------------------------------------------------------------===//
2595
2596/// ParseRet - Parse a return instruction.
2597/// ::= 'ret' void
2598/// ::= 'ret' TypeAndValue
2599/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2600bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2601 PerFunctionState &PFS) {
2602 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002603 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002604
2605 if (Ty == Type::VoidTy) {
2606 Inst = ReturnInst::Create();
2607 return false;
2608 }
2609
2610 Value *RV;
2611 if (ParseValue(Ty, RV, PFS)) return true;
2612
2613 // The normal case is one return value.
2614 if (Lex.getKind() == lltok::comma) {
2615 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2616 // of 'ret {i32,i32} {i32 1, i32 2}'
2617 SmallVector<Value*, 8> RVs;
2618 RVs.push_back(RV);
2619
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002620 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002621 if (ParseTypeAndValue(RV, PFS)) return true;
2622 RVs.push_back(RV);
2623 }
2624
Owen Andersonb43eae72009-07-02 17:04:01 +00002625 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002626 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2627 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2628 BB->getInstList().push_back(I);
2629 RV = I;
2630 }
2631 }
2632 Inst = ReturnInst::Create(RV);
2633 return false;
2634}
2635
2636
2637/// ParseBr
2638/// ::= 'br' TypeAndValue
2639/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2640bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2641 LocTy Loc, Loc2;
2642 Value *Op0, *Op1, *Op2;
2643 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2644
2645 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2646 Inst = BranchInst::Create(BB);
2647 return false;
2648 }
2649
2650 if (Op0->getType() != Type::Int1Ty)
2651 return Error(Loc, "branch condition must have 'i1' type");
2652
2653 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2654 ParseTypeAndValue(Op1, Loc, PFS) ||
2655 ParseToken(lltok::comma, "expected ',' after true destination") ||
2656 ParseTypeAndValue(Op2, Loc2, PFS))
2657 return true;
2658
2659 if (!isa<BasicBlock>(Op1))
2660 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002661 if (!isa<BasicBlock>(Op2))
2662 return Error(Loc2, "true destination of branch must be a basic block");
2663
2664 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2665 return false;
2666}
2667
2668/// ParseSwitch
2669/// Instruction
2670/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2671/// JumpTable
2672/// ::= (TypeAndValue ',' TypeAndValue)*
2673bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2674 LocTy CondLoc, BBLoc;
2675 Value *Cond, *DefaultBB;
2676 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2677 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2678 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2679 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2680 return true;
2681
2682 if (!isa<IntegerType>(Cond->getType()))
2683 return Error(CondLoc, "switch condition must have integer type");
2684 if (!isa<BasicBlock>(DefaultBB))
2685 return Error(BBLoc, "default destination must be a basic block");
2686
2687 // Parse the jump table pairs.
2688 SmallPtrSet<Value*, 32> SeenCases;
2689 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2690 while (Lex.getKind() != lltok::rsquare) {
2691 Value *Constant, *DestBB;
2692
2693 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2694 ParseToken(lltok::comma, "expected ',' after case value") ||
2695 ParseTypeAndValue(DestBB, BBLoc, PFS))
2696 return true;
2697
2698 if (!SeenCases.insert(Constant))
2699 return Error(CondLoc, "duplicate case value in switch");
2700 if (!isa<ConstantInt>(Constant))
2701 return Error(CondLoc, "case value is not a constant integer");
2702 if (!isa<BasicBlock>(DestBB))
2703 return Error(BBLoc, "case destination is not a basic block");
2704
2705 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2706 cast<BasicBlock>(DestBB)));
2707 }
2708
2709 Lex.Lex(); // Eat the ']'.
2710
2711 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2712 Table.size());
2713 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2714 SI->addCase(Table[i].first, Table[i].second);
2715 Inst = SI;
2716 return false;
2717}
2718
2719/// ParseInvoke
2720/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2721/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2722bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2723 LocTy CallLoc = Lex.getLoc();
2724 unsigned CC, RetAttrs, FnAttrs;
2725 PATypeHolder RetType(Type::VoidTy);
2726 LocTy RetTypeLoc;
2727 ValID CalleeID;
2728 SmallVector<ParamInfo, 16> ArgList;
2729
2730 Value *NormalBB, *UnwindBB;
2731 if (ParseOptionalCallingConv(CC) ||
2732 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002733 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 ParseValID(CalleeID) ||
2735 ParseParameterList(ArgList, PFS) ||
2736 ParseOptionalAttrs(FnAttrs, 2) ||
2737 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2738 ParseTypeAndValue(NormalBB, PFS) ||
2739 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2740 ParseTypeAndValue(UnwindBB, PFS))
2741 return true;
2742
2743 if (!isa<BasicBlock>(NormalBB))
2744 return Error(CallLoc, "normal destination is not a basic block");
2745 if (!isa<BasicBlock>(UnwindBB))
2746 return Error(CallLoc, "unwind destination is not a basic block");
2747
2748 // If RetType is a non-function pointer type, then this is the short syntax
2749 // for the call, which means that RetType is just the return type. Infer the
2750 // rest of the function argument types from the arguments that are present.
2751 const PointerType *PFTy = 0;
2752 const FunctionType *Ty = 0;
2753 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2754 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2755 // Pull out the types of all of the arguments...
2756 std::vector<const Type*> ParamTypes;
2757 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2758 ParamTypes.push_back(ArgList[i].V->getType());
2759
2760 if (!FunctionType::isValidReturnType(RetType))
2761 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2762
Owen Andersonfba933c2009-07-01 23:57:11 +00002763 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2764 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 }
2766
2767 // Look up the callee.
2768 Value *Callee;
2769 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2770
2771 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2772 // function attributes.
2773 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2774 if (FnAttrs & ObsoleteFuncAttrs) {
2775 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2776 FnAttrs &= ~ObsoleteFuncAttrs;
2777 }
2778
2779 // Set up the Attributes for the function.
2780 SmallVector<AttributeWithIndex, 8> Attrs;
2781 if (RetAttrs != Attribute::None)
2782 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2783
2784 SmallVector<Value*, 8> Args;
2785
2786 // Loop through FunctionType's arguments and ensure they are specified
2787 // correctly. Also, gather any parameter attributes.
2788 FunctionType::param_iterator I = Ty->param_begin();
2789 FunctionType::param_iterator E = Ty->param_end();
2790 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2791 const Type *ExpectedTy = 0;
2792 if (I != E) {
2793 ExpectedTy = *I++;
2794 } else if (!Ty->isVarArg()) {
2795 return Error(ArgList[i].Loc, "too many arguments specified");
2796 }
2797
2798 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2799 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2800 ExpectedTy->getDescription() + "'");
2801 Args.push_back(ArgList[i].V);
2802 if (ArgList[i].Attrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2804 }
2805
2806 if (I != E)
2807 return Error(CallLoc, "not enough parameters specified for call");
2808
2809 if (FnAttrs != Attribute::None)
2810 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2811
2812 // Finish off the Attributes and check them
2813 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2814
2815 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2816 cast<BasicBlock>(UnwindBB),
2817 Args.begin(), Args.end());
2818 II->setCallingConv(CC);
2819 II->setAttributes(PAL);
2820 Inst = II;
2821 return false;
2822}
2823
2824
2825
2826//===----------------------------------------------------------------------===//
2827// Binary Operators.
2828//===----------------------------------------------------------------------===//
2829
2830/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002831/// ::= ArithmeticOps TypeAndValue ',' Value
2832///
2833/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2834/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002835bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002836 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 LocTy Loc; Value *LHS, *RHS;
2838 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2839 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2840 ParseValue(LHS->getType(), RHS, PFS))
2841 return true;
2842
Chris Lattnere914b592009-01-05 08:24:46 +00002843 bool Valid;
2844 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002845 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00002846 case 0: // int or FP.
2847 Valid = LHS->getType()->isIntOrIntVector() ||
2848 LHS->getType()->isFPOrFPVector();
2849 break;
2850 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2851 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2852 }
2853
2854 if (!Valid)
2855 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002856
2857 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2858 return false;
2859}
2860
2861/// ParseLogical
2862/// ::= ArithmeticOps TypeAndValue ',' Value {
2863bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2864 unsigned Opc) {
2865 LocTy Loc; Value *LHS, *RHS;
2866 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2867 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2868 ParseValue(LHS->getType(), RHS, PFS))
2869 return true;
2870
2871 if (!LHS->getType()->isIntOrIntVector())
2872 return Error(Loc,"instruction requires integer or integer vector operands");
2873
2874 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2875 return false;
2876}
2877
2878
2879/// ParseCompare
2880/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2881/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002882bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2883 unsigned Opc) {
2884 // Parse the integer/fp comparison predicate.
2885 LocTy Loc;
2886 unsigned Pred;
2887 Value *LHS, *RHS;
2888 if (ParseCmpPredicate(Pred, Opc) ||
2889 ParseTypeAndValue(LHS, Loc, PFS) ||
2890 ParseToken(lltok::comma, "expected ',' after compare value") ||
2891 ParseValue(LHS->getType(), RHS, PFS))
2892 return true;
2893
2894 if (Opc == Instruction::FCmp) {
2895 if (!LHS->getType()->isFPOrFPVector())
2896 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002897 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002898 } else {
2899 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002900 if (!LHS->getType()->isIntOrIntVector() &&
2901 !isa<PointerType>(LHS->getType()))
2902 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002903 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002904 }
2905 return false;
2906}
2907
2908//===----------------------------------------------------------------------===//
2909// Other Instructions.
2910//===----------------------------------------------------------------------===//
2911
2912
2913/// ParseCast
2914/// ::= CastOpc TypeAndValue 'to' Type
2915bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2916 unsigned Opc) {
2917 LocTy Loc; Value *Op;
2918 PATypeHolder DestTy(Type::VoidTy);
2919 if (ParseTypeAndValue(Op, Loc, PFS) ||
2920 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2921 ParseType(DestTy))
2922 return true;
2923
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002924 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2925 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002926 return Error(Loc, "invalid cast opcode for cast from '" +
2927 Op->getType()->getDescription() + "' to '" +
2928 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002929 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2931 return false;
2932}
2933
2934/// ParseSelect
2935/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2936bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2937 LocTy Loc;
2938 Value *Op0, *Op1, *Op2;
2939 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2940 ParseToken(lltok::comma, "expected ',' after select condition") ||
2941 ParseTypeAndValue(Op1, PFS) ||
2942 ParseToken(lltok::comma, "expected ',' after select value") ||
2943 ParseTypeAndValue(Op2, PFS))
2944 return true;
2945
2946 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2947 return Error(Loc, Reason);
2948
2949 Inst = SelectInst::Create(Op0, Op1, Op2);
2950 return false;
2951}
2952
Chris Lattner0088a5c2009-01-05 08:18:44 +00002953/// ParseVA_Arg
2954/// ::= 'va_arg' TypeAndValue ',' Type
2955bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 Value *Op;
2957 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002958 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002959 if (ParseTypeAndValue(Op, PFS) ||
2960 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002961 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002963
2964 if (!EltTy->isFirstClassType())
2965 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002966
2967 Inst = new VAArgInst(Op, EltTy);
2968 return false;
2969}
2970
2971/// ParseExtractElement
2972/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2973bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2974 LocTy Loc;
2975 Value *Op0, *Op1;
2976 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2977 ParseToken(lltok::comma, "expected ',' after extract value") ||
2978 ParseTypeAndValue(Op1, PFS))
2979 return true;
2980
2981 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2982 return Error(Loc, "invalid extractelement operands");
2983
2984 Inst = new ExtractElementInst(Op0, Op1);
2985 return false;
2986}
2987
2988/// ParseInsertElement
2989/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2990bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2991 LocTy Loc;
2992 Value *Op0, *Op1, *Op2;
2993 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2994 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2995 ParseTypeAndValue(Op1, PFS) ||
2996 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2997 ParseTypeAndValue(Op2, PFS))
2998 return true;
2999
3000 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3001 return Error(Loc, "invalid extractelement operands");
3002
3003 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3004 return false;
3005}
3006
3007/// ParseShuffleVector
3008/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3009bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3010 LocTy Loc;
3011 Value *Op0, *Op1, *Op2;
3012 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3013 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3014 ParseTypeAndValue(Op1, PFS) ||
3015 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3016 ParseTypeAndValue(Op2, PFS))
3017 return true;
3018
3019 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3020 return Error(Loc, "invalid extractelement operands");
3021
3022 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3023 return false;
3024}
3025
3026/// ParsePHI
3027/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3028bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3029 PATypeHolder Ty(Type::VoidTy);
3030 Value *Op0, *Op1;
3031 LocTy TypeLoc = Lex.getLoc();
3032
3033 if (ParseType(Ty) ||
3034 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3035 ParseValue(Ty, Op0, PFS) ||
3036 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3037 ParseValue(Type::LabelTy, Op1, PFS) ||
3038 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3039 return true;
3040
3041 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3042 while (1) {
3043 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3044
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003045 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 break;
3047
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003048 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 ParseValue(Ty, Op0, PFS) ||
3050 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3051 ParseValue(Type::LabelTy, Op1, PFS) ||
3052 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3053 return true;
3054 }
3055
3056 if (!Ty->isFirstClassType())
3057 return Error(TypeLoc, "phi node must have first class type");
3058
3059 PHINode *PN = PHINode::Create(Ty);
3060 PN->reserveOperandSpace(PHIVals.size());
3061 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3062 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3063 Inst = PN;
3064 return false;
3065}
3066
3067/// ParseCall
3068/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3069/// ParameterList OptionalAttrs
3070bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3071 bool isTail) {
3072 unsigned CC, RetAttrs, FnAttrs;
3073 PATypeHolder RetType(Type::VoidTy);
3074 LocTy RetTypeLoc;
3075 ValID CalleeID;
3076 SmallVector<ParamInfo, 16> ArgList;
3077 LocTy CallLoc = Lex.getLoc();
3078
3079 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3080 ParseOptionalCallingConv(CC) ||
3081 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003082 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 ParseValID(CalleeID) ||
3084 ParseParameterList(ArgList, PFS) ||
3085 ParseOptionalAttrs(FnAttrs, 2))
3086 return true;
3087
3088 // If RetType is a non-function pointer type, then this is the short syntax
3089 // for the call, which means that RetType is just the return type. Infer the
3090 // rest of the function argument types from the arguments that are present.
3091 const PointerType *PFTy = 0;
3092 const FunctionType *Ty = 0;
3093 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3094 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3095 // Pull out the types of all of the arguments...
3096 std::vector<const Type*> ParamTypes;
3097 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3098 ParamTypes.push_back(ArgList[i].V->getType());
3099
3100 if (!FunctionType::isValidReturnType(RetType))
3101 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3102
Owen Andersonfba933c2009-07-01 23:57:11 +00003103 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3104 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003105 }
3106
3107 // Look up the callee.
3108 Value *Callee;
3109 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3110
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3112 // function attributes.
3113 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3114 if (FnAttrs & ObsoleteFuncAttrs) {
3115 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3116 FnAttrs &= ~ObsoleteFuncAttrs;
3117 }
3118
3119 // Set up the Attributes for the function.
3120 SmallVector<AttributeWithIndex, 8> Attrs;
3121 if (RetAttrs != Attribute::None)
3122 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3123
3124 SmallVector<Value*, 8> Args;
3125
3126 // Loop through FunctionType's arguments and ensure they are specified
3127 // correctly. Also, gather any parameter attributes.
3128 FunctionType::param_iterator I = Ty->param_begin();
3129 FunctionType::param_iterator E = Ty->param_end();
3130 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3131 const Type *ExpectedTy = 0;
3132 if (I != E) {
3133 ExpectedTy = *I++;
3134 } else if (!Ty->isVarArg()) {
3135 return Error(ArgList[i].Loc, "too many arguments specified");
3136 }
3137
3138 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3139 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3140 ExpectedTy->getDescription() + "'");
3141 Args.push_back(ArgList[i].V);
3142 if (ArgList[i].Attrs != Attribute::None)
3143 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3144 }
3145
3146 if (I != E)
3147 return Error(CallLoc, "not enough parameters specified for call");
3148
3149 if (FnAttrs != Attribute::None)
3150 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3151
3152 // Finish off the Attributes and check them
3153 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3154
3155 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3156 CI->setTailCall(isTail);
3157 CI->setCallingConv(CC);
3158 CI->setAttributes(PAL);
3159 Inst = CI;
3160 return false;
3161}
3162
3163//===----------------------------------------------------------------------===//
3164// Memory Instructions.
3165//===----------------------------------------------------------------------===//
3166
3167/// ParseAlloc
3168/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3169/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3170bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3171 unsigned Opc) {
3172 PATypeHolder Ty(Type::VoidTy);
3173 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003174 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003176 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003177
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003178 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 if (Lex.getKind() == lltok::kw_align) {
3180 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003181 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3182 ParseOptionalCommaAlignment(Alignment)) {
3183 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003184 }
3185 }
3186
3187 if (Size && Size->getType() != Type::Int32Ty)
3188 return Error(SizeLoc, "element count must be i32");
3189
3190 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003191 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003192 else
Owen Anderson50dead02009-07-15 23:53:25 +00003193 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 return false;
3195}
3196
3197/// ParseFree
3198/// ::= 'free' TypeAndValue
3199bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3200 Value *Val; LocTy Loc;
3201 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3202 if (!isa<PointerType>(Val->getType()))
3203 return Error(Loc, "operand to free must be a pointer");
3204 Inst = new FreeInst(Val);
3205 return false;
3206}
3207
3208/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003209/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003210bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3211 bool isVolatile) {
3212 Value *Val; LocTy Loc;
3213 unsigned Alignment;
3214 if (ParseTypeAndValue(Val, Loc, PFS) ||
3215 ParseOptionalCommaAlignment(Alignment))
3216 return true;
3217
3218 if (!isa<PointerType>(Val->getType()) ||
3219 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3220 return Error(Loc, "load operand must be a pointer to a first class type");
3221
3222 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3223 return false;
3224}
3225
3226/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003227/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003228bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3229 bool isVolatile) {
3230 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3231 unsigned Alignment;
3232 if (ParseTypeAndValue(Val, Loc, PFS) ||
3233 ParseToken(lltok::comma, "expected ',' after store operand") ||
3234 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3235 ParseOptionalCommaAlignment(Alignment))
3236 return true;
3237
3238 if (!isa<PointerType>(Ptr->getType()))
3239 return Error(PtrLoc, "store operand must be a pointer");
3240 if (!Val->getType()->isFirstClassType())
3241 return Error(Loc, "store operand must be a first class value");
3242 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3243 return Error(Loc, "stored value and pointer type do not match");
3244
3245 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3246 return false;
3247}
3248
3249/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003250/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003251/// FIXME: Remove support for getresult in LLVM 3.0
3252bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3253 Value *Val; LocTy ValLoc, EltLoc;
3254 unsigned Element;
3255 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3256 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003257 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003258 return true;
3259
3260 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3261 return Error(ValLoc, "getresult inst requires an aggregate operand");
3262 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3263 return Error(EltLoc, "invalid getresult index for value");
3264 Inst = ExtractValueInst::Create(Val, Element);
3265 return false;
3266}
3267
3268/// ParseGetElementPtr
3269/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3270bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3271 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003272 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003273
3274 if (!isa<PointerType>(Ptr->getType()))
3275 return Error(Loc, "base of getelementptr must be a pointer");
3276
3277 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003278 while (EatIfPresent(lltok::comma)) {
3279 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 if (!isa<IntegerType>(Val->getType()))
3281 return Error(EltLoc, "getelementptr index must be an integer");
3282 Indices.push_back(Val);
3283 }
3284
3285 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3286 Indices.begin(), Indices.end()))
3287 return Error(Loc, "invalid getelementptr indices");
3288 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3289 return false;
3290}
3291
3292/// ParseExtractValue
3293/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3294bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3295 Value *Val; LocTy Loc;
3296 SmallVector<unsigned, 4> Indices;
3297 if (ParseTypeAndValue(Val, Loc, PFS) ||
3298 ParseIndexList(Indices))
3299 return true;
3300
3301 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3302 return Error(Loc, "extractvalue operand must be array or struct");
3303
3304 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3305 Indices.end()))
3306 return Error(Loc, "invalid indices for extractvalue");
3307 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3308 return false;
3309}
3310
3311/// ParseInsertValue
3312/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3313bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3314 Value *Val0, *Val1; LocTy Loc0, Loc1;
3315 SmallVector<unsigned, 4> Indices;
3316 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3317 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3318 ParseTypeAndValue(Val1, Loc1, PFS) ||
3319 ParseIndexList(Indices))
3320 return true;
3321
3322 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3323 return Error(Loc0, "extractvalue operand must be array or struct");
3324
3325 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3326 Indices.end()))
3327 return Error(Loc0, "invalid indices for insertvalue");
3328 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3329 return false;
3330}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003331
3332//===----------------------------------------------------------------------===//
3333// Embedded metadata.
3334//===----------------------------------------------------------------------===//
3335
3336/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003337/// ::= Element (',' Element)*
3338/// Element
3339/// ::= 'null' | TypeAndValue
3340bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003341 assert(Lex.getKind() == lltok::lbrace);
3342 Lex.Lex();
3343 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003344 Value *V;
3345 if (Lex.getKind() == lltok::kw_null) {
3346 Lex.Lex();
3347 V = 0;
3348 } else {
3349 Constant *C;
3350 if (ParseGlobalTypeAndValue(C)) return true;
3351 V = C;
3352 }
3353 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003354 } while (EatIfPresent(lltok::comma));
3355
3356 return false;
3357}