blob: fca24607bb0e4ff89efe34c9042760fe5645be05 [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') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000126 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000127 case lltok::kw_internal: // OptionalLinkage
128 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000129 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000130 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000131 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000132 case lltok::kw_appending: // OptionalLinkage
133 case lltok::kw_dllexport: // OptionalLinkage
134 case lltok::kw_common: // OptionalLinkage
135 case lltok::kw_dllimport: // OptionalLinkage
136 case lltok::kw_extern_weak: // OptionalLinkage
137 case lltok::kw_external: { // OptionalLinkage
138 unsigned Linkage, Visibility;
139 if (ParseOptionalLinkage(Linkage) ||
140 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000141 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000142 return true;
143 break;
144 }
145 case lltok::kw_default: // OptionalVisibility
146 case lltok::kw_hidden: // OptionalVisibility
147 case lltok::kw_protected: { // OptionalVisibility
148 unsigned Visibility;
149 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000150 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000151 return true;
152 break;
153 }
154
155 case lltok::kw_thread_local: // OptionalThreadLocal
156 case lltok::kw_addrspace: // OptionalAddrSpace
157 case lltok::kw_constant: // GlobalType
158 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000159 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000160 break;
161 }
162 }
163}
164
165
166/// toplevelentity
167/// ::= 'module' 'asm' STRINGCONSTANT
168bool LLParser::ParseModuleAsm() {
169 assert(Lex.getKind() == lltok::kw_module);
170 Lex.Lex();
171
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000172 std::string AsmStr;
173 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
174 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175
176 const std::string &AsmSoFar = M->getModuleInlineAsm();
177 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000178 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000179 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000180 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 return false;
182}
183
184/// toplevelentity
185/// ::= 'target' 'triple' '=' STRINGCONSTANT
186/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
187bool LLParser::ParseTargetDefinition() {
188 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000189 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 switch (Lex.Lex()) {
191 default: return TokError("unknown target property");
192 case lltok::kw_triple:
193 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000194 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
195 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000197 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 return false;
199 case lltok::kw_datalayout:
200 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000201 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
202 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return false;
206 }
207}
208
209/// toplevelentity
210/// ::= 'deplibs' '=' '[' ']'
211/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
212bool LLParser::ParseDepLibs() {
213 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000215 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
216 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
217 return true;
218
219 if (EatIfPresent(lltok::rsquare))
220 return false;
221
222 std::string Str;
223 if (ParseStringConstant(Str)) return true;
224 M->addLibrary(Str);
225
226 while (EatIfPresent(lltok::comma)) {
227 if (ParseStringConstant(Str)) return true;
228 M->addLibrary(Str);
229 }
230
231 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000232}
233
234/// toplevelentity
235/// ::= 'type' type
236bool LLParser::ParseUnnamedType() {
237 assert(Lex.getKind() == lltok::kw_type);
238 LocTy TypeLoc = Lex.getLoc();
239 Lex.Lex(); // eat kw_type
240
241 PATypeHolder Ty(Type::VoidTy);
242 if (ParseType(Ty)) return true;
243
244 unsigned TypeID = NumberedTypes.size();
245
Chris Lattnerdf986172009-01-02 07:01:27 +0000246 // See if this type was previously referenced.
247 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
248 FI = ForwardRefTypeIDs.find(TypeID);
249 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000250 if (FI->second.first.get() == Ty)
251 return Error(TypeLoc, "self referential type is invalid");
252
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
254 Ty = FI->second.first.get();
255 ForwardRefTypeIDs.erase(FI);
256 }
257
258 NumberedTypes.push_back(Ty);
259
260 return false;
261}
262
263/// toplevelentity
264/// ::= LocalVar '=' 'type' type
265bool LLParser::ParseNamedType() {
266 std::string Name = Lex.getStrVal();
267 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000268 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000269
270 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000271
272 if (ParseToken(lltok::equal, "expected '=' after name") ||
273 ParseToken(lltok::kw_type, "expected 'type' after name") ||
274 ParseType(Ty))
275 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000276
Chris Lattnerdf986172009-01-02 07:01:27 +0000277 // Set the type name, checking for conflicts as we do so.
278 bool AlreadyExists = M->addTypeName(Name, Ty);
279 if (!AlreadyExists) return false;
280
281 // See if this type is a forward reference. We need to eagerly resolve
282 // types to allow recursive type redefinitions below.
283 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
284 FI = ForwardRefTypes.find(Name);
285 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000286 if (FI->second.first.get() == Ty)
287 return Error(NameLoc, "self referential type is invalid");
288
Chris Lattnerdf986172009-01-02 07:01:27 +0000289 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
290 Ty = FI->second.first.get();
291 ForwardRefTypes.erase(FI);
292 }
293
294 // Inserting a name that is already defined, get the existing name.
295 const Type *Existing = M->getTypeByName(Name);
296 assert(Existing && "Conflict but no matching type?!");
297
298 // Otherwise, this is an attempt to redefine a type. That's okay if
299 // the redefinition is identical to the original.
300 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
301 if (Existing == Ty) return false;
302
303 // Any other kind of (non-equivalent) redefinition is an error.
304 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
305 Ty->getDescription() + "'");
306}
307
308
309/// toplevelentity
310/// ::= 'declare' FunctionHeader
311bool LLParser::ParseDeclare() {
312 assert(Lex.getKind() == lltok::kw_declare);
313 Lex.Lex();
314
315 Function *F;
316 return ParseFunctionHeader(F, false);
317}
318
319/// toplevelentity
320/// ::= 'define' FunctionHeader '{' ...
321bool LLParser::ParseDefine() {
322 assert(Lex.getKind() == lltok::kw_define);
323 Lex.Lex();
324
325 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000326 return ParseFunctionHeader(F, true) ||
327 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000328}
329
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000330/// ParseGlobalType
331/// ::= 'constant'
332/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000333bool LLParser::ParseGlobalType(bool &IsConstant) {
334 if (Lex.getKind() == lltok::kw_constant)
335 IsConstant = true;
336 else if (Lex.getKind() == lltok::kw_global)
337 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000338 else {
339 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000341 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000342 Lex.Lex();
343 return false;
344}
345
346/// ParseNamedGlobal:
347/// GlobalVar '=' OptionalVisibility ALIAS ...
348/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
349bool LLParser::ParseNamedGlobal() {
350 assert(Lex.getKind() == lltok::GlobalVar);
351 LocTy NameLoc = Lex.getLoc();
352 std::string Name = Lex.getStrVal();
353 Lex.Lex();
354
355 bool HasLinkage;
356 unsigned Linkage, Visibility;
357 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
358 ParseOptionalLinkage(Linkage, HasLinkage) ||
359 ParseOptionalVisibility(Visibility))
360 return true;
361
362 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
363 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
364 return ParseAlias(Name, NameLoc, Visibility);
365}
366
Devang Patel923078c2009-07-01 19:21:12 +0000367/// ParseStandaloneMetadata:
368/// !42 = !{...}
369bool LLParser::ParseStandaloneMetadata() {
370 assert(Lex.getKind() == lltok::Metadata);
371 Lex.Lex();
372 unsigned MetadataID = 0;
373 if (ParseUInt32(MetadataID))
374 return true;
375 if (MetadataCache.find(MetadataID) != MetadataCache.end())
376 return TokError("Metadata id is already used");
377 if (ParseToken(lltok::equal, "expected '=' here"))
378 return true;
379
380 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000381 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000382 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000383 return true;
384
385 Constant *Init = 0;
386 if (ParseGlobalValue(Ty, Init))
387 return true;
388
389 MetadataCache[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000390 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
391 FI = ForwardRefMDNodes.find(MetadataID);
392 if (FI != ForwardRefMDNodes.end()) {
393 Constant *FwdNode = FI->second.first;
394 FwdNode->replaceAllUsesWith(Init);
395 ForwardRefMDNodes.erase(FI);
396 }
397
Devang Patel923078c2009-07-01 19:21:12 +0000398 return false;
399}
400
Chris Lattnerdf986172009-01-02 07:01:27 +0000401/// ParseAlias:
402/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
403/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000404/// ::= TypeAndValue
405/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
406/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000407///
408/// Everything through visibility has already been parsed.
409///
410bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
411 unsigned Visibility) {
412 assert(Lex.getKind() == lltok::kw_alias);
413 Lex.Lex();
414 unsigned Linkage;
415 LocTy LinkageLoc = Lex.getLoc();
416 if (ParseOptionalLinkage(Linkage))
417 return true;
418
419 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000420 Linkage != GlobalValue::WeakAnyLinkage &&
421 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000422 Linkage != GlobalValue::InternalLinkage &&
423 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000424 return Error(LinkageLoc, "invalid linkage type for alias");
425
426 Constant *Aliasee;
427 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000428 if (Lex.getKind() != lltok::kw_bitcast &&
429 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000430 if (ParseGlobalTypeAndValue(Aliasee)) return true;
431 } else {
432 // The bitcast dest type is not present, it is implied by the dest type.
433 ValID ID;
434 if (ParseValID(ID)) return true;
435 if (ID.Kind != ValID::t_Constant)
436 return Error(AliaseeLoc, "invalid aliasee");
437 Aliasee = ID.ConstantVal;
438 }
439
440 if (!isa<PointerType>(Aliasee->getType()))
441 return Error(AliaseeLoc, "alias must have pointer type");
442
443 // Okay, create the alias but do not insert it into the module yet.
444 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
445 (GlobalValue::LinkageTypes)Linkage, Name,
446 Aliasee);
447 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
448
449 // See if this value already exists in the symbol table. If so, it is either
450 // a redefinition or a definition of a forward reference.
451 if (GlobalValue *Val =
452 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
453 // See if this was a redefinition. If so, there is no entry in
454 // ForwardRefVals.
455 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
456 I = ForwardRefVals.find(Name);
457 if (I == ForwardRefVals.end())
458 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
459
460 // Otherwise, this was a definition of forward ref. Verify that types
461 // agree.
462 if (Val->getType() != GA->getType())
463 return Error(NameLoc,
464 "forward reference and definition of alias have different types");
465
466 // If they agree, just RAUW the old value with the alias and remove the
467 // forward ref info.
468 Val->replaceAllUsesWith(GA);
469 Val->eraseFromParent();
470 ForwardRefVals.erase(I);
471 }
472
473 // Insert into the module, we know its name won't collide now.
474 M->getAliasList().push_back(GA);
475 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
476
477 return false;
478}
479
480/// ParseGlobal
481/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
482/// OptionalAddrSpace GlobalType Type Const
483/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
484/// OptionalAddrSpace GlobalType Type Const
485///
486/// Everything through visibility has been parsed already.
487///
488bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
489 unsigned Linkage, bool HasLinkage,
490 unsigned Visibility) {
491 unsigned AddrSpace;
492 bool ThreadLocal, IsConstant;
493 LocTy TyLoc;
494
495 PATypeHolder Ty(Type::VoidTy);
496 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
497 ParseOptionalAddrSpace(AddrSpace) ||
498 ParseGlobalType(IsConstant) ||
499 ParseType(Ty, TyLoc))
500 return true;
501
502 // If the linkage is specified and is external, then no initializer is
503 // present.
504 Constant *Init = 0;
505 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000506 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000507 Linkage != GlobalValue::ExternalLinkage)) {
508 if (ParseGlobalValue(Ty, Init))
509 return true;
510 }
511
Chris Lattnera9a9e072009-03-09 04:49:14 +0000512 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000513 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000514
515 GlobalVariable *GV = 0;
516
517 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000518 if (!Name.empty()) {
519 if ((GV = M->getGlobalVariable(Name, true)) &&
520 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000521 return Error(NameLoc, "redefinition of global '@" + Name + "'");
522 } else {
523 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
524 I = ForwardRefValIDs.find(NumberedVals.size());
525 if (I != ForwardRefValIDs.end()) {
526 GV = cast<GlobalVariable>(I->second.first);
527 ForwardRefValIDs.erase(I);
528 }
529 }
530
531 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000532 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
533 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000534 } else {
535 if (GV->getType()->getElementType() != Ty)
536 return Error(TyLoc,
537 "forward reference and definition of global have different types");
538
539 // Move the forward-reference to the correct spot in the module.
540 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
541 }
542
543 if (Name.empty())
544 NumberedVals.push_back(GV);
545
546 // Set the parsed properties on the global.
547 if (Init)
548 GV->setInitializer(Init);
549 GV->setConstant(IsConstant);
550 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
551 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
552 GV->setThreadLocal(ThreadLocal);
553
554 // Parse attributes on the global.
555 while (Lex.getKind() == lltok::comma) {
556 Lex.Lex();
557
558 if (Lex.getKind() == lltok::kw_section) {
559 Lex.Lex();
560 GV->setSection(Lex.getStrVal());
561 if (ParseToken(lltok::StringConstant, "expected global section string"))
562 return true;
563 } else if (Lex.getKind() == lltok::kw_align) {
564 unsigned Alignment;
565 if (ParseOptionalAlignment(Alignment)) return true;
566 GV->setAlignment(Alignment);
567 } else {
568 TokError("unknown global variable property!");
569 }
570 }
571
572 return false;
573}
574
575
576//===----------------------------------------------------------------------===//
577// GlobalValue Reference/Resolution Routines.
578//===----------------------------------------------------------------------===//
579
580/// GetGlobalVal - Get a value with the specified name or ID, creating a
581/// forward reference record if needed. This can return null if the value
582/// exists but does not have the right type.
583GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
584 LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
586 if (PTy == 0) {
587 Error(Loc, "global variable reference must have pointer type");
588 return 0;
589 }
590
591 // Look this name up in the normal function symbol table.
592 GlobalValue *Val =
593 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
594
595 // If this is a forward reference for the value, see if we already created a
596 // forward ref record.
597 if (Val == 0) {
598 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
599 I = ForwardRefVals.find(Name);
600 if (I != ForwardRefVals.end())
601 Val = I->second.first;
602 }
603
604 // If we have the value in the symbol table or fwd-ref table, return it.
605 if (Val) {
606 if (Val->getType() == Ty) return Val;
607 Error(Loc, "'@" + Name + "' defined with type '" +
608 Val->getType()->getDescription() + "'");
609 return 0;
610 }
611
612 // Otherwise, create a new forward reference for this value and remember it.
613 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000614 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
615 // Function types can return opaque but functions can't.
616 if (isa<OpaqueType>(FT->getReturnType())) {
617 Error(Loc, "function may not return opaque type");
618 return 0;
619 }
620
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000622 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000623 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
624 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000625 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000626
627 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
628 return FwdVal;
629}
630
631GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
632 const PointerType *PTy = dyn_cast<PointerType>(Ty);
633 if (PTy == 0) {
634 Error(Loc, "global variable reference must have pointer type");
635 return 0;
636 }
637
638 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
639
640 // If this is a forward reference for the value, see if we already created a
641 // forward ref record.
642 if (Val == 0) {
643 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
644 I = ForwardRefValIDs.find(ID);
645 if (I != ForwardRefValIDs.end())
646 Val = I->second.first;
647 }
648
649 // If we have the value in the symbol table or fwd-ref table, return it.
650 if (Val) {
651 if (Val->getType() == Ty) return Val;
652 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
653 Val->getType()->getDescription() + "'");
654 return 0;
655 }
656
657 // Otherwise, create a new forward reference for this value and remember it.
658 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000659 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
660 // Function types can return opaque but functions can't.
661 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000662 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000663 return 0;
664 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000665 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000666 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000667 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
668 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000669 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000670
671 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
672 return FwdVal;
673}
674
675
676//===----------------------------------------------------------------------===//
677// Helper Routines.
678//===----------------------------------------------------------------------===//
679
680/// ParseToken - If the current token has the specified kind, eat it and return
681/// success. Otherwise, emit the specified error and return failure.
682bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
683 if (Lex.getKind() != T)
684 return TokError(ErrMsg);
685 Lex.Lex();
686 return false;
687}
688
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000689/// ParseStringConstant
690/// ::= StringConstant
691bool LLParser::ParseStringConstant(std::string &Result) {
692 if (Lex.getKind() != lltok::StringConstant)
693 return TokError("expected string constant");
694 Result = Lex.getStrVal();
695 Lex.Lex();
696 return false;
697}
698
699/// ParseUInt32
700/// ::= uint32
701bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000702 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
703 return TokError("expected integer");
704 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
705 if (Val64 != unsigned(Val64))
706 return TokError("expected 32-bit integer (too large)");
707 Val = Val64;
708 Lex.Lex();
709 return false;
710}
711
712
713/// ParseOptionalAddrSpace
714/// := /*empty*/
715/// := 'addrspace' '(' uint32 ')'
716bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
717 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000718 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000720 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000721 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 ParseToken(lltok::rparen, "expected ')' in address space");
723}
724
725/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
726/// indicates what kind of attribute list this is: 0: function arg, 1: result,
727/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000728/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000729bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
730 Attrs = Attribute::None;
731 LocTy AttrLoc = Lex.getLoc();
732
733 while (1) {
734 switch (Lex.getKind()) {
735 case lltok::kw_sext:
736 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000737 // Treat these as signext/zeroext if they occur in the argument list after
738 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
739 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
740 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000741 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000742 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000743 if (Lex.getKind() == lltok::kw_sext)
744 Attrs |= Attribute::SExt;
745 else
746 Attrs |= Attribute::ZExt;
747 break;
748 }
749 // FALL THROUGH.
750 default: // End of attributes.
751 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
752 return Error(AttrLoc, "invalid use of function-only attribute");
753
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000754 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000755 return Error(AttrLoc, "invalid use of parameter-only attribute");
756
757 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000758 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
759 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
760 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
761 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
762 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
763 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
764 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
765 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000766
Devang Patel578efa92009-06-05 21:57:13 +0000767 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
768 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
769 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
770 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
771 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
772 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
773 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
774 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
775 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
776 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
777 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000778
779 case lltok::kw_align: {
780 unsigned Alignment;
781 if (ParseOptionalAlignment(Alignment))
782 return true;
783 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
784 continue;
785 }
786 }
787 Lex.Lex();
788 }
789}
790
791/// ParseOptionalLinkage
792/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000793/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000794/// ::= 'internal'
795/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000796/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000797/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000798/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000799/// ::= 'appending'
800/// ::= 'dllexport'
801/// ::= 'common'
802/// ::= 'dllimport'
803/// ::= 'extern_weak'
804/// ::= 'external'
805bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
806 HasLinkage = false;
807 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000808 default: Res = GlobalValue::ExternalLinkage; return false;
809 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
810 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
811 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
812 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
813 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
814 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000815 case lltok::kw_available_externally:
816 Res = GlobalValue::AvailableExternallyLinkage;
817 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000818 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
819 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000820 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000821 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000822 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000823 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000824 }
825 Lex.Lex();
826 HasLinkage = true;
827 return false;
828}
829
830/// ParseOptionalVisibility
831/// ::= /*empty*/
832/// ::= 'default'
833/// ::= 'hidden'
834/// ::= 'protected'
835///
836bool LLParser::ParseOptionalVisibility(unsigned &Res) {
837 switch (Lex.getKind()) {
838 default: Res = GlobalValue::DefaultVisibility; return false;
839 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
840 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
841 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
842 }
843 Lex.Lex();
844 return false;
845}
846
847/// ParseOptionalCallingConv
848/// ::= /*empty*/
849/// ::= 'ccc'
850/// ::= 'fastcc'
851/// ::= 'coldcc'
852/// ::= 'x86_stdcallcc'
853/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000854/// ::= 'arm_apcscc'
855/// ::= 'arm_aapcscc'
856/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000857/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000858///
Chris Lattnerdf986172009-01-02 07:01:27 +0000859bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
860 switch (Lex.getKind()) {
861 default: CC = CallingConv::C; return false;
862 case lltok::kw_ccc: CC = CallingConv::C; break;
863 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
864 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
865 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
866 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000867 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
868 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
869 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000870 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000871 }
872 Lex.Lex();
873 return false;
874}
875
876/// ParseOptionalAlignment
877/// ::= /* empty */
878/// ::= 'align' 4
879bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
880 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000881 if (!EatIfPresent(lltok::kw_align))
882 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000883 LocTy AlignLoc = Lex.getLoc();
884 if (ParseUInt32(Alignment)) return true;
885 if (!isPowerOf2_32(Alignment))
886 return Error(AlignLoc, "alignment is not a power of two");
887 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000888}
889
890/// ParseOptionalCommaAlignment
891/// ::= /* empty */
892/// ::= ',' 'align' 4
893bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
894 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000895 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000897 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000898 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000899}
900
901/// ParseIndexList
902/// ::= (',' uint32)+
903bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
904 if (Lex.getKind() != lltok::comma)
905 return TokError("expected ',' as start of index list");
906
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000907 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000908 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000909 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 Indices.push_back(Idx);
911 }
912
913 return false;
914}
915
916//===----------------------------------------------------------------------===//
917// Type Parsing.
918//===----------------------------------------------------------------------===//
919
920/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000921bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
922 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000923 if (ParseTypeRec(Result)) return true;
924
925 // Verify no unresolved uprefs.
926 if (!UpRefs.empty())
927 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000928
Chris Lattnera9a9e072009-03-09 04:49:14 +0000929 if (!AllowVoid && Result.get() == Type::VoidTy)
930 return Error(TypeLoc, "void type only allowed for function results");
931
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 return false;
933}
934
935/// HandleUpRefs - Every time we finish a new layer of types, this function is
936/// called. It loops through the UpRefs vector, which is a list of the
937/// currently active types. For each type, if the up-reference is contained in
938/// the newly completed type, we decrement the level count. When the level
939/// count reaches zero, the up-referenced type is the type that is passed in:
940/// thus we can complete the cycle.
941///
942PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
943 // If Ty isn't abstract, or if there are no up-references in it, then there is
944 // nothing to resolve here.
945 if (!ty->isAbstract() || UpRefs.empty()) return ty;
946
947 PATypeHolder Ty(ty);
948#if 0
949 errs() << "Type '" << Ty->getDescription()
950 << "' newly formed. Resolving upreferences.\n"
951 << UpRefs.size() << " upreferences active!\n";
952#endif
953
954 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
955 // to zero), we resolve them all together before we resolve them to Ty. At
956 // the end of the loop, if there is anything to resolve to Ty, it will be in
957 // this variable.
958 OpaqueType *TypeToResolve = 0;
959
960 for (unsigned i = 0; i != UpRefs.size(); ++i) {
961 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
962 bool ContainsType =
963 std::find(Ty->subtype_begin(), Ty->subtype_end(),
964 UpRefs[i].LastContainedTy) != Ty->subtype_end();
965
966#if 0
967 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
968 << UpRefs[i].LastContainedTy->getDescription() << ") = "
969 << (ContainsType ? "true" : "false")
970 << " level=" << UpRefs[i].NestingLevel << "\n";
971#endif
972 if (!ContainsType)
973 continue;
974
975 // Decrement level of upreference
976 unsigned Level = --UpRefs[i].NestingLevel;
977 UpRefs[i].LastContainedTy = Ty;
978
979 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
980 if (Level != 0)
981 continue;
982
983#if 0
984 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
985#endif
986 if (!TypeToResolve)
987 TypeToResolve = UpRefs[i].UpRefTy;
988 else
989 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
990 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
991 --i; // Do not skip the next element.
992 }
993
994 if (TypeToResolve)
995 TypeToResolve->refineAbstractTypeTo(Ty);
996
997 return Ty;
998}
999
1000
1001/// ParseTypeRec - The recursive function used to process the internal
1002/// implementation details of types.
1003bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1004 switch (Lex.getKind()) {
1005 default:
1006 return TokError("expected type");
1007 case lltok::Type:
1008 // TypeRec ::= 'float' | 'void' (etc)
1009 Result = Lex.getTyVal();
1010 Lex.Lex();
1011 break;
1012 case lltok::kw_opaque:
1013 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001014 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001015 Lex.Lex();
1016 break;
1017 case lltok::lbrace:
1018 // TypeRec ::= '{' ... '}'
1019 if (ParseStructType(Result, false))
1020 return true;
1021 break;
1022 case lltok::lsquare:
1023 // TypeRec ::= '[' ... ']'
1024 Lex.Lex(); // eat the lsquare.
1025 if (ParseArrayVectorType(Result, false))
1026 return true;
1027 break;
1028 case lltok::less: // Either vector or packed struct.
1029 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001030 Lex.Lex();
1031 if (Lex.getKind() == lltok::lbrace) {
1032 if (ParseStructType(Result, true) ||
1033 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001034 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001035 } else if (ParseArrayVectorType(Result, true))
1036 return true;
1037 break;
1038 case lltok::LocalVar:
1039 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1040 // TypeRec ::= %foo
1041 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1042 Result = T;
1043 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001044 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001045 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1046 std::make_pair(Result,
1047 Lex.getLoc())));
1048 M->addTypeName(Lex.getStrVal(), Result.get());
1049 }
1050 Lex.Lex();
1051 break;
1052
1053 case lltok::LocalVarID:
1054 // TypeRec ::= %4
1055 if (Lex.getUIntVal() < NumberedTypes.size())
1056 Result = NumberedTypes[Lex.getUIntVal()];
1057 else {
1058 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1059 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1060 if (I != ForwardRefTypeIDs.end())
1061 Result = I->second.first;
1062 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001063 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001064 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1065 std::make_pair(Result,
1066 Lex.getLoc())));
1067 }
1068 }
1069 Lex.Lex();
1070 break;
1071 case lltok::backslash: {
1072 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001073 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001074 unsigned Val;
1075 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001076 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001077 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1078 Result = OT;
1079 break;
1080 }
1081 }
1082
1083 // Parse the type suffixes.
1084 while (1) {
1085 switch (Lex.getKind()) {
1086 // End of type.
1087 default: return false;
1088
1089 // TypeRec ::= TypeRec '*'
1090 case lltok::star:
1091 if (Result.get() == Type::LabelTy)
1092 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001093 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001094 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001095 if (!PointerType::isValidElementType(Result.get()))
1096 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001097 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001098 Lex.Lex();
1099 break;
1100
1101 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1102 case lltok::kw_addrspace: {
1103 if (Result.get() == Type::LabelTy)
1104 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001105 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001106 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001107 if (!PointerType::isValidElementType(Result.get()))
1108 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001109 unsigned AddrSpace;
1110 if (ParseOptionalAddrSpace(AddrSpace) ||
1111 ParseToken(lltok::star, "expected '*' in address space"))
1112 return true;
1113
Owen Andersonfba933c2009-07-01 23:57:11 +00001114 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 break;
1116 }
1117
1118 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1119 case lltok::lparen:
1120 if (ParseFunctionType(Result))
1121 return true;
1122 break;
1123 }
1124 }
1125}
1126
1127/// ParseParameterList
1128/// ::= '(' ')'
1129/// ::= '(' Arg (',' Arg)* ')'
1130/// Arg
1131/// ::= Type OptionalAttributes Value OptionalAttributes
1132bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1133 PerFunctionState &PFS) {
1134 if (ParseToken(lltok::lparen, "expected '(' in call"))
1135 return true;
1136
1137 while (Lex.getKind() != lltok::rparen) {
1138 // If this isn't the first argument, we need a comma.
1139 if (!ArgList.empty() &&
1140 ParseToken(lltok::comma, "expected ',' in argument list"))
1141 return true;
1142
1143 // Parse the argument.
1144 LocTy ArgLoc;
1145 PATypeHolder ArgTy(Type::VoidTy);
1146 unsigned ArgAttrs1, ArgAttrs2;
1147 Value *V;
1148 if (ParseType(ArgTy, ArgLoc) ||
1149 ParseOptionalAttrs(ArgAttrs1, 0) ||
1150 ParseValue(ArgTy, V, PFS) ||
1151 // FIXME: Should not allow attributes after the argument, remove this in
1152 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001153 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 return true;
1155 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1156 }
1157
1158 Lex.Lex(); // Lex the ')'.
1159 return false;
1160}
1161
1162
1163
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001164/// ParseArgumentList - Parse the argument list for a function type or function
1165/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001166/// ::= '(' ArgTypeListI ')'
1167/// ArgTypeListI
1168/// ::= /*empty*/
1169/// ::= '...'
1170/// ::= ArgTypeList ',' '...'
1171/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001172///
Chris Lattnerdf986172009-01-02 07:01:27 +00001173bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001174 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 isVarArg = false;
1176 assert(Lex.getKind() == lltok::lparen);
1177 Lex.Lex(); // eat the (.
1178
1179 if (Lex.getKind() == lltok::rparen) {
1180 // empty
1181 } else if (Lex.getKind() == lltok::dotdotdot) {
1182 isVarArg = true;
1183 Lex.Lex();
1184 } else {
1185 LocTy TypeLoc = Lex.getLoc();
1186 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001189
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001190 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1191 // types (such as a function returning a pointer to itself). If parsing a
1192 // function prototype, we require fully resolved types.
1193 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001194 ParseOptionalAttrs(Attrs, 0)) return true;
1195
Chris Lattnera9a9e072009-03-09 04:49:14 +00001196 if (ArgTy == Type::VoidTy)
1197 return Error(TypeLoc, "argument can not have void type");
1198
Chris Lattnerdf986172009-01-02 07:01:27 +00001199 if (Lex.getKind() == lltok::LocalVar ||
1200 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1201 Name = Lex.getStrVal();
1202 Lex.Lex();
1203 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001204
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001205 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001206 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001207
1208 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1209
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001210 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001211 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001212 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001213 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001214 break;
1215 }
1216
1217 // Otherwise must be an argument type.
1218 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001219 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001220 ParseOptionalAttrs(Attrs, 0)) return true;
1221
Chris Lattnera9a9e072009-03-09 04:49:14 +00001222 if (ArgTy == Type::VoidTy)
1223 return Error(TypeLoc, "argument can not have void type");
1224
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 if (Lex.getKind() == lltok::LocalVar ||
1226 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1227 Name = Lex.getStrVal();
1228 Lex.Lex();
1229 } else {
1230 Name = "";
1231 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001232
1233 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1234 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001235
1236 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1237 }
1238 }
1239
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001240 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001241}
1242
1243/// ParseFunctionType
1244/// ::= Type ArgumentList OptionalAttrs
1245bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1246 assert(Lex.getKind() == lltok::lparen);
1247
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001248 if (!FunctionType::isValidReturnType(Result))
1249 return TokError("invalid function return type");
1250
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 std::vector<ArgInfo> ArgList;
1252 bool isVarArg;
1253 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001254 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 // FIXME: Allow, but ignore attributes on function types!
1256 // FIXME: Remove in LLVM 3.0
1257 ParseOptionalAttrs(Attrs, 2))
1258 return true;
1259
1260 // Reject names on the arguments lists.
1261 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1262 if (!ArgList[i].Name.empty())
1263 return Error(ArgList[i].Loc, "argument name invalid in function type");
1264 if (!ArgList[i].Attrs != 0) {
1265 // Allow but ignore attributes on function types; this permits
1266 // auto-upgrade.
1267 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1268 }
1269 }
1270
1271 std::vector<const Type*> ArgListTy;
1272 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1273 ArgListTy.push_back(ArgList[i].Type);
1274
Owen Andersonfba933c2009-07-01 23:57:11 +00001275 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1276 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001277 return false;
1278}
1279
1280/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1281/// TypeRec
1282/// ::= '{' '}'
1283/// ::= '{' TypeRec (',' TypeRec)* '}'
1284/// ::= '<' '{' '}' '>'
1285/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1286bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1287 assert(Lex.getKind() == lltok::lbrace);
1288 Lex.Lex(); // Consume the '{'
1289
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001290 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001291 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 return false;
1293 }
1294
1295 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001296 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001297 if (ParseTypeRec(Result)) return true;
1298 ParamsList.push_back(Result);
1299
Chris Lattnera9a9e072009-03-09 04:49:14 +00001300 if (Result == Type::VoidTy)
1301 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001302 if (!StructType::isValidElementType(Result))
1303 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001304
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001305 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001306 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001307 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001308
1309 if (Result == Type::VoidTy)
1310 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001311 if (!StructType::isValidElementType(Result))
1312 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001313
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 ParamsList.push_back(Result);
1315 }
1316
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001317 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1318 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001319
1320 std::vector<const Type*> ParamsListTy;
1321 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1322 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001323 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 return false;
1325}
1326
1327/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1328/// token has already been consumed.
1329/// TypeRec
1330/// ::= '[' APSINTVAL 'x' Types ']'
1331/// ::= '<' APSINTVAL 'x' Types '>'
1332bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1333 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1334 Lex.getAPSIntVal().getBitWidth() > 64)
1335 return TokError("expected number in address space");
1336
1337 LocTy SizeLoc = Lex.getLoc();
1338 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001339 Lex.Lex();
1340
1341 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1342 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001343
1344 LocTy TypeLoc = Lex.getLoc();
1345 PATypeHolder EltTy(Type::VoidTy);
1346 if (ParseTypeRec(EltTy)) return true;
1347
Chris Lattnera9a9e072009-03-09 04:49:14 +00001348 if (EltTy == Type::VoidTy)
1349 return Error(TypeLoc, "array and vector element type cannot be void");
1350
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001351 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1352 "expected end of sequential type"))
1353 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001354
1355 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001356 if (Size == 0)
1357 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001358 if ((unsigned)Size != Size)
1359 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001360 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001362 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001364 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001366 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001367 }
1368 return false;
1369}
1370
1371//===----------------------------------------------------------------------===//
1372// Function Semantic Analysis.
1373//===----------------------------------------------------------------------===//
1374
1375LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1376 : P(p), F(f) {
1377
1378 // Insert unnamed arguments into the NumberedVals list.
1379 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1380 AI != E; ++AI)
1381 if (!AI->hasName())
1382 NumberedVals.push_back(AI);
1383}
1384
1385LLParser::PerFunctionState::~PerFunctionState() {
1386 // If there were any forward referenced non-basicblock values, delete them.
1387 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1388 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1389 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001390 I->second.first->replaceAllUsesWith(
1391 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001392 delete I->second.first;
1393 I->second.first = 0;
1394 }
1395
1396 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1397 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1398 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001399 I->second.first->replaceAllUsesWith(
1400 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 delete I->second.first;
1402 I->second.first = 0;
1403 }
1404}
1405
1406bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1407 if (!ForwardRefVals.empty())
1408 return P.Error(ForwardRefVals.begin()->second.second,
1409 "use of undefined value '%" + ForwardRefVals.begin()->first +
1410 "'");
1411 if (!ForwardRefValIDs.empty())
1412 return P.Error(ForwardRefValIDs.begin()->second.second,
1413 "use of undefined value '%" +
1414 utostr(ForwardRefValIDs.begin()->first) + "'");
1415 return false;
1416}
1417
1418
1419/// GetVal - Get a value with the specified name or ID, creating a
1420/// forward reference record if needed. This can return null if the value
1421/// exists but does not have the right type.
1422Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1423 const Type *Ty, LocTy Loc) {
1424 // Look this name up in the normal function symbol table.
1425 Value *Val = F.getValueSymbolTable().lookup(Name);
1426
1427 // If this is a forward reference for the value, see if we already created a
1428 // forward ref record.
1429 if (Val == 0) {
1430 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1431 I = ForwardRefVals.find(Name);
1432 if (I != ForwardRefVals.end())
1433 Val = I->second.first;
1434 }
1435
1436 // If we have the value in the symbol table or fwd-ref table, return it.
1437 if (Val) {
1438 if (Val->getType() == Ty) return Val;
1439 if (Ty == Type::LabelTy)
1440 P.Error(Loc, "'%" + Name + "' is not a basic block");
1441 else
1442 P.Error(Loc, "'%" + Name + "' defined with type '" +
1443 Val->getType()->getDescription() + "'");
1444 return 0;
1445 }
1446
1447 // Don't make placeholders with invalid type.
1448 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1449 P.Error(Loc, "invalid use of a non-first-class type");
1450 return 0;
1451 }
1452
1453 // Otherwise, create a new forward reference for this value and remember it.
1454 Value *FwdVal;
1455 if (Ty == Type::LabelTy)
1456 FwdVal = BasicBlock::Create(Name, &F);
1457 else
1458 FwdVal = new Argument(Ty, Name);
1459
1460 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1461 return FwdVal;
1462}
1463
1464Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1465 LocTy Loc) {
1466 // Look this name up in the normal function symbol table.
1467 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1468
1469 // If this is a forward reference for the value, see if we already created a
1470 // forward ref record.
1471 if (Val == 0) {
1472 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1473 I = ForwardRefValIDs.find(ID);
1474 if (I != ForwardRefValIDs.end())
1475 Val = I->second.first;
1476 }
1477
1478 // If we have the value in the symbol table or fwd-ref table, return it.
1479 if (Val) {
1480 if (Val->getType() == Ty) return Val;
1481 if (Ty == Type::LabelTy)
1482 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1483 else
1484 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1485 Val->getType()->getDescription() + "'");
1486 return 0;
1487 }
1488
1489 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1490 P.Error(Loc, "invalid use of a non-first-class type");
1491 return 0;
1492 }
1493
1494 // Otherwise, create a new forward reference for this value and remember it.
1495 Value *FwdVal;
1496 if (Ty == Type::LabelTy)
1497 FwdVal = BasicBlock::Create("", &F);
1498 else
1499 FwdVal = new Argument(Ty);
1500
1501 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1502 return FwdVal;
1503}
1504
1505/// SetInstName - After an instruction is parsed and inserted into its
1506/// basic block, this installs its name.
1507bool LLParser::PerFunctionState::SetInstName(int NameID,
1508 const std::string &NameStr,
1509 LocTy NameLoc, Instruction *Inst) {
1510 // If this instruction has void type, it cannot have a name or ID specified.
1511 if (Inst->getType() == Type::VoidTy) {
1512 if (NameID != -1 || !NameStr.empty())
1513 return P.Error(NameLoc, "instructions returning void cannot have a name");
1514 return false;
1515 }
1516
1517 // If this was a numbered instruction, verify that the instruction is the
1518 // expected value and resolve any forward references.
1519 if (NameStr.empty()) {
1520 // If neither a name nor an ID was specified, just use the next ID.
1521 if (NameID == -1)
1522 NameID = NumberedVals.size();
1523
1524 if (unsigned(NameID) != NumberedVals.size())
1525 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1526 utostr(NumberedVals.size()) + "'");
1527
1528 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1529 ForwardRefValIDs.find(NameID);
1530 if (FI != ForwardRefValIDs.end()) {
1531 if (FI->second.first->getType() != Inst->getType())
1532 return P.Error(NameLoc, "instruction forward referenced with type '" +
1533 FI->second.first->getType()->getDescription() + "'");
1534 FI->second.first->replaceAllUsesWith(Inst);
1535 ForwardRefValIDs.erase(FI);
1536 }
1537
1538 NumberedVals.push_back(Inst);
1539 return false;
1540 }
1541
1542 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1543 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1544 FI = ForwardRefVals.find(NameStr);
1545 if (FI != ForwardRefVals.end()) {
1546 if (FI->second.first->getType() != Inst->getType())
1547 return P.Error(NameLoc, "instruction forward referenced with type '" +
1548 FI->second.first->getType()->getDescription() + "'");
1549 FI->second.first->replaceAllUsesWith(Inst);
1550 ForwardRefVals.erase(FI);
1551 }
1552
1553 // Set the name on the instruction.
1554 Inst->setName(NameStr);
1555
1556 if (Inst->getNameStr() != NameStr)
1557 return P.Error(NameLoc, "multiple definition of local value named '" +
1558 NameStr + "'");
1559 return false;
1560}
1561
1562/// GetBB - Get a basic block with the specified name or ID, creating a
1563/// forward reference record if needed.
1564BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1565 LocTy Loc) {
1566 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1567}
1568
1569BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1570 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1571}
1572
1573/// DefineBB - Define the specified basic block, which is either named or
1574/// unnamed. If there is an error, this returns null otherwise it returns
1575/// the block being defined.
1576BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1577 LocTy Loc) {
1578 BasicBlock *BB;
1579 if (Name.empty())
1580 BB = GetBB(NumberedVals.size(), Loc);
1581 else
1582 BB = GetBB(Name, Loc);
1583 if (BB == 0) return 0; // Already diagnosed error.
1584
1585 // Move the block to the end of the function. Forward ref'd blocks are
1586 // inserted wherever they happen to be referenced.
1587 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1588
1589 // Remove the block from forward ref sets.
1590 if (Name.empty()) {
1591 ForwardRefValIDs.erase(NumberedVals.size());
1592 NumberedVals.push_back(BB);
1593 } else {
1594 // BB forward references are already in the function symbol table.
1595 ForwardRefVals.erase(Name);
1596 }
1597
1598 return BB;
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// Constants.
1603//===----------------------------------------------------------------------===//
1604
1605/// ParseValID - Parse an abstract value that doesn't necessarily have a
1606/// type implied. For example, if we parse "4" we don't know what integer type
1607/// it has. The value will later be combined with its type and checked for
1608/// sanity.
1609bool LLParser::ParseValID(ValID &ID) {
1610 ID.Loc = Lex.getLoc();
1611 switch (Lex.getKind()) {
1612 default: return TokError("expected value token");
1613 case lltok::GlobalID: // @42
1614 ID.UIntVal = Lex.getUIntVal();
1615 ID.Kind = ValID::t_GlobalID;
1616 break;
1617 case lltok::GlobalVar: // @foo
1618 ID.StrVal = Lex.getStrVal();
1619 ID.Kind = ValID::t_GlobalName;
1620 break;
1621 case lltok::LocalVarID: // %42
1622 ID.UIntVal = Lex.getUIntVal();
1623 ID.Kind = ValID::t_LocalID;
1624 break;
1625 case lltok::LocalVar: // %foo
1626 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1627 ID.StrVal = Lex.getStrVal();
1628 ID.Kind = ValID::t_LocalName;
1629 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001630 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1631 ID.Kind = ValID::t_Constant;
1632 Lex.Lex();
1633 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001634 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001635 if (ParseMDNodeVector(Elts) ||
1636 ParseToken(lltok::rbrace, "expected end of metadata node"))
1637 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001638
Owen Andersone951bdf2009-07-02 17:20:28 +00001639 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001640 return false;
1641 }
1642
Devang Patel923078c2009-07-01 19:21:12 +00001643 // Standalone metadata reference
1644 // !{ ..., !42, ... }
1645 unsigned MID = 0;
1646 if (!ParseUInt32(MID)) {
1647 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001648 if (I != MetadataCache.end())
1649 ID.ConstantVal = I->second;
1650 else {
1651 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1652 FI = ForwardRefMDNodes.find(MID);
1653 if (FI != ForwardRefMDNodes.end())
1654 ID.ConstantVal = FI->second.first;
1655 else {
1656 // Create MDNode forward reference
1657 SmallVector<Value *, 1> Elts;
Devang Pateld1095402009-07-08 22:25:56 +00001658 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001659 Elts.push_back(Context.getMDString(FwdRefName));
1660 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1661 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1662 ID.ConstantVal = FwdNode;
1663 }
1664 }
1665
Devang Patel923078c2009-07-01 19:21:12 +00001666 return false;
1667 }
1668
Nick Lewycky21cc4462009-04-04 07:22:01 +00001669 // MDString:
1670 // ::= '!' STRINGCONSTANT
1671 std::string Str;
1672 if (ParseStringConstant(Str)) return true;
1673
Owen Anderson12c99d82009-07-02 17:28:30 +00001674 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001675 return false;
1676 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001677 case lltok::APSInt:
1678 ID.APSIntVal = Lex.getAPSIntVal();
1679 ID.Kind = ValID::t_APSInt;
1680 break;
1681 case lltok::APFloat:
1682 ID.APFloatVal = Lex.getAPFloatVal();
1683 ID.Kind = ValID::t_APFloat;
1684 break;
1685 case lltok::kw_true:
Owen Andersonfba933c2009-07-01 23:57:11 +00001686 ID.ConstantVal = Context.getConstantIntTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001687 ID.Kind = ValID::t_Constant;
1688 break;
1689 case lltok::kw_false:
Owen Andersonfba933c2009-07-01 23:57:11 +00001690 ID.ConstantVal = Context.getConstantIntFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 ID.Kind = ValID::t_Constant;
1692 break;
1693 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1694 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1695 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1696
1697 case lltok::lbrace: {
1698 // ValID ::= '{' ConstVector '}'
1699 Lex.Lex();
1700 SmallVector<Constant*, 16> Elts;
1701 if (ParseGlobalValueVector(Elts) ||
1702 ParseToken(lltok::rbrace, "expected end of struct constant"))
1703 return true;
1704
Owen Andersonfba933c2009-07-01 23:57:11 +00001705 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 ID.Kind = ValID::t_Constant;
1707 return false;
1708 }
1709 case lltok::less: {
1710 // ValID ::= '<' ConstVector '>' --> Vector.
1711 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1712 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001713 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001714
1715 SmallVector<Constant*, 16> Elts;
1716 LocTy FirstEltLoc = Lex.getLoc();
1717 if (ParseGlobalValueVector(Elts) ||
1718 (isPackedStruct &&
1719 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1720 ParseToken(lltok::greater, "expected end of constant"))
1721 return true;
1722
1723 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001724 ID.ConstantVal =
1725 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 ID.Kind = ValID::t_Constant;
1727 return false;
1728 }
1729
1730 if (Elts.empty())
1731 return Error(ID.Loc, "constant vector must not be empty");
1732
1733 if (!Elts[0]->getType()->isInteger() &&
1734 !Elts[0]->getType()->isFloatingPoint())
1735 return Error(FirstEltLoc,
1736 "vector elements must have integer or floating point type");
1737
1738 // Verify that all the vector elements have the same type.
1739 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1740 if (Elts[i]->getType() != Elts[0]->getType())
1741 return Error(FirstEltLoc,
1742 "vector element #" + utostr(i) +
1743 " is not of type '" + Elts[0]->getType()->getDescription());
1744
Owen Andersonfba933c2009-07-01 23:57:11 +00001745 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 ID.Kind = ValID::t_Constant;
1747 return false;
1748 }
1749 case lltok::lsquare: { // Array Constant
1750 Lex.Lex();
1751 SmallVector<Constant*, 16> Elts;
1752 LocTy FirstEltLoc = Lex.getLoc();
1753 if (ParseGlobalValueVector(Elts) ||
1754 ParseToken(lltok::rsquare, "expected end of array constant"))
1755 return true;
1756
1757 // Handle empty element.
1758 if (Elts.empty()) {
1759 // Use undef instead of an array because it's inconvenient to determine
1760 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001761 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 return false;
1763 }
1764
1765 if (!Elts[0]->getType()->isFirstClassType())
1766 return Error(FirstEltLoc, "invalid array element type: " +
1767 Elts[0]->getType()->getDescription());
1768
Owen Andersonfba933c2009-07-01 23:57:11 +00001769 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001770
1771 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001772 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001773 if (Elts[i]->getType() != Elts[0]->getType())
1774 return Error(FirstEltLoc,
1775 "array element #" + utostr(i) +
1776 " is not of type '" +Elts[0]->getType()->getDescription());
1777 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001778
Owen Andersonfba933c2009-07-01 23:57:11 +00001779 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001780 ID.Kind = ValID::t_Constant;
1781 return false;
1782 }
1783 case lltok::kw_c: // c "foo"
1784 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001785 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1787 ID.Kind = ValID::t_Constant;
1788 return false;
1789
1790 case lltok::kw_asm: {
1791 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1792 bool HasSideEffect;
1793 Lex.Lex();
1794 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001795 ParseStringConstant(ID.StrVal) ||
1796 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 ParseToken(lltok::StringConstant, "expected constraint string"))
1798 return true;
1799 ID.StrVal2 = Lex.getStrVal();
1800 ID.UIntVal = HasSideEffect;
1801 ID.Kind = ValID::t_InlineAsm;
1802 return false;
1803 }
1804
1805 case lltok::kw_trunc:
1806 case lltok::kw_zext:
1807 case lltok::kw_sext:
1808 case lltok::kw_fptrunc:
1809 case lltok::kw_fpext:
1810 case lltok::kw_bitcast:
1811 case lltok::kw_uitofp:
1812 case lltok::kw_sitofp:
1813 case lltok::kw_fptoui:
1814 case lltok::kw_fptosi:
1815 case lltok::kw_inttoptr:
1816 case lltok::kw_ptrtoint: {
1817 unsigned Opc = Lex.getUIntVal();
1818 PATypeHolder DestTy(Type::VoidTy);
1819 Constant *SrcVal;
1820 Lex.Lex();
1821 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1822 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001823 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 ParseType(DestTy) ||
1825 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1826 return true;
1827 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1828 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1829 SrcVal->getType()->getDescription() + "' to '" +
1830 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001831 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1832 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001833 ID.Kind = ValID::t_Constant;
1834 return false;
1835 }
1836 case lltok::kw_extractvalue: {
1837 Lex.Lex();
1838 Constant *Val;
1839 SmallVector<unsigned, 4> Indices;
1840 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1841 ParseGlobalTypeAndValue(Val) ||
1842 ParseIndexList(Indices) ||
1843 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1844 return true;
1845 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1846 return Error(ID.Loc, "extractvalue operand must be array or struct");
1847 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1848 Indices.end()))
1849 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001850 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001851 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 ID.Kind = ValID::t_Constant;
1853 return false;
1854 }
1855 case lltok::kw_insertvalue: {
1856 Lex.Lex();
1857 Constant *Val0, *Val1;
1858 SmallVector<unsigned, 4> Indices;
1859 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1860 ParseGlobalTypeAndValue(Val0) ||
1861 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1862 ParseGlobalTypeAndValue(Val1) ||
1863 ParseIndexList(Indices) ||
1864 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1865 return true;
1866 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1867 return Error(ID.Loc, "extractvalue operand must be array or struct");
1868 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1869 Indices.end()))
1870 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001871 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1872 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 ID.Kind = ValID::t_Constant;
1874 return false;
1875 }
1876 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001877 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001878 unsigned PredVal, Opc = Lex.getUIntVal();
1879 Constant *Val0, *Val1;
1880 Lex.Lex();
1881 if (ParseCmpPredicate(PredVal, Opc) ||
1882 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1883 ParseGlobalTypeAndValue(Val0) ||
1884 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1885 ParseGlobalTypeAndValue(Val1) ||
1886 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1887 return true;
1888
1889 if (Val0->getType() != Val1->getType())
1890 return Error(ID.Loc, "compare operands must have the same type");
1891
1892 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1893
1894 if (Opc == Instruction::FCmp) {
1895 if (!Val0->getType()->isFPOrFPVector())
1896 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001897 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001898 } else {
1899 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 if (!Val0->getType()->isIntOrIntVector() &&
1901 !isa<PointerType>(Val0->getType()))
1902 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001903 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001904 }
1905 ID.Kind = ValID::t_Constant;
1906 return false;
1907 }
1908
1909 // Binary Operators.
1910 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001911 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001913 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001915 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 case lltok::kw_udiv:
1917 case lltok::kw_sdiv:
1918 case lltok::kw_fdiv:
1919 case lltok::kw_urem:
1920 case lltok::kw_srem:
1921 case lltok::kw_frem: {
1922 unsigned Opc = Lex.getUIntVal();
1923 Constant *Val0, *Val1;
1924 Lex.Lex();
1925 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1926 ParseGlobalTypeAndValue(Val0) ||
1927 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1928 ParseGlobalTypeAndValue(Val1) ||
1929 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1930 return true;
1931 if (Val0->getType() != Val1->getType())
1932 return Error(ID.Loc, "operands of constexpr must have same type");
1933 if (!Val0->getType()->isIntOrIntVector() &&
1934 !Val0->getType()->isFPOrFPVector())
1935 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001936 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 ID.Kind = ValID::t_Constant;
1938 return false;
1939 }
1940
1941 // Logical Operations
1942 case lltok::kw_shl:
1943 case lltok::kw_lshr:
1944 case lltok::kw_ashr:
1945 case lltok::kw_and:
1946 case lltok::kw_or:
1947 case lltok::kw_xor: {
1948 unsigned Opc = Lex.getUIntVal();
1949 Constant *Val0, *Val1;
1950 Lex.Lex();
1951 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1952 ParseGlobalTypeAndValue(Val0) ||
1953 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1954 ParseGlobalTypeAndValue(Val1) ||
1955 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1956 return true;
1957 if (Val0->getType() != Val1->getType())
1958 return Error(ID.Loc, "operands of constexpr must have same type");
1959 if (!Val0->getType()->isIntOrIntVector())
1960 return Error(ID.Loc,
1961 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001962 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001963 ID.Kind = ValID::t_Constant;
1964 return false;
1965 }
1966
1967 case lltok::kw_getelementptr:
1968 case lltok::kw_shufflevector:
1969 case lltok::kw_insertelement:
1970 case lltok::kw_extractelement:
1971 case lltok::kw_select: {
1972 unsigned Opc = Lex.getUIntVal();
1973 SmallVector<Constant*, 16> Elts;
1974 Lex.Lex();
1975 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1976 ParseGlobalValueVector(Elts) ||
1977 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1978 return true;
1979
1980 if (Opc == Instruction::GetElementPtr) {
1981 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1982 return Error(ID.Loc, "getelementptr requires pointer operand");
1983
1984 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1985 (Value**)&Elts[1], Elts.size()-1))
1986 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00001987 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00001988 &Elts[1], Elts.size()-1);
1989 } else if (Opc == Instruction::Select) {
1990 if (Elts.size() != 3)
1991 return Error(ID.Loc, "expected three operands to select");
1992 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1993 Elts[2]))
1994 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00001995 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001996 } else if (Opc == Instruction::ShuffleVector) {
1997 if (Elts.size() != 3)
1998 return Error(ID.Loc, "expected three operands to shufflevector");
1999 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2000 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002001 ID.ConstantVal =
2002 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 } else if (Opc == Instruction::ExtractElement) {
2004 if (Elts.size() != 2)
2005 return Error(ID.Loc, "expected two operands to extractelement");
2006 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2007 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002008 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 } else {
2010 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2011 if (Elts.size() != 3)
2012 return Error(ID.Loc, "expected three operands to insertelement");
2013 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2014 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002015 ID.ConstantVal =
2016 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 }
2018
2019 ID.Kind = ValID::t_Constant;
2020 return false;
2021 }
2022 }
2023
2024 Lex.Lex();
2025 return false;
2026}
2027
2028/// ParseGlobalValue - Parse a global value with the specified type.
2029bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2030 V = 0;
2031 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002032 return ParseValID(ID) ||
2033 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002034}
2035
2036/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2037/// constant.
2038bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2039 Constant *&V) {
2040 if (isa<FunctionType>(Ty))
2041 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2042
2043 switch (ID.Kind) {
Torok Edwinc25e7582009-07-11 20:10:48 +00002044 default: LLVM_UNREACHABLE("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002045 case ValID::t_LocalID:
2046 case ValID::t_LocalName:
2047 return Error(ID.Loc, "invalid use of function-local name");
2048 case ValID::t_InlineAsm:
2049 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2050 case ValID::t_GlobalName:
2051 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2052 return V == 0;
2053 case ValID::t_GlobalID:
2054 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2055 return V == 0;
2056 case ValID::t_APSInt:
2057 if (!isa<IntegerType>(Ty))
2058 return Error(ID.Loc, "integer constant must have integer type");
2059 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002060 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 return false;
2062 case ValID::t_APFloat:
2063 if (!Ty->isFloatingPoint() ||
2064 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2065 return Error(ID.Loc, "floating point constant invalid for type");
2066
2067 // The lexer has no type info, so builds all float and double FP constants
2068 // as double. Fix this here. Long double does not need this.
2069 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2070 Ty == Type::FloatTy) {
2071 bool Ignored;
2072 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2073 &Ignored);
2074 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002075 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002076
2077 if (V->getType() != Ty)
2078 return Error(ID.Loc, "floating point constant does not have type '" +
2079 Ty->getDescription() + "'");
2080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 return false;
2082 case ValID::t_Null:
2083 if (!isa<PointerType>(Ty))
2084 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002085 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 return false;
2087 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002088 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002089 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2090 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002091 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002092 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002093 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002094 case ValID::t_EmptyArray:
2095 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2096 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002097 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002098 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002100 // FIXME: LabelTy should not be a first-class type.
2101 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002103 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 return false;
2105 case ValID::t_Constant:
2106 if (ID.ConstantVal->getType() != Ty)
2107 return Error(ID.Loc, "constant expression type mismatch");
2108 V = ID.ConstantVal;
2109 return false;
2110 }
2111}
2112
2113bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2114 PATypeHolder Type(Type::VoidTy);
2115 return ParseType(Type) ||
2116 ParseGlobalValue(Type, V);
2117}
2118
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002119/// ParseGlobalValueVector
2120/// ::= /*empty*/
2121/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002122bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2123 // Empty list.
2124 if (Lex.getKind() == lltok::rbrace ||
2125 Lex.getKind() == lltok::rsquare ||
2126 Lex.getKind() == lltok::greater ||
2127 Lex.getKind() == lltok::rparen)
2128 return false;
2129
2130 Constant *C;
2131 if (ParseGlobalTypeAndValue(C)) return true;
2132 Elts.push_back(C);
2133
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002134 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 if (ParseGlobalTypeAndValue(C)) return true;
2136 Elts.push_back(C);
2137 }
2138
2139 return false;
2140}
2141
2142
2143//===----------------------------------------------------------------------===//
2144// Function Parsing.
2145//===----------------------------------------------------------------------===//
2146
2147bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2148 PerFunctionState &PFS) {
2149 if (ID.Kind == ValID::t_LocalID)
2150 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2151 else if (ID.Kind == ValID::t_LocalName)
2152 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002153 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2155 const FunctionType *FTy =
2156 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2157 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2158 return Error(ID.Loc, "invalid type for inline asm constraint string");
2159 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2160 return false;
2161 } else {
2162 Constant *C;
2163 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2164 V = C;
2165 return false;
2166 }
2167
2168 return V == 0;
2169}
2170
2171bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2172 V = 0;
2173 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002174 return ParseValID(ID) ||
2175 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002176}
2177
2178bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2179 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002180 return ParseType(T) ||
2181 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002182}
2183
2184/// FunctionHeader
2185/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2186/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2187/// OptionalAlign OptGC
2188bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2189 // Parse the linkage.
2190 LocTy LinkageLoc = Lex.getLoc();
2191 unsigned Linkage;
2192
2193 unsigned Visibility, CC, RetAttrs;
2194 PATypeHolder RetType(Type::VoidTy);
2195 LocTy RetTypeLoc = Lex.getLoc();
2196 if (ParseOptionalLinkage(Linkage) ||
2197 ParseOptionalVisibility(Visibility) ||
2198 ParseOptionalCallingConv(CC) ||
2199 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002200 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 return true;
2202
2203 // Verify that the linkage is ok.
2204 switch ((GlobalValue::LinkageTypes)Linkage) {
2205 case GlobalValue::ExternalLinkage:
2206 break; // always ok.
2207 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002208 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002209 if (isDefine)
2210 return Error(LinkageLoc, "invalid linkage for function definition");
2211 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002212 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002214 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002215 case GlobalValue::LinkOnceAnyLinkage:
2216 case GlobalValue::LinkOnceODRLinkage:
2217 case GlobalValue::WeakAnyLinkage:
2218 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002219 case GlobalValue::DLLExportLinkage:
2220 if (!isDefine)
2221 return Error(LinkageLoc, "invalid linkage for function declaration");
2222 break;
2223 case GlobalValue::AppendingLinkage:
2224 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002225 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002226 return Error(LinkageLoc, "invalid function linkage type");
2227 }
2228
Chris Lattner99bb3152009-01-05 08:00:30 +00002229 if (!FunctionType::isValidReturnType(RetType) ||
2230 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002231 return Error(RetTypeLoc, "invalid function return type");
2232
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002234
2235 std::string FunctionName;
2236 if (Lex.getKind() == lltok::GlobalVar) {
2237 FunctionName = Lex.getStrVal();
2238 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2239 unsigned NameID = Lex.getUIntVal();
2240
2241 if (NameID != NumberedVals.size())
2242 return TokError("function expected to be numbered '%" +
2243 utostr(NumberedVals.size()) + "'");
2244 } else {
2245 return TokError("expected function name");
2246 }
2247
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002248 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002249
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002250 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002251 return TokError("expected '(' in function argument list");
2252
2253 std::vector<ArgInfo> ArgList;
2254 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002258 std::string GC;
2259
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002260 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002261 ParseOptionalAttrs(FuncAttrs, 2) ||
2262 (EatIfPresent(lltok::kw_section) &&
2263 ParseStringConstant(Section)) ||
2264 ParseOptionalAlignment(Alignment) ||
2265 (EatIfPresent(lltok::kw_gc) &&
2266 ParseStringConstant(GC)))
2267 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002268
2269 // If the alignment was parsed as an attribute, move to the alignment field.
2270 if (FuncAttrs & Attribute::Alignment) {
2271 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2272 FuncAttrs &= ~Attribute::Alignment;
2273 }
2274
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 // Okay, if we got here, the function is syntactically valid. Convert types
2276 // and do semantic checks.
2277 std::vector<const Type*> ParamTypeList;
2278 SmallVector<AttributeWithIndex, 8> Attrs;
2279 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2280 // attributes.
2281 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2282 if (FuncAttrs & ObsoleteFuncAttrs) {
2283 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2284 FuncAttrs &= ~ObsoleteFuncAttrs;
2285 }
2286
2287 if (RetAttrs != Attribute::None)
2288 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2289
2290 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2291 ParamTypeList.push_back(ArgList[i].Type);
2292 if (ArgList[i].Attrs != Attribute::None)
2293 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2294 }
2295
2296 if (FuncAttrs != Attribute::None)
2297 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2298
2299 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2300
Chris Lattnera9a9e072009-03-09 04:49:14 +00002301 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2302 RetType != Type::VoidTy)
2303 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2304
Owen Andersonfba933c2009-07-01 23:57:11 +00002305 const FunctionType *FT =
2306 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2307 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002308
2309 Fn = 0;
2310 if (!FunctionName.empty()) {
2311 // If this was a definition of a forward reference, remove the definition
2312 // from the forward reference table and fill in the forward ref.
2313 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2314 ForwardRefVals.find(FunctionName);
2315 if (FRVI != ForwardRefVals.end()) {
2316 Fn = M->getFunction(FunctionName);
2317 ForwardRefVals.erase(FRVI);
2318 } else if ((Fn = M->getFunction(FunctionName))) {
2319 // If this function already exists in the symbol table, then it is
2320 // multiply defined. We accept a few cases for old backwards compat.
2321 // FIXME: Remove this stuff for LLVM 3.0.
2322 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2323 (!Fn->isDeclaration() && isDefine)) {
2324 // If the redefinition has different type or different attributes,
2325 // reject it. If both have bodies, reject it.
2326 return Error(NameLoc, "invalid redefinition of function '" +
2327 FunctionName + "'");
2328 } else if (Fn->isDeclaration()) {
2329 // Make sure to strip off any argument names so we can't get conflicts.
2330 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2331 AI != AE; ++AI)
2332 AI->setName("");
2333 }
2334 }
2335
2336 } else if (FunctionName.empty()) {
2337 // If this is a definition of a forward referenced function, make sure the
2338 // types agree.
2339 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2340 = ForwardRefValIDs.find(NumberedVals.size());
2341 if (I != ForwardRefValIDs.end()) {
2342 Fn = cast<Function>(I->second.first);
2343 if (Fn->getType() != PFT)
2344 return Error(NameLoc, "type of definition and forward reference of '@" +
2345 utostr(NumberedVals.size()) +"' disagree");
2346 ForwardRefValIDs.erase(I);
2347 }
2348 }
2349
2350 if (Fn == 0)
2351 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2352 else // Move the forward-reference to the correct spot in the module.
2353 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2354
2355 if (FunctionName.empty())
2356 NumberedVals.push_back(Fn);
2357
2358 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2359 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2360 Fn->setCallingConv(CC);
2361 Fn->setAttributes(PAL);
2362 Fn->setAlignment(Alignment);
2363 Fn->setSection(Section);
2364 if (!GC.empty()) Fn->setGC(GC.c_str());
2365
2366 // Add all of the arguments we parsed to the function.
2367 Function::arg_iterator ArgIt = Fn->arg_begin();
2368 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2369 // If the argument has a name, insert it into the argument symbol table.
2370 if (ArgList[i].Name.empty()) continue;
2371
2372 // Set the name, if it conflicted, it will be auto-renamed.
2373 ArgIt->setName(ArgList[i].Name);
2374
2375 if (ArgIt->getNameStr() != ArgList[i].Name)
2376 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2377 ArgList[i].Name + "'");
2378 }
2379
2380 return false;
2381}
2382
2383
2384/// ParseFunctionBody
2385/// ::= '{' BasicBlock+ '}'
2386/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2387///
2388bool LLParser::ParseFunctionBody(Function &Fn) {
2389 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2390 return TokError("expected '{' in function body");
2391 Lex.Lex(); // eat the {.
2392
2393 PerFunctionState PFS(*this, Fn);
2394
2395 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2396 if (ParseBasicBlock(PFS)) return true;
2397
2398 // Eat the }.
2399 Lex.Lex();
2400
2401 // Verify function is ok.
2402 return PFS.VerifyFunctionComplete();
2403}
2404
2405/// ParseBasicBlock
2406/// ::= LabelStr? Instruction*
2407bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2408 // If this basic block starts out with a name, remember it.
2409 std::string Name;
2410 LocTy NameLoc = Lex.getLoc();
2411 if (Lex.getKind() == lltok::LabelStr) {
2412 Name = Lex.getStrVal();
2413 Lex.Lex();
2414 }
2415
2416 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2417 if (BB == 0) return true;
2418
2419 std::string NameStr;
2420
2421 // Parse the instructions in this block until we get a terminator.
2422 Instruction *Inst;
2423 do {
2424 // This instruction may have three possibilities for a name: a) none
2425 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2426 LocTy NameLoc = Lex.getLoc();
2427 int NameID = -1;
2428 NameStr = "";
2429
2430 if (Lex.getKind() == lltok::LocalVarID) {
2431 NameID = Lex.getUIntVal();
2432 Lex.Lex();
2433 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2434 return true;
2435 } else if (Lex.getKind() == lltok::LocalVar ||
2436 // FIXME: REMOVE IN LLVM 3.0
2437 Lex.getKind() == lltok::StringConstant) {
2438 NameStr = Lex.getStrVal();
2439 Lex.Lex();
2440 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2441 return true;
2442 }
2443
2444 if (ParseInstruction(Inst, BB, PFS)) return true;
2445
2446 BB->getInstList().push_back(Inst);
2447
2448 // Set the name on the instruction.
2449 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2450 } while (!isa<TerminatorInst>(Inst));
2451
2452 return false;
2453}
2454
2455//===----------------------------------------------------------------------===//
2456// Instruction Parsing.
2457//===----------------------------------------------------------------------===//
2458
2459/// ParseInstruction - Parse one of the many different instructions.
2460///
2461bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2462 PerFunctionState &PFS) {
2463 lltok::Kind Token = Lex.getKind();
2464 if (Token == lltok::Eof)
2465 return TokError("found end of file when expecting more instructions");
2466 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002467 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 Lex.Lex(); // Eat the keyword.
2469
2470 switch (Token) {
2471 default: return Error(Loc, "expected instruction opcode");
2472 // Terminator Instructions.
2473 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2474 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2475 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2476 case lltok::kw_br: return ParseBr(Inst, PFS);
2477 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2478 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2479 // Binary Operators.
2480 case lltok::kw_add:
2481 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002482 case lltok::kw_mul:
2483 // API compatibility: Accept either integer or floating-point types.
2484 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2485 case lltok::kw_fadd:
2486 case lltok::kw_fsub:
2487 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2488
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 case lltok::kw_udiv:
2490 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002491 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002492 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002493 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002494 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002495 case lltok::kw_shl:
2496 case lltok::kw_lshr:
2497 case lltok::kw_ashr:
2498 case lltok::kw_and:
2499 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002500 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002501 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002502 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002503 // Casts.
2504 case lltok::kw_trunc:
2505 case lltok::kw_zext:
2506 case lltok::kw_sext:
2507 case lltok::kw_fptrunc:
2508 case lltok::kw_fpext:
2509 case lltok::kw_bitcast:
2510 case lltok::kw_uitofp:
2511 case lltok::kw_sitofp:
2512 case lltok::kw_fptoui:
2513 case lltok::kw_fptosi:
2514 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002515 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002516 // Other.
2517 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002518 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2520 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2521 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2522 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2523 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2524 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2525 // Memory.
2526 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002527 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002528 case lltok::kw_free: return ParseFree(Inst, PFS);
2529 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2530 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2531 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002532 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002533 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002534 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002535 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002536 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002538 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2539 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2540 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2541 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2542 }
2543}
2544
2545/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2546bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002547 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 switch (Lex.getKind()) {
2549 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2550 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2551 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2552 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2553 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2554 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2555 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2556 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2557 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2558 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2559 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2560 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2561 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2562 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2563 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2564 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2565 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2566 }
2567 } else {
2568 switch (Lex.getKind()) {
2569 default: TokError("expected icmp predicate (e.g. 'eq')");
2570 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2571 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2572 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2573 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2574 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2575 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2576 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2577 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2578 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2579 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2580 }
2581 }
2582 Lex.Lex();
2583 return false;
2584}
2585
2586//===----------------------------------------------------------------------===//
2587// Terminator Instructions.
2588//===----------------------------------------------------------------------===//
2589
2590/// ParseRet - Parse a return instruction.
2591/// ::= 'ret' void
2592/// ::= 'ret' TypeAndValue
2593/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2594bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2595 PerFunctionState &PFS) {
2596 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002597 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002598
2599 if (Ty == Type::VoidTy) {
2600 Inst = ReturnInst::Create();
2601 return false;
2602 }
2603
2604 Value *RV;
2605 if (ParseValue(Ty, RV, PFS)) return true;
2606
2607 // The normal case is one return value.
2608 if (Lex.getKind() == lltok::comma) {
2609 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2610 // of 'ret {i32,i32} {i32 1, i32 2}'
2611 SmallVector<Value*, 8> RVs;
2612 RVs.push_back(RV);
2613
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002614 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 if (ParseTypeAndValue(RV, PFS)) return true;
2616 RVs.push_back(RV);
2617 }
2618
Owen Andersonb43eae72009-07-02 17:04:01 +00002619 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2621 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2622 BB->getInstList().push_back(I);
2623 RV = I;
2624 }
2625 }
2626 Inst = ReturnInst::Create(RV);
2627 return false;
2628}
2629
2630
2631/// ParseBr
2632/// ::= 'br' TypeAndValue
2633/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2634bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2635 LocTy Loc, Loc2;
2636 Value *Op0, *Op1, *Op2;
2637 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2638
2639 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2640 Inst = BranchInst::Create(BB);
2641 return false;
2642 }
2643
2644 if (Op0->getType() != Type::Int1Ty)
2645 return Error(Loc, "branch condition must have 'i1' type");
2646
2647 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2648 ParseTypeAndValue(Op1, Loc, PFS) ||
2649 ParseToken(lltok::comma, "expected ',' after true destination") ||
2650 ParseTypeAndValue(Op2, Loc2, PFS))
2651 return true;
2652
2653 if (!isa<BasicBlock>(Op1))
2654 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 if (!isa<BasicBlock>(Op2))
2656 return Error(Loc2, "true destination of branch must be a basic block");
2657
2658 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2659 return false;
2660}
2661
2662/// ParseSwitch
2663/// Instruction
2664/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2665/// JumpTable
2666/// ::= (TypeAndValue ',' TypeAndValue)*
2667bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2668 LocTy CondLoc, BBLoc;
2669 Value *Cond, *DefaultBB;
2670 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2671 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2672 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2673 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2674 return true;
2675
2676 if (!isa<IntegerType>(Cond->getType()))
2677 return Error(CondLoc, "switch condition must have integer type");
2678 if (!isa<BasicBlock>(DefaultBB))
2679 return Error(BBLoc, "default destination must be a basic block");
2680
2681 // Parse the jump table pairs.
2682 SmallPtrSet<Value*, 32> SeenCases;
2683 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2684 while (Lex.getKind() != lltok::rsquare) {
2685 Value *Constant, *DestBB;
2686
2687 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2688 ParseToken(lltok::comma, "expected ',' after case value") ||
2689 ParseTypeAndValue(DestBB, BBLoc, PFS))
2690 return true;
2691
2692 if (!SeenCases.insert(Constant))
2693 return Error(CondLoc, "duplicate case value in switch");
2694 if (!isa<ConstantInt>(Constant))
2695 return Error(CondLoc, "case value is not a constant integer");
2696 if (!isa<BasicBlock>(DestBB))
2697 return Error(BBLoc, "case destination is not a basic block");
2698
2699 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2700 cast<BasicBlock>(DestBB)));
2701 }
2702
2703 Lex.Lex(); // Eat the ']'.
2704
2705 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2706 Table.size());
2707 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2708 SI->addCase(Table[i].first, Table[i].second);
2709 Inst = SI;
2710 return false;
2711}
2712
2713/// ParseInvoke
2714/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2715/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2716bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2717 LocTy CallLoc = Lex.getLoc();
2718 unsigned CC, RetAttrs, FnAttrs;
2719 PATypeHolder RetType(Type::VoidTy);
2720 LocTy RetTypeLoc;
2721 ValID CalleeID;
2722 SmallVector<ParamInfo, 16> ArgList;
2723
2724 Value *NormalBB, *UnwindBB;
2725 if (ParseOptionalCallingConv(CC) ||
2726 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002727 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 ParseValID(CalleeID) ||
2729 ParseParameterList(ArgList, PFS) ||
2730 ParseOptionalAttrs(FnAttrs, 2) ||
2731 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2732 ParseTypeAndValue(NormalBB, PFS) ||
2733 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2734 ParseTypeAndValue(UnwindBB, PFS))
2735 return true;
2736
2737 if (!isa<BasicBlock>(NormalBB))
2738 return Error(CallLoc, "normal destination is not a basic block");
2739 if (!isa<BasicBlock>(UnwindBB))
2740 return Error(CallLoc, "unwind destination is not a basic block");
2741
2742 // If RetType is a non-function pointer type, then this is the short syntax
2743 // for the call, which means that RetType is just the return type. Infer the
2744 // rest of the function argument types from the arguments that are present.
2745 const PointerType *PFTy = 0;
2746 const FunctionType *Ty = 0;
2747 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2748 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2749 // Pull out the types of all of the arguments...
2750 std::vector<const Type*> ParamTypes;
2751 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2752 ParamTypes.push_back(ArgList[i].V->getType());
2753
2754 if (!FunctionType::isValidReturnType(RetType))
2755 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2756
Owen Andersonfba933c2009-07-01 23:57:11 +00002757 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2758 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002759 }
2760
2761 // Look up the callee.
2762 Value *Callee;
2763 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2764
2765 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2766 // function attributes.
2767 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2768 if (FnAttrs & ObsoleteFuncAttrs) {
2769 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2770 FnAttrs &= ~ObsoleteFuncAttrs;
2771 }
2772
2773 // Set up the Attributes for the function.
2774 SmallVector<AttributeWithIndex, 8> Attrs;
2775 if (RetAttrs != Attribute::None)
2776 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2777
2778 SmallVector<Value*, 8> Args;
2779
2780 // Loop through FunctionType's arguments and ensure they are specified
2781 // correctly. Also, gather any parameter attributes.
2782 FunctionType::param_iterator I = Ty->param_begin();
2783 FunctionType::param_iterator E = Ty->param_end();
2784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2785 const Type *ExpectedTy = 0;
2786 if (I != E) {
2787 ExpectedTy = *I++;
2788 } else if (!Ty->isVarArg()) {
2789 return Error(ArgList[i].Loc, "too many arguments specified");
2790 }
2791
2792 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2793 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2794 ExpectedTy->getDescription() + "'");
2795 Args.push_back(ArgList[i].V);
2796 if (ArgList[i].Attrs != Attribute::None)
2797 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2798 }
2799
2800 if (I != E)
2801 return Error(CallLoc, "not enough parameters specified for call");
2802
2803 if (FnAttrs != Attribute::None)
2804 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2805
2806 // Finish off the Attributes and check them
2807 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2808
2809 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2810 cast<BasicBlock>(UnwindBB),
2811 Args.begin(), Args.end());
2812 II->setCallingConv(CC);
2813 II->setAttributes(PAL);
2814 Inst = II;
2815 return false;
2816}
2817
2818
2819
2820//===----------------------------------------------------------------------===//
2821// Binary Operators.
2822//===----------------------------------------------------------------------===//
2823
2824/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002825/// ::= ArithmeticOps TypeAndValue ',' Value
2826///
2827/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2828/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002829bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002830 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002831 LocTy Loc; Value *LHS, *RHS;
2832 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2833 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2834 ParseValue(LHS->getType(), RHS, PFS))
2835 return true;
2836
Chris Lattnere914b592009-01-05 08:24:46 +00002837 bool Valid;
2838 switch (OperandType) {
Torok Edwinc25e7582009-07-11 20:10:48 +00002839 default: LLVM_UNREACHABLE("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00002840 case 0: // int or FP.
2841 Valid = LHS->getType()->isIntOrIntVector() ||
2842 LHS->getType()->isFPOrFPVector();
2843 break;
2844 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2845 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2846 }
2847
2848 if (!Valid)
2849 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002850
2851 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2852 return false;
2853}
2854
2855/// ParseLogical
2856/// ::= ArithmeticOps TypeAndValue ',' Value {
2857bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2858 unsigned Opc) {
2859 LocTy Loc; Value *LHS, *RHS;
2860 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2861 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2862 ParseValue(LHS->getType(), RHS, PFS))
2863 return true;
2864
2865 if (!LHS->getType()->isIntOrIntVector())
2866 return Error(Loc,"instruction requires integer or integer vector operands");
2867
2868 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2869 return false;
2870}
2871
2872
2873/// ParseCompare
2874/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2875/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002876bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2877 unsigned Opc) {
2878 // Parse the integer/fp comparison predicate.
2879 LocTy Loc;
2880 unsigned Pred;
2881 Value *LHS, *RHS;
2882 if (ParseCmpPredicate(Pred, Opc) ||
2883 ParseTypeAndValue(LHS, Loc, PFS) ||
2884 ParseToken(lltok::comma, "expected ',' after compare value") ||
2885 ParseValue(LHS->getType(), RHS, PFS))
2886 return true;
2887
2888 if (Opc == Instruction::FCmp) {
2889 if (!LHS->getType()->isFPOrFPVector())
2890 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002891 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002892 } else {
2893 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002894 if (!LHS->getType()->isIntOrIntVector() &&
2895 !isa<PointerType>(LHS->getType()))
2896 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002897 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002898 }
2899 return false;
2900}
2901
2902//===----------------------------------------------------------------------===//
2903// Other Instructions.
2904//===----------------------------------------------------------------------===//
2905
2906
2907/// ParseCast
2908/// ::= CastOpc TypeAndValue 'to' Type
2909bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2910 unsigned Opc) {
2911 LocTy Loc; Value *Op;
2912 PATypeHolder DestTy(Type::VoidTy);
2913 if (ParseTypeAndValue(Op, Loc, PFS) ||
2914 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2915 ParseType(DestTy))
2916 return true;
2917
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002918 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2919 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 return Error(Loc, "invalid cast opcode for cast from '" +
2921 Op->getType()->getDescription() + "' to '" +
2922 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002923 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2925 return false;
2926}
2927
2928/// ParseSelect
2929/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2930bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2931 LocTy Loc;
2932 Value *Op0, *Op1, *Op2;
2933 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2934 ParseToken(lltok::comma, "expected ',' after select condition") ||
2935 ParseTypeAndValue(Op1, PFS) ||
2936 ParseToken(lltok::comma, "expected ',' after select value") ||
2937 ParseTypeAndValue(Op2, PFS))
2938 return true;
2939
2940 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2941 return Error(Loc, Reason);
2942
2943 Inst = SelectInst::Create(Op0, Op1, Op2);
2944 return false;
2945}
2946
Chris Lattner0088a5c2009-01-05 08:18:44 +00002947/// ParseVA_Arg
2948/// ::= 'va_arg' TypeAndValue ',' Type
2949bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 Value *Op;
2951 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002952 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 if (ParseTypeAndValue(Op, PFS) ||
2954 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002955 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002957
2958 if (!EltTy->isFirstClassType())
2959 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002960
2961 Inst = new VAArgInst(Op, EltTy);
2962 return false;
2963}
2964
2965/// ParseExtractElement
2966/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2967bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2968 LocTy Loc;
2969 Value *Op0, *Op1;
2970 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2971 ParseToken(lltok::comma, "expected ',' after extract value") ||
2972 ParseTypeAndValue(Op1, PFS))
2973 return true;
2974
2975 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2976 return Error(Loc, "invalid extractelement operands");
2977
2978 Inst = new ExtractElementInst(Op0, Op1);
2979 return false;
2980}
2981
2982/// ParseInsertElement
2983/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2984bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2985 LocTy Loc;
2986 Value *Op0, *Op1, *Op2;
2987 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2988 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2989 ParseTypeAndValue(Op1, PFS) ||
2990 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2991 ParseTypeAndValue(Op2, PFS))
2992 return true;
2993
2994 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2995 return Error(Loc, "invalid extractelement operands");
2996
2997 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2998 return false;
2999}
3000
3001/// ParseShuffleVector
3002/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3003bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3004 LocTy Loc;
3005 Value *Op0, *Op1, *Op2;
3006 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3007 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3008 ParseTypeAndValue(Op1, PFS) ||
3009 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3010 ParseTypeAndValue(Op2, PFS))
3011 return true;
3012
3013 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3014 return Error(Loc, "invalid extractelement operands");
3015
3016 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3017 return false;
3018}
3019
3020/// ParsePHI
3021/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3022bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3023 PATypeHolder Ty(Type::VoidTy);
3024 Value *Op0, *Op1;
3025 LocTy TypeLoc = Lex.getLoc();
3026
3027 if (ParseType(Ty) ||
3028 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3029 ParseValue(Ty, Op0, PFS) ||
3030 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3031 ParseValue(Type::LabelTy, Op1, PFS) ||
3032 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3033 return true;
3034
3035 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3036 while (1) {
3037 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3038
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003039 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 break;
3041
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003042 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003043 ParseValue(Ty, Op0, PFS) ||
3044 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3045 ParseValue(Type::LabelTy, Op1, PFS) ||
3046 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3047 return true;
3048 }
3049
3050 if (!Ty->isFirstClassType())
3051 return Error(TypeLoc, "phi node must have first class type");
3052
3053 PHINode *PN = PHINode::Create(Ty);
3054 PN->reserveOperandSpace(PHIVals.size());
3055 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3056 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3057 Inst = PN;
3058 return false;
3059}
3060
3061/// ParseCall
3062/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3063/// ParameterList OptionalAttrs
3064bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3065 bool isTail) {
3066 unsigned CC, RetAttrs, FnAttrs;
3067 PATypeHolder RetType(Type::VoidTy);
3068 LocTy RetTypeLoc;
3069 ValID CalleeID;
3070 SmallVector<ParamInfo, 16> ArgList;
3071 LocTy CallLoc = Lex.getLoc();
3072
3073 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3074 ParseOptionalCallingConv(CC) ||
3075 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003076 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003077 ParseValID(CalleeID) ||
3078 ParseParameterList(ArgList, PFS) ||
3079 ParseOptionalAttrs(FnAttrs, 2))
3080 return true;
3081
3082 // If RetType is a non-function pointer type, then this is the short syntax
3083 // for the call, which means that RetType is just the return type. Infer the
3084 // rest of the function argument types from the arguments that are present.
3085 const PointerType *PFTy = 0;
3086 const FunctionType *Ty = 0;
3087 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3088 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3089 // Pull out the types of all of the arguments...
3090 std::vector<const Type*> ParamTypes;
3091 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3092 ParamTypes.push_back(ArgList[i].V->getType());
3093
3094 if (!FunctionType::isValidReturnType(RetType))
3095 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3096
Owen Andersonfba933c2009-07-01 23:57:11 +00003097 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3098 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 }
3100
3101 // Look up the callee.
3102 Value *Callee;
3103 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3104
Chris Lattnerdf986172009-01-02 07:01:27 +00003105 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3106 // function attributes.
3107 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3108 if (FnAttrs & ObsoleteFuncAttrs) {
3109 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3110 FnAttrs &= ~ObsoleteFuncAttrs;
3111 }
3112
3113 // Set up the Attributes for the function.
3114 SmallVector<AttributeWithIndex, 8> Attrs;
3115 if (RetAttrs != Attribute::None)
3116 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3117
3118 SmallVector<Value*, 8> Args;
3119
3120 // Loop through FunctionType's arguments and ensure they are specified
3121 // correctly. Also, gather any parameter attributes.
3122 FunctionType::param_iterator I = Ty->param_begin();
3123 FunctionType::param_iterator E = Ty->param_end();
3124 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3125 const Type *ExpectedTy = 0;
3126 if (I != E) {
3127 ExpectedTy = *I++;
3128 } else if (!Ty->isVarArg()) {
3129 return Error(ArgList[i].Loc, "too many arguments specified");
3130 }
3131
3132 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3133 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3134 ExpectedTy->getDescription() + "'");
3135 Args.push_back(ArgList[i].V);
3136 if (ArgList[i].Attrs != Attribute::None)
3137 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3138 }
3139
3140 if (I != E)
3141 return Error(CallLoc, "not enough parameters specified for call");
3142
3143 if (FnAttrs != Attribute::None)
3144 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3145
3146 // Finish off the Attributes and check them
3147 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3148
3149 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3150 CI->setTailCall(isTail);
3151 CI->setCallingConv(CC);
3152 CI->setAttributes(PAL);
3153 Inst = CI;
3154 return false;
3155}
3156
3157//===----------------------------------------------------------------------===//
3158// Memory Instructions.
3159//===----------------------------------------------------------------------===//
3160
3161/// ParseAlloc
3162/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3163/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3164bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3165 unsigned Opc) {
3166 PATypeHolder Ty(Type::VoidTy);
3167 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003168 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003170 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003171
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003172 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003173 if (Lex.getKind() == lltok::kw_align) {
3174 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003175 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3176 ParseOptionalCommaAlignment(Alignment)) {
3177 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 }
3179 }
3180
3181 if (Size && Size->getType() != Type::Int32Ty)
3182 return Error(SizeLoc, "element count must be i32");
3183
3184 if (Opc == Instruction::Malloc)
3185 Inst = new MallocInst(Ty, Size, Alignment);
3186 else
3187 Inst = new AllocaInst(Ty, Size, Alignment);
3188 return false;
3189}
3190
3191/// ParseFree
3192/// ::= 'free' TypeAndValue
3193bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3194 Value *Val; LocTy Loc;
3195 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3196 if (!isa<PointerType>(Val->getType()))
3197 return Error(Loc, "operand to free must be a pointer");
3198 Inst = new FreeInst(Val);
3199 return false;
3200}
3201
3202/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003203/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003204bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3205 bool isVolatile) {
3206 Value *Val; LocTy Loc;
3207 unsigned Alignment;
3208 if (ParseTypeAndValue(Val, Loc, PFS) ||
3209 ParseOptionalCommaAlignment(Alignment))
3210 return true;
3211
3212 if (!isa<PointerType>(Val->getType()) ||
3213 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3214 return Error(Loc, "load operand must be a pointer to a first class type");
3215
3216 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3217 return false;
3218}
3219
3220/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003221/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003222bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3223 bool isVolatile) {
3224 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3225 unsigned Alignment;
3226 if (ParseTypeAndValue(Val, Loc, PFS) ||
3227 ParseToken(lltok::comma, "expected ',' after store operand") ||
3228 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3229 ParseOptionalCommaAlignment(Alignment))
3230 return true;
3231
3232 if (!isa<PointerType>(Ptr->getType()))
3233 return Error(PtrLoc, "store operand must be a pointer");
3234 if (!Val->getType()->isFirstClassType())
3235 return Error(Loc, "store operand must be a first class value");
3236 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3237 return Error(Loc, "stored value and pointer type do not match");
3238
3239 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3240 return false;
3241}
3242
3243/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003244/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003245/// FIXME: Remove support for getresult in LLVM 3.0
3246bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3247 Value *Val; LocTy ValLoc, EltLoc;
3248 unsigned Element;
3249 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3250 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003251 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 return true;
3253
3254 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3255 return Error(ValLoc, "getresult inst requires an aggregate operand");
3256 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3257 return Error(EltLoc, "invalid getresult index for value");
3258 Inst = ExtractValueInst::Create(Val, Element);
3259 return false;
3260}
3261
3262/// ParseGetElementPtr
3263/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3264bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3265 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003266 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003267
3268 if (!isa<PointerType>(Ptr->getType()))
3269 return Error(Loc, "base of getelementptr must be a pointer");
3270
3271 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003272 while (EatIfPresent(lltok::comma)) {
3273 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003274 if (!isa<IntegerType>(Val->getType()))
3275 return Error(EltLoc, "getelementptr index must be an integer");
3276 Indices.push_back(Val);
3277 }
3278
3279 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3280 Indices.begin(), Indices.end()))
3281 return Error(Loc, "invalid getelementptr indices");
3282 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3283 return false;
3284}
3285
3286/// ParseExtractValue
3287/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3288bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3289 Value *Val; LocTy Loc;
3290 SmallVector<unsigned, 4> Indices;
3291 if (ParseTypeAndValue(Val, Loc, PFS) ||
3292 ParseIndexList(Indices))
3293 return true;
3294
3295 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3296 return Error(Loc, "extractvalue operand must be array or struct");
3297
3298 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3299 Indices.end()))
3300 return Error(Loc, "invalid indices for extractvalue");
3301 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3302 return false;
3303}
3304
3305/// ParseInsertValue
3306/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3307bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3308 Value *Val0, *Val1; LocTy Loc0, Loc1;
3309 SmallVector<unsigned, 4> Indices;
3310 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3311 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3312 ParseTypeAndValue(Val1, Loc1, PFS) ||
3313 ParseIndexList(Indices))
3314 return true;
3315
3316 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3317 return Error(Loc0, "extractvalue operand must be array or struct");
3318
3319 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3320 Indices.end()))
3321 return Error(Loc0, "invalid indices for insertvalue");
3322 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3323 return false;
3324}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003325
3326//===----------------------------------------------------------------------===//
3327// Embedded metadata.
3328//===----------------------------------------------------------------------===//
3329
3330/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003331/// ::= Element (',' Element)*
3332/// Element
3333/// ::= 'null' | TypeAndValue
3334bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003335 assert(Lex.getKind() == lltok::lbrace);
3336 Lex.Lex();
3337 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003338 Value *V;
3339 if (Lex.getKind() == lltok::kw_null) {
3340 Lex.Lex();
3341 V = 0;
3342 } else {
3343 Constant *C;
3344 if (ParseGlobalTypeAndValue(C)) return true;
3345 V = C;
3346 }
3347 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003348 } while (EatIfPresent(lltok::comma));
3349
3350 return false;
3351}