blob: 64212f61934991fe6654ee63d8081be6e9a7be0b [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"
27#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattnerdf986172009-01-02 07:01:27 +000030namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000031 /// ValID - Represents a reference of a definition of some sort with no type.
32 /// There are several cases where we have to parse the value but where the
33 /// type can depend on later context. This may either be a numeric reference
34 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000035 struct ValID {
36 enum {
37 t_LocalID, t_GlobalID, // ID in UIntVal.
38 t_LocalName, t_GlobalName, // Name in StrVal.
39 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
40 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000041 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000042 t_Constant, // Value in ConstantVal.
43 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
44 } Kind;
45
46 LLParser::LocTy Loc;
47 unsigned UIntVal;
48 std::string StrVal, StrVal2;
49 APSInt APSIntVal;
50 APFloat APFloatVal;
51 Constant *ConstantVal;
52 ValID() : APFloatVal(0.0) {}
53 };
54}
55
Chris Lattner3ed88ef2009-01-02 08:05:26 +000056/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000057bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000058 // Prime the lexer.
59 Lex.Lex();
60
Chris Lattnerad7d1e22009-01-04 20:44:11 +000061 return ParseTopLevelEntities() ||
62 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000063}
64
65/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
66/// module.
67bool LLParser::ValidateEndOfModule() {
68 if (!ForwardRefTypes.empty())
69 return Error(ForwardRefTypes.begin()->second.second,
70 "use of undefined type named '" +
71 ForwardRefTypes.begin()->first + "'");
72 if (!ForwardRefTypeIDs.empty())
73 return Error(ForwardRefTypeIDs.begin()->second.second,
74 "use of undefined type '%" +
75 utostr(ForwardRefTypeIDs.begin()->first) + "'");
76
77 if (!ForwardRefVals.empty())
78 return Error(ForwardRefVals.begin()->second.second,
79 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 "'");
81
82 if (!ForwardRefValIDs.empty())
83 return Error(ForwardRefValIDs.begin()->second.second,
84 "use of undefined value '@" +
85 utostr(ForwardRefValIDs.begin()->first) + "'");
86
Devang Patel1c7eea62009-07-08 19:23:54 +000087 if (!ForwardRefMDNodes.empty())
88 return Error(ForwardRefMDNodes.begin()->second.second,
89 "use of undefined metadata '!" +
90 utostr(ForwardRefMDNodes.begin()->first) + "'");
91
92
Chris Lattnerdf986172009-01-02 07:01:27 +000093 // Look for intrinsic functions and CallInst that need to be upgraded
94 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
95 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
96
97 return false;
98}
99
100//===----------------------------------------------------------------------===//
101// Top-Level Entities
102//===----------------------------------------------------------------------===//
103
104bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000105 while (1) {
106 switch (Lex.getKind()) {
107 default: return TokError("expected top-level entity");
108 case lltok::Eof: return false;
109 //case lltok::kw_define:
110 case lltok::kw_declare: if (ParseDeclare()) return true; break;
111 case lltok::kw_define: if (ParseDefine()) return true; break;
112 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
113 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
114 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
115 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
116 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
117 case lltok::LocalVar: if (ParseNamedType()) return true; break;
118 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000119 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000120
121 // The Global variable production with no name can have many different
122 // optional leading prefixes, the production is:
123 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
124 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000125 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000126 case lltok::kw_internal: // OptionalLinkage
127 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000128 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000129 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000130 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000131 case lltok::kw_appending: // OptionalLinkage
132 case lltok::kw_dllexport: // OptionalLinkage
133 case lltok::kw_common: // OptionalLinkage
134 case lltok::kw_dllimport: // OptionalLinkage
135 case lltok::kw_extern_weak: // OptionalLinkage
136 case lltok::kw_external: { // OptionalLinkage
137 unsigned Linkage, Visibility;
138 if (ParseOptionalLinkage(Linkage) ||
139 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000140 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000141 return true;
142 break;
143 }
144 case lltok::kw_default: // OptionalVisibility
145 case lltok::kw_hidden: // OptionalVisibility
146 case lltok::kw_protected: { // OptionalVisibility
147 unsigned Visibility;
148 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000149 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000150 return true;
151 break;
152 }
153
154 case lltok::kw_thread_local: // OptionalThreadLocal
155 case lltok::kw_addrspace: // OptionalAddrSpace
156 case lltok::kw_constant: // GlobalType
157 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000158 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000159 break;
160 }
161 }
162}
163
164
165/// toplevelentity
166/// ::= 'module' 'asm' STRINGCONSTANT
167bool LLParser::ParseModuleAsm() {
168 assert(Lex.getKind() == lltok::kw_module);
169 Lex.Lex();
170
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 std::string AsmStr;
172 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
173 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000174
175 const std::string &AsmSoFar = M->getModuleInlineAsm();
176 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000177 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000178 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000180 return false;
181}
182
183/// toplevelentity
184/// ::= 'target' 'triple' '=' STRINGCONSTANT
185/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
186bool LLParser::ParseTargetDefinition() {
187 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000188 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 switch (Lex.Lex()) {
190 default: return TokError("unknown target property");
191 case lltok::kw_triple:
192 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000193 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
194 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000196 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000197 return false;
198 case lltok::kw_datalayout:
199 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000200 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
201 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000203 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return false;
205 }
206}
207
208/// toplevelentity
209/// ::= 'deplibs' '=' '[' ']'
210/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
211bool LLParser::ParseDepLibs() {
212 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000214 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
215 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
216 return true;
217
218 if (EatIfPresent(lltok::rsquare))
219 return false;
220
221 std::string Str;
222 if (ParseStringConstant(Str)) return true;
223 M->addLibrary(Str);
224
225 while (EatIfPresent(lltok::comma)) {
226 if (ParseStringConstant(Str)) return true;
227 M->addLibrary(Str);
228 }
229
230 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000231}
232
233/// toplevelentity
234/// ::= 'type' type
235bool LLParser::ParseUnnamedType() {
236 assert(Lex.getKind() == lltok::kw_type);
237 LocTy TypeLoc = Lex.getLoc();
238 Lex.Lex(); // eat kw_type
239
240 PATypeHolder Ty(Type::VoidTy);
241 if (ParseType(Ty)) return true;
242
243 unsigned TypeID = NumberedTypes.size();
244
Chris Lattnerdf986172009-01-02 07:01:27 +0000245 // See if this type was previously referenced.
246 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
247 FI = ForwardRefTypeIDs.find(TypeID);
248 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000249 if (FI->second.first.get() == Ty)
250 return Error(TypeLoc, "self referential type is invalid");
251
Chris Lattnerdf986172009-01-02 07:01:27 +0000252 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
253 Ty = FI->second.first.get();
254 ForwardRefTypeIDs.erase(FI);
255 }
256
257 NumberedTypes.push_back(Ty);
258
259 return false;
260}
261
262/// toplevelentity
263/// ::= LocalVar '=' 'type' type
264bool LLParser::ParseNamedType() {
265 std::string Name = Lex.getStrVal();
266 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000267 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000268
269 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000270
271 if (ParseToken(lltok::equal, "expected '=' after name") ||
272 ParseToken(lltok::kw_type, "expected 'type' after name") ||
273 ParseType(Ty))
274 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000275
Chris Lattnerdf986172009-01-02 07:01:27 +0000276 // Set the type name, checking for conflicts as we do so.
277 bool AlreadyExists = M->addTypeName(Name, Ty);
278 if (!AlreadyExists) return false;
279
280 // See if this type is a forward reference. We need to eagerly resolve
281 // types to allow recursive type redefinitions below.
282 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
283 FI = ForwardRefTypes.find(Name);
284 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000285 if (FI->second.first.get() == Ty)
286 return Error(NameLoc, "self referential type is invalid");
287
Chris Lattnerdf986172009-01-02 07:01:27 +0000288 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
289 Ty = FI->second.first.get();
290 ForwardRefTypes.erase(FI);
291 }
292
293 // Inserting a name that is already defined, get the existing name.
294 const Type *Existing = M->getTypeByName(Name);
295 assert(Existing && "Conflict but no matching type?!");
296
297 // Otherwise, this is an attempt to redefine a type. That's okay if
298 // the redefinition is identical to the original.
299 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
300 if (Existing == Ty) return false;
301
302 // Any other kind of (non-equivalent) redefinition is an error.
303 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
304 Ty->getDescription() + "'");
305}
306
307
308/// toplevelentity
309/// ::= 'declare' FunctionHeader
310bool LLParser::ParseDeclare() {
311 assert(Lex.getKind() == lltok::kw_declare);
312 Lex.Lex();
313
314 Function *F;
315 return ParseFunctionHeader(F, false);
316}
317
318/// toplevelentity
319/// ::= 'define' FunctionHeader '{' ...
320bool LLParser::ParseDefine() {
321 assert(Lex.getKind() == lltok::kw_define);
322 Lex.Lex();
323
324 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000325 return ParseFunctionHeader(F, true) ||
326 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000327}
328
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000329/// ParseGlobalType
330/// ::= 'constant'
331/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000332bool LLParser::ParseGlobalType(bool &IsConstant) {
333 if (Lex.getKind() == lltok::kw_constant)
334 IsConstant = true;
335 else if (Lex.getKind() == lltok::kw_global)
336 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000337 else {
338 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000339 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000340 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 Lex.Lex();
342 return false;
343}
344
345/// ParseNamedGlobal:
346/// GlobalVar '=' OptionalVisibility ALIAS ...
347/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
348bool LLParser::ParseNamedGlobal() {
349 assert(Lex.getKind() == lltok::GlobalVar);
350 LocTy NameLoc = Lex.getLoc();
351 std::string Name = Lex.getStrVal();
352 Lex.Lex();
353
354 bool HasLinkage;
355 unsigned Linkage, Visibility;
356 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
357 ParseOptionalLinkage(Linkage, HasLinkage) ||
358 ParseOptionalVisibility(Visibility))
359 return true;
360
361 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
362 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
363 return ParseAlias(Name, NameLoc, Visibility);
364}
365
Devang Patel923078c2009-07-01 19:21:12 +0000366/// ParseStandaloneMetadata:
367/// !42 = !{...}
368bool LLParser::ParseStandaloneMetadata() {
369 assert(Lex.getKind() == lltok::Metadata);
370 Lex.Lex();
371 unsigned MetadataID = 0;
372 if (ParseUInt32(MetadataID))
373 return true;
374 if (MetadataCache.find(MetadataID) != MetadataCache.end())
375 return TokError("Metadata id is already used");
376 if (ParseToken(lltok::equal, "expected '=' here"))
377 return true;
378
379 LocTy TyLoc;
Devang Patel923078c2009-07-01 19:21:12 +0000380 PATypeHolder Ty(Type::VoidTy);
Devang Patel2214c942009-07-08 21:57:07 +0000381 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000382 return true;
383
384 Constant *Init = 0;
385 if (ParseGlobalValue(Ty, Init))
386 return true;
387
388 MetadataCache[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000389 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
390 FI = ForwardRefMDNodes.find(MetadataID);
391 if (FI != ForwardRefMDNodes.end()) {
392 Constant *FwdNode = FI->second.first;
393 FwdNode->replaceAllUsesWith(Init);
394 ForwardRefMDNodes.erase(FI);
395 }
396
Devang Patel923078c2009-07-01 19:21:12 +0000397 return false;
398}
399
Chris Lattnerdf986172009-01-02 07:01:27 +0000400/// ParseAlias:
401/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
402/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000403/// ::= TypeAndValue
404/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
405/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000406///
407/// Everything through visibility has already been parsed.
408///
409bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
410 unsigned Visibility) {
411 assert(Lex.getKind() == lltok::kw_alias);
412 Lex.Lex();
413 unsigned Linkage;
414 LocTy LinkageLoc = Lex.getLoc();
415 if (ParseOptionalLinkage(Linkage))
416 return true;
417
418 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000419 Linkage != GlobalValue::WeakAnyLinkage &&
420 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000421 Linkage != GlobalValue::InternalLinkage &&
422 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000423 return Error(LinkageLoc, "invalid linkage type for alias");
424
425 Constant *Aliasee;
426 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000427 if (Lex.getKind() != lltok::kw_bitcast &&
428 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000429 if (ParseGlobalTypeAndValue(Aliasee)) return true;
430 } else {
431 // The bitcast dest type is not present, it is implied by the dest type.
432 ValID ID;
433 if (ParseValID(ID)) return true;
434 if (ID.Kind != ValID::t_Constant)
435 return Error(AliaseeLoc, "invalid aliasee");
436 Aliasee = ID.ConstantVal;
437 }
438
439 if (!isa<PointerType>(Aliasee->getType()))
440 return Error(AliaseeLoc, "alias must have pointer type");
441
442 // Okay, create the alias but do not insert it into the module yet.
443 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
444 (GlobalValue::LinkageTypes)Linkage, Name,
445 Aliasee);
446 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
447
448 // See if this value already exists in the symbol table. If so, it is either
449 // a redefinition or a definition of a forward reference.
450 if (GlobalValue *Val =
451 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
452 // See if this was a redefinition. If so, there is no entry in
453 // ForwardRefVals.
454 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
455 I = ForwardRefVals.find(Name);
456 if (I == ForwardRefVals.end())
457 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
458
459 // Otherwise, this was a definition of forward ref. Verify that types
460 // agree.
461 if (Val->getType() != GA->getType())
462 return Error(NameLoc,
463 "forward reference and definition of alias have different types");
464
465 // If they agree, just RAUW the old value with the alias and remove the
466 // forward ref info.
467 Val->replaceAllUsesWith(GA);
468 Val->eraseFromParent();
469 ForwardRefVals.erase(I);
470 }
471
472 // Insert into the module, we know its name won't collide now.
473 M->getAliasList().push_back(GA);
474 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
475
476 return false;
477}
478
479/// ParseGlobal
480/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
481/// OptionalAddrSpace GlobalType Type Const
482/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
483/// OptionalAddrSpace GlobalType Type Const
484///
485/// Everything through visibility has been parsed already.
486///
487bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
488 unsigned Linkage, bool HasLinkage,
489 unsigned Visibility) {
490 unsigned AddrSpace;
491 bool ThreadLocal, IsConstant;
492 LocTy TyLoc;
493
494 PATypeHolder Ty(Type::VoidTy);
495 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
496 ParseOptionalAddrSpace(AddrSpace) ||
497 ParseGlobalType(IsConstant) ||
498 ParseType(Ty, TyLoc))
499 return true;
500
501 // If the linkage is specified and is external, then no initializer is
502 // present.
503 Constant *Init = 0;
504 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000505 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000506 Linkage != GlobalValue::ExternalLinkage)) {
507 if (ParseGlobalValue(Ty, Init))
508 return true;
509 }
510
Chris Lattnera9a9e072009-03-09 04:49:14 +0000511 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000512 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000513
514 GlobalVariable *GV = 0;
515
516 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000517 if (!Name.empty()) {
518 if ((GV = M->getGlobalVariable(Name, true)) &&
519 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000520 return Error(NameLoc, "redefinition of global '@" + Name + "'");
521 } else {
522 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
523 I = ForwardRefValIDs.find(NumberedVals.size());
524 if (I != ForwardRefValIDs.end()) {
525 GV = cast<GlobalVariable>(I->second.first);
526 ForwardRefValIDs.erase(I);
527 }
528 }
529
530 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000531 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
532 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000533 } else {
534 if (GV->getType()->getElementType() != Ty)
535 return Error(TyLoc,
536 "forward reference and definition of global have different types");
537
538 // Move the forward-reference to the correct spot in the module.
539 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
540 }
541
542 if (Name.empty())
543 NumberedVals.push_back(GV);
544
545 // Set the parsed properties on the global.
546 if (Init)
547 GV->setInitializer(Init);
548 GV->setConstant(IsConstant);
549 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
550 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
551 GV->setThreadLocal(ThreadLocal);
552
553 // Parse attributes on the global.
554 while (Lex.getKind() == lltok::comma) {
555 Lex.Lex();
556
557 if (Lex.getKind() == lltok::kw_section) {
558 Lex.Lex();
559 GV->setSection(Lex.getStrVal());
560 if (ParseToken(lltok::StringConstant, "expected global section string"))
561 return true;
562 } else if (Lex.getKind() == lltok::kw_align) {
563 unsigned Alignment;
564 if (ParseOptionalAlignment(Alignment)) return true;
565 GV->setAlignment(Alignment);
566 } else {
567 TokError("unknown global variable property!");
568 }
569 }
570
571 return false;
572}
573
574
575//===----------------------------------------------------------------------===//
576// GlobalValue Reference/Resolution Routines.
577//===----------------------------------------------------------------------===//
578
579/// GetGlobalVal - Get a value with the specified name or ID, creating a
580/// forward reference record if needed. This can return null if the value
581/// exists but does not have the right type.
582GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
583 LocTy Loc) {
584 const PointerType *PTy = dyn_cast<PointerType>(Ty);
585 if (PTy == 0) {
586 Error(Loc, "global variable reference must have pointer type");
587 return 0;
588 }
589
590 // Look this name up in the normal function symbol table.
591 GlobalValue *Val =
592 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
593
594 // If this is a forward reference for the value, see if we already created a
595 // forward ref record.
596 if (Val == 0) {
597 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
598 I = ForwardRefVals.find(Name);
599 if (I != ForwardRefVals.end())
600 Val = I->second.first;
601 }
602
603 // If we have the value in the symbol table or fwd-ref table, return it.
604 if (Val) {
605 if (Val->getType() == Ty) return Val;
606 Error(Loc, "'@" + Name + "' defined with type '" +
607 Val->getType()->getDescription() + "'");
608 return 0;
609 }
610
611 // Otherwise, create a new forward reference for this value and remember it.
612 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000613 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
614 // Function types can return opaque but functions can't.
615 if (isa<OpaqueType>(FT->getReturnType())) {
616 Error(Loc, "function may not return opaque type");
617 return 0;
618 }
619
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000620 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000621 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000622 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
623 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000624 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000625
626 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
627 return FwdVal;
628}
629
630GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
631 const PointerType *PTy = dyn_cast<PointerType>(Ty);
632 if (PTy == 0) {
633 Error(Loc, "global variable reference must have pointer type");
634 return 0;
635 }
636
637 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
638
639 // If this is a forward reference for the value, see if we already created a
640 // forward ref record.
641 if (Val == 0) {
642 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
643 I = ForwardRefValIDs.find(ID);
644 if (I != ForwardRefValIDs.end())
645 Val = I->second.first;
646 }
647
648 // If we have the value in the symbol table or fwd-ref table, return it.
649 if (Val) {
650 if (Val->getType() == Ty) return Val;
651 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
652 Val->getType()->getDescription() + "'");
653 return 0;
654 }
655
656 // Otherwise, create a new forward reference for this value and remember it.
657 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000658 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
659 // Function types can return opaque but functions can't.
660 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000661 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000662 return 0;
663 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000664 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000665 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000666 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
667 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000668 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000669
670 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
671 return FwdVal;
672}
673
674
675//===----------------------------------------------------------------------===//
676// Helper Routines.
677//===----------------------------------------------------------------------===//
678
679/// ParseToken - If the current token has the specified kind, eat it and return
680/// success. Otherwise, emit the specified error and return failure.
681bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
682 if (Lex.getKind() != T)
683 return TokError(ErrMsg);
684 Lex.Lex();
685 return false;
686}
687
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000688/// ParseStringConstant
689/// ::= StringConstant
690bool LLParser::ParseStringConstant(std::string &Result) {
691 if (Lex.getKind() != lltok::StringConstant)
692 return TokError("expected string constant");
693 Result = Lex.getStrVal();
694 Lex.Lex();
695 return false;
696}
697
698/// ParseUInt32
699/// ::= uint32
700bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000701 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
702 return TokError("expected integer");
703 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
704 if (Val64 != unsigned(Val64))
705 return TokError("expected 32-bit integer (too large)");
706 Val = Val64;
707 Lex.Lex();
708 return false;
709}
710
711
712/// ParseOptionalAddrSpace
713/// := /*empty*/
714/// := 'addrspace' '(' uint32 ')'
715bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
716 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000717 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000720 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000721 ParseToken(lltok::rparen, "expected ')' in address space");
722}
723
724/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
725/// indicates what kind of attribute list this is: 0: function arg, 1: result,
726/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000727/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000728bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
729 Attrs = Attribute::None;
730 LocTy AttrLoc = Lex.getLoc();
731
732 while (1) {
733 switch (Lex.getKind()) {
734 case lltok::kw_sext:
735 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000736 // Treat these as signext/zeroext if they occur in the argument list after
737 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
738 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
739 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000740 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000741 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000742 if (Lex.getKind() == lltok::kw_sext)
743 Attrs |= Attribute::SExt;
744 else
745 Attrs |= Attribute::ZExt;
746 break;
747 }
748 // FALL THROUGH.
749 default: // End of attributes.
750 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
751 return Error(AttrLoc, "invalid use of function-only attribute");
752
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000753 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000754 return Error(AttrLoc, "invalid use of parameter-only attribute");
755
756 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000757 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
758 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
759 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
760 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
761 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
762 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
763 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
764 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000765
Devang Patel578efa92009-06-05 21:57:13 +0000766 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
767 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
768 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
769 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
770 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
771 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
772 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
773 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
774 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
775 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
776 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000777
778 case lltok::kw_align: {
779 unsigned Alignment;
780 if (ParseOptionalAlignment(Alignment))
781 return true;
782 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
783 continue;
784 }
785 }
786 Lex.Lex();
787 }
788}
789
790/// ParseOptionalLinkage
791/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000792/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000793/// ::= 'internal'
794/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000795/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000796/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000797/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000798/// ::= 'appending'
799/// ::= 'dllexport'
800/// ::= 'common'
801/// ::= 'dllimport'
802/// ::= 'extern_weak'
803/// ::= 'external'
804bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
805 HasLinkage = false;
806 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000807 default: Res = GlobalValue::ExternalLinkage; return false;
808 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
809 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
810 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
811 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
812 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
813 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000814 case lltok::kw_available_externally:
815 Res = GlobalValue::AvailableExternallyLinkage;
816 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000817 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
818 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000819 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000820 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000821 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000822 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000823 }
824 Lex.Lex();
825 HasLinkage = true;
826 return false;
827}
828
829/// ParseOptionalVisibility
830/// ::= /*empty*/
831/// ::= 'default'
832/// ::= 'hidden'
833/// ::= 'protected'
834///
835bool LLParser::ParseOptionalVisibility(unsigned &Res) {
836 switch (Lex.getKind()) {
837 default: Res = GlobalValue::DefaultVisibility; return false;
838 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
839 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
840 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
841 }
842 Lex.Lex();
843 return false;
844}
845
846/// ParseOptionalCallingConv
847/// ::= /*empty*/
848/// ::= 'ccc'
849/// ::= 'fastcc'
850/// ::= 'coldcc'
851/// ::= 'x86_stdcallcc'
852/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000853/// ::= 'arm_apcscc'
854/// ::= 'arm_aapcscc'
855/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000856/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000857///
Chris Lattnerdf986172009-01-02 07:01:27 +0000858bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
859 switch (Lex.getKind()) {
860 default: CC = CallingConv::C; return false;
861 case lltok::kw_ccc: CC = CallingConv::C; break;
862 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
863 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
864 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
865 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000866 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
867 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
868 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000869 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000870 }
871 Lex.Lex();
872 return false;
873}
874
875/// ParseOptionalAlignment
876/// ::= /* empty */
877/// ::= 'align' 4
878bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
879 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000880 if (!EatIfPresent(lltok::kw_align))
881 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000882 LocTy AlignLoc = Lex.getLoc();
883 if (ParseUInt32(Alignment)) return true;
884 if (!isPowerOf2_32(Alignment))
885 return Error(AlignLoc, "alignment is not a power of two");
886 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000887}
888
889/// ParseOptionalCommaAlignment
890/// ::= /* empty */
891/// ::= ',' 'align' 4
892bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
893 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000894 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000895 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000897 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000898}
899
900/// ParseIndexList
901/// ::= (',' uint32)+
902bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
903 if (Lex.getKind() != lltok::comma)
904 return TokError("expected ',' as start of index list");
905
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000906 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000907 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000908 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000909 Indices.push_back(Idx);
910 }
911
912 return false;
913}
914
915//===----------------------------------------------------------------------===//
916// Type Parsing.
917//===----------------------------------------------------------------------===//
918
919/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000920bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
921 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000922 if (ParseTypeRec(Result)) return true;
923
924 // Verify no unresolved uprefs.
925 if (!UpRefs.empty())
926 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000927
Chris Lattnera9a9e072009-03-09 04:49:14 +0000928 if (!AllowVoid && Result.get() == Type::VoidTy)
929 return Error(TypeLoc, "void type only allowed for function results");
930
Chris Lattnerdf986172009-01-02 07:01:27 +0000931 return false;
932}
933
934/// HandleUpRefs - Every time we finish a new layer of types, this function is
935/// called. It loops through the UpRefs vector, which is a list of the
936/// currently active types. For each type, if the up-reference is contained in
937/// the newly completed type, we decrement the level count. When the level
938/// count reaches zero, the up-referenced type is the type that is passed in:
939/// thus we can complete the cycle.
940///
941PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
942 // If Ty isn't abstract, or if there are no up-references in it, then there is
943 // nothing to resolve here.
944 if (!ty->isAbstract() || UpRefs.empty()) return ty;
945
946 PATypeHolder Ty(ty);
947#if 0
948 errs() << "Type '" << Ty->getDescription()
949 << "' newly formed. Resolving upreferences.\n"
950 << UpRefs.size() << " upreferences active!\n";
951#endif
952
953 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
954 // to zero), we resolve them all together before we resolve them to Ty. At
955 // the end of the loop, if there is anything to resolve to Ty, it will be in
956 // this variable.
957 OpaqueType *TypeToResolve = 0;
958
959 for (unsigned i = 0; i != UpRefs.size(); ++i) {
960 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
961 bool ContainsType =
962 std::find(Ty->subtype_begin(), Ty->subtype_end(),
963 UpRefs[i].LastContainedTy) != Ty->subtype_end();
964
965#if 0
966 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
967 << UpRefs[i].LastContainedTy->getDescription() << ") = "
968 << (ContainsType ? "true" : "false")
969 << " level=" << UpRefs[i].NestingLevel << "\n";
970#endif
971 if (!ContainsType)
972 continue;
973
974 // Decrement level of upreference
975 unsigned Level = --UpRefs[i].NestingLevel;
976 UpRefs[i].LastContainedTy = Ty;
977
978 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
979 if (Level != 0)
980 continue;
981
982#if 0
983 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
984#endif
985 if (!TypeToResolve)
986 TypeToResolve = UpRefs[i].UpRefTy;
987 else
988 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
989 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
990 --i; // Do not skip the next element.
991 }
992
993 if (TypeToResolve)
994 TypeToResolve->refineAbstractTypeTo(Ty);
995
996 return Ty;
997}
998
999
1000/// ParseTypeRec - The recursive function used to process the internal
1001/// implementation details of types.
1002bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1003 switch (Lex.getKind()) {
1004 default:
1005 return TokError("expected type");
1006 case lltok::Type:
1007 // TypeRec ::= 'float' | 'void' (etc)
1008 Result = Lex.getTyVal();
1009 Lex.Lex();
1010 break;
1011 case lltok::kw_opaque:
1012 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001013 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001014 Lex.Lex();
1015 break;
1016 case lltok::lbrace:
1017 // TypeRec ::= '{' ... '}'
1018 if (ParseStructType(Result, false))
1019 return true;
1020 break;
1021 case lltok::lsquare:
1022 // TypeRec ::= '[' ... ']'
1023 Lex.Lex(); // eat the lsquare.
1024 if (ParseArrayVectorType(Result, false))
1025 return true;
1026 break;
1027 case lltok::less: // Either vector or packed struct.
1028 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001029 Lex.Lex();
1030 if (Lex.getKind() == lltok::lbrace) {
1031 if (ParseStructType(Result, true) ||
1032 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001033 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001034 } else if (ParseArrayVectorType(Result, true))
1035 return true;
1036 break;
1037 case lltok::LocalVar:
1038 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1039 // TypeRec ::= %foo
1040 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1041 Result = T;
1042 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001043 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001044 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1045 std::make_pair(Result,
1046 Lex.getLoc())));
1047 M->addTypeName(Lex.getStrVal(), Result.get());
1048 }
1049 Lex.Lex();
1050 break;
1051
1052 case lltok::LocalVarID:
1053 // TypeRec ::= %4
1054 if (Lex.getUIntVal() < NumberedTypes.size())
1055 Result = NumberedTypes[Lex.getUIntVal()];
1056 else {
1057 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1058 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1059 if (I != ForwardRefTypeIDs.end())
1060 Result = I->second.first;
1061 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001062 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001063 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1064 std::make_pair(Result,
1065 Lex.getLoc())));
1066 }
1067 }
1068 Lex.Lex();
1069 break;
1070 case lltok::backslash: {
1071 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001072 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001073 unsigned Val;
1074 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001075 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001076 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1077 Result = OT;
1078 break;
1079 }
1080 }
1081
1082 // Parse the type suffixes.
1083 while (1) {
1084 switch (Lex.getKind()) {
1085 // End of type.
1086 default: return false;
1087
1088 // TypeRec ::= TypeRec '*'
1089 case lltok::star:
1090 if (Result.get() == Type::LabelTy)
1091 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001092 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001093 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001094 if (!PointerType::isValidElementType(Result.get()))
1095 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001096 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001097 Lex.Lex();
1098 break;
1099
1100 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1101 case lltok::kw_addrspace: {
1102 if (Result.get() == Type::LabelTy)
1103 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001104 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001105 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001106 if (!PointerType::isValidElementType(Result.get()))
1107 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001108 unsigned AddrSpace;
1109 if (ParseOptionalAddrSpace(AddrSpace) ||
1110 ParseToken(lltok::star, "expected '*' in address space"))
1111 return true;
1112
Owen Andersonfba933c2009-07-01 23:57:11 +00001113 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001114 break;
1115 }
1116
1117 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1118 case lltok::lparen:
1119 if (ParseFunctionType(Result))
1120 return true;
1121 break;
1122 }
1123 }
1124}
1125
1126/// ParseParameterList
1127/// ::= '(' ')'
1128/// ::= '(' Arg (',' Arg)* ')'
1129/// Arg
1130/// ::= Type OptionalAttributes Value OptionalAttributes
1131bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1132 PerFunctionState &PFS) {
1133 if (ParseToken(lltok::lparen, "expected '(' in call"))
1134 return true;
1135
1136 while (Lex.getKind() != lltok::rparen) {
1137 // If this isn't the first argument, we need a comma.
1138 if (!ArgList.empty() &&
1139 ParseToken(lltok::comma, "expected ',' in argument list"))
1140 return true;
1141
1142 // Parse the argument.
1143 LocTy ArgLoc;
1144 PATypeHolder ArgTy(Type::VoidTy);
1145 unsigned ArgAttrs1, ArgAttrs2;
1146 Value *V;
1147 if (ParseType(ArgTy, ArgLoc) ||
1148 ParseOptionalAttrs(ArgAttrs1, 0) ||
1149 ParseValue(ArgTy, V, PFS) ||
1150 // FIXME: Should not allow attributes after the argument, remove this in
1151 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001152 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001153 return true;
1154 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1155 }
1156
1157 Lex.Lex(); // Lex the ')'.
1158 return false;
1159}
1160
1161
1162
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001163/// ParseArgumentList - Parse the argument list for a function type or function
1164/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001165/// ::= '(' ArgTypeListI ')'
1166/// ArgTypeListI
1167/// ::= /*empty*/
1168/// ::= '...'
1169/// ::= ArgTypeList ',' '...'
1170/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001171///
Chris Lattnerdf986172009-01-02 07:01:27 +00001172bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001173 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 isVarArg = false;
1175 assert(Lex.getKind() == lltok::lparen);
1176 Lex.Lex(); // eat the (.
1177
1178 if (Lex.getKind() == lltok::rparen) {
1179 // empty
1180 } else if (Lex.getKind() == lltok::dotdotdot) {
1181 isVarArg = true;
1182 Lex.Lex();
1183 } else {
1184 LocTy TypeLoc = Lex.getLoc();
1185 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001186 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001188
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001189 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1190 // types (such as a function returning a pointer to itself). If parsing a
1191 // function prototype, we require fully resolved types.
1192 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001193 ParseOptionalAttrs(Attrs, 0)) return true;
1194
Chris Lattnera9a9e072009-03-09 04:49:14 +00001195 if (ArgTy == Type::VoidTy)
1196 return Error(TypeLoc, "argument can not have void type");
1197
Chris Lattnerdf986172009-01-02 07:01:27 +00001198 if (Lex.getKind() == lltok::LocalVar ||
1199 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1200 Name = Lex.getStrVal();
1201 Lex.Lex();
1202 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001203
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001204 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001205 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001206
1207 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1208
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001209 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001210 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001211 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001213 break;
1214 }
1215
1216 // Otherwise must be an argument type.
1217 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001218 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001219 ParseOptionalAttrs(Attrs, 0)) return true;
1220
Chris Lattnera9a9e072009-03-09 04:49:14 +00001221 if (ArgTy == Type::VoidTy)
1222 return Error(TypeLoc, "argument can not have void type");
1223
Chris Lattnerdf986172009-01-02 07:01:27 +00001224 if (Lex.getKind() == lltok::LocalVar ||
1225 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1226 Name = Lex.getStrVal();
1227 Lex.Lex();
1228 } else {
1229 Name = "";
1230 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001231
1232 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1233 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001234
1235 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1236 }
1237 }
1238
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001239 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001240}
1241
1242/// ParseFunctionType
1243/// ::= Type ArgumentList OptionalAttrs
1244bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1245 assert(Lex.getKind() == lltok::lparen);
1246
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001247 if (!FunctionType::isValidReturnType(Result))
1248 return TokError("invalid function return type");
1249
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 std::vector<ArgInfo> ArgList;
1251 bool isVarArg;
1252 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001253 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 // FIXME: Allow, but ignore attributes on function types!
1255 // FIXME: Remove in LLVM 3.0
1256 ParseOptionalAttrs(Attrs, 2))
1257 return true;
1258
1259 // Reject names on the arguments lists.
1260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1261 if (!ArgList[i].Name.empty())
1262 return Error(ArgList[i].Loc, "argument name invalid in function type");
1263 if (!ArgList[i].Attrs != 0) {
1264 // Allow but ignore attributes on function types; this permits
1265 // auto-upgrade.
1266 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1267 }
1268 }
1269
1270 std::vector<const Type*> ArgListTy;
1271 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1272 ArgListTy.push_back(ArgList[i].Type);
1273
Owen Andersonfba933c2009-07-01 23:57:11 +00001274 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1275 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 return false;
1277}
1278
1279/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1280/// TypeRec
1281/// ::= '{' '}'
1282/// ::= '{' TypeRec (',' TypeRec)* '}'
1283/// ::= '<' '{' '}' '>'
1284/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1285bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1286 assert(Lex.getKind() == lltok::lbrace);
1287 Lex.Lex(); // Consume the '{'
1288
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001289 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001290 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 return false;
1292 }
1293
1294 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001295 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 if (ParseTypeRec(Result)) return true;
1297 ParamsList.push_back(Result);
1298
Chris Lattnera9a9e072009-03-09 04:49:14 +00001299 if (Result == Type::VoidTy)
1300 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001301 if (!StructType::isValidElementType(Result))
1302 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001303
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001304 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001305 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001306 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001307
1308 if (Result == Type::VoidTy)
1309 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001310 if (!StructType::isValidElementType(Result))
1311 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001312
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 ParamsList.push_back(Result);
1314 }
1315
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001316 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1317 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001318
1319 std::vector<const Type*> ParamsListTy;
1320 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1321 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001322 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001323 return false;
1324}
1325
1326/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1327/// token has already been consumed.
1328/// TypeRec
1329/// ::= '[' APSINTVAL 'x' Types ']'
1330/// ::= '<' APSINTVAL 'x' Types '>'
1331bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1332 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1333 Lex.getAPSIntVal().getBitWidth() > 64)
1334 return TokError("expected number in address space");
1335
1336 LocTy SizeLoc = Lex.getLoc();
1337 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001338 Lex.Lex();
1339
1340 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1341 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001342
1343 LocTy TypeLoc = Lex.getLoc();
1344 PATypeHolder EltTy(Type::VoidTy);
1345 if (ParseTypeRec(EltTy)) return true;
1346
Chris Lattnera9a9e072009-03-09 04:49:14 +00001347 if (EltTy == Type::VoidTy)
1348 return Error(TypeLoc, "array and vector element type cannot be void");
1349
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001350 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1351 "expected end of sequential type"))
1352 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001353
1354 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001355 if (Size == 0)
1356 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001357 if ((unsigned)Size != Size)
1358 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001359 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001360 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001361 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001363 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001365 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 }
1367 return false;
1368}
1369
1370//===----------------------------------------------------------------------===//
1371// Function Semantic Analysis.
1372//===----------------------------------------------------------------------===//
1373
1374LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1375 : P(p), F(f) {
1376
1377 // Insert unnamed arguments into the NumberedVals list.
1378 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1379 AI != E; ++AI)
1380 if (!AI->hasName())
1381 NumberedVals.push_back(AI);
1382}
1383
1384LLParser::PerFunctionState::~PerFunctionState() {
1385 // If there were any forward referenced non-basicblock values, delete them.
1386 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1387 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1388 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001389 I->second.first->replaceAllUsesWith(
1390 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 delete I->second.first;
1392 I->second.first = 0;
1393 }
1394
1395 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1396 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1397 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001398 I->second.first->replaceAllUsesWith(
1399 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 delete I->second.first;
1401 I->second.first = 0;
1402 }
1403}
1404
1405bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1406 if (!ForwardRefVals.empty())
1407 return P.Error(ForwardRefVals.begin()->second.second,
1408 "use of undefined value '%" + ForwardRefVals.begin()->first +
1409 "'");
1410 if (!ForwardRefValIDs.empty())
1411 return P.Error(ForwardRefValIDs.begin()->second.second,
1412 "use of undefined value '%" +
1413 utostr(ForwardRefValIDs.begin()->first) + "'");
1414 return false;
1415}
1416
1417
1418/// GetVal - Get a value with the specified name or ID, creating a
1419/// forward reference record if needed. This can return null if the value
1420/// exists but does not have the right type.
1421Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1422 const Type *Ty, LocTy Loc) {
1423 // Look this name up in the normal function symbol table.
1424 Value *Val = F.getValueSymbolTable().lookup(Name);
1425
1426 // If this is a forward reference for the value, see if we already created a
1427 // forward ref record.
1428 if (Val == 0) {
1429 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1430 I = ForwardRefVals.find(Name);
1431 if (I != ForwardRefVals.end())
1432 Val = I->second.first;
1433 }
1434
1435 // If we have the value in the symbol table or fwd-ref table, return it.
1436 if (Val) {
1437 if (Val->getType() == Ty) return Val;
1438 if (Ty == Type::LabelTy)
1439 P.Error(Loc, "'%" + Name + "' is not a basic block");
1440 else
1441 P.Error(Loc, "'%" + Name + "' defined with type '" +
1442 Val->getType()->getDescription() + "'");
1443 return 0;
1444 }
1445
1446 // Don't make placeholders with invalid type.
1447 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1448 P.Error(Loc, "invalid use of a non-first-class type");
1449 return 0;
1450 }
1451
1452 // Otherwise, create a new forward reference for this value and remember it.
1453 Value *FwdVal;
1454 if (Ty == Type::LabelTy)
1455 FwdVal = BasicBlock::Create(Name, &F);
1456 else
1457 FwdVal = new Argument(Ty, Name);
1458
1459 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1460 return FwdVal;
1461}
1462
1463Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1464 LocTy Loc) {
1465 // Look this name up in the normal function symbol table.
1466 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1467
1468 // If this is a forward reference for the value, see if we already created a
1469 // forward ref record.
1470 if (Val == 0) {
1471 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1472 I = ForwardRefValIDs.find(ID);
1473 if (I != ForwardRefValIDs.end())
1474 Val = I->second.first;
1475 }
1476
1477 // If we have the value in the symbol table or fwd-ref table, return it.
1478 if (Val) {
1479 if (Val->getType() == Ty) return Val;
1480 if (Ty == Type::LabelTy)
1481 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1482 else
1483 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1484 Val->getType()->getDescription() + "'");
1485 return 0;
1486 }
1487
1488 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1489 P.Error(Loc, "invalid use of a non-first-class type");
1490 return 0;
1491 }
1492
1493 // Otherwise, create a new forward reference for this value and remember it.
1494 Value *FwdVal;
1495 if (Ty == Type::LabelTy)
1496 FwdVal = BasicBlock::Create("", &F);
1497 else
1498 FwdVal = new Argument(Ty);
1499
1500 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1501 return FwdVal;
1502}
1503
1504/// SetInstName - After an instruction is parsed and inserted into its
1505/// basic block, this installs its name.
1506bool LLParser::PerFunctionState::SetInstName(int NameID,
1507 const std::string &NameStr,
1508 LocTy NameLoc, Instruction *Inst) {
1509 // If this instruction has void type, it cannot have a name or ID specified.
1510 if (Inst->getType() == Type::VoidTy) {
1511 if (NameID != -1 || !NameStr.empty())
1512 return P.Error(NameLoc, "instructions returning void cannot have a name");
1513 return false;
1514 }
1515
1516 // If this was a numbered instruction, verify that the instruction is the
1517 // expected value and resolve any forward references.
1518 if (NameStr.empty()) {
1519 // If neither a name nor an ID was specified, just use the next ID.
1520 if (NameID == -1)
1521 NameID = NumberedVals.size();
1522
1523 if (unsigned(NameID) != NumberedVals.size())
1524 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1525 utostr(NumberedVals.size()) + "'");
1526
1527 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1528 ForwardRefValIDs.find(NameID);
1529 if (FI != ForwardRefValIDs.end()) {
1530 if (FI->second.first->getType() != Inst->getType())
1531 return P.Error(NameLoc, "instruction forward referenced with type '" +
1532 FI->second.first->getType()->getDescription() + "'");
1533 FI->second.first->replaceAllUsesWith(Inst);
1534 ForwardRefValIDs.erase(FI);
1535 }
1536
1537 NumberedVals.push_back(Inst);
1538 return false;
1539 }
1540
1541 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1542 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1543 FI = ForwardRefVals.find(NameStr);
1544 if (FI != ForwardRefVals.end()) {
1545 if (FI->second.first->getType() != Inst->getType())
1546 return P.Error(NameLoc, "instruction forward referenced with type '" +
1547 FI->second.first->getType()->getDescription() + "'");
1548 FI->second.first->replaceAllUsesWith(Inst);
1549 ForwardRefVals.erase(FI);
1550 }
1551
1552 // Set the name on the instruction.
1553 Inst->setName(NameStr);
1554
1555 if (Inst->getNameStr() != NameStr)
1556 return P.Error(NameLoc, "multiple definition of local value named '" +
1557 NameStr + "'");
1558 return false;
1559}
1560
1561/// GetBB - Get a basic block with the specified name or ID, creating a
1562/// forward reference record if needed.
1563BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1564 LocTy Loc) {
1565 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1566}
1567
1568BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1569 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1570}
1571
1572/// DefineBB - Define the specified basic block, which is either named or
1573/// unnamed. If there is an error, this returns null otherwise it returns
1574/// the block being defined.
1575BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1576 LocTy Loc) {
1577 BasicBlock *BB;
1578 if (Name.empty())
1579 BB = GetBB(NumberedVals.size(), Loc);
1580 else
1581 BB = GetBB(Name, Loc);
1582 if (BB == 0) return 0; // Already diagnosed error.
1583
1584 // Move the block to the end of the function. Forward ref'd blocks are
1585 // inserted wherever they happen to be referenced.
1586 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1587
1588 // Remove the block from forward ref sets.
1589 if (Name.empty()) {
1590 ForwardRefValIDs.erase(NumberedVals.size());
1591 NumberedVals.push_back(BB);
1592 } else {
1593 // BB forward references are already in the function symbol table.
1594 ForwardRefVals.erase(Name);
1595 }
1596
1597 return BB;
1598}
1599
1600//===----------------------------------------------------------------------===//
1601// Constants.
1602//===----------------------------------------------------------------------===//
1603
1604/// ParseValID - Parse an abstract value that doesn't necessarily have a
1605/// type implied. For example, if we parse "4" we don't know what integer type
1606/// it has. The value will later be combined with its type and checked for
1607/// sanity.
1608bool LLParser::ParseValID(ValID &ID) {
1609 ID.Loc = Lex.getLoc();
1610 switch (Lex.getKind()) {
1611 default: return TokError("expected value token");
1612 case lltok::GlobalID: // @42
1613 ID.UIntVal = Lex.getUIntVal();
1614 ID.Kind = ValID::t_GlobalID;
1615 break;
1616 case lltok::GlobalVar: // @foo
1617 ID.StrVal = Lex.getStrVal();
1618 ID.Kind = ValID::t_GlobalName;
1619 break;
1620 case lltok::LocalVarID: // %42
1621 ID.UIntVal = Lex.getUIntVal();
1622 ID.Kind = ValID::t_LocalID;
1623 break;
1624 case lltok::LocalVar: // %foo
1625 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1626 ID.StrVal = Lex.getStrVal();
1627 ID.Kind = ValID::t_LocalName;
1628 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001629 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1630 ID.Kind = ValID::t_Constant;
1631 Lex.Lex();
1632 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001633 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001634 if (ParseMDNodeVector(Elts) ||
1635 ParseToken(lltok::rbrace, "expected end of metadata node"))
1636 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001637
Owen Andersone951bdf2009-07-02 17:20:28 +00001638 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001639 return false;
1640 }
1641
Devang Patel923078c2009-07-01 19:21:12 +00001642 // Standalone metadata reference
1643 // !{ ..., !42, ... }
1644 unsigned MID = 0;
1645 if (!ParseUInt32(MID)) {
1646 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001647 if (I != MetadataCache.end())
1648 ID.ConstantVal = I->second;
1649 else {
1650 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
1651 FI = ForwardRefMDNodes.find(MID);
1652 if (FI != ForwardRefMDNodes.end())
1653 ID.ConstantVal = FI->second.first;
1654 else {
1655 // Create MDNode forward reference
1656 SmallVector<Value *, 1> Elts;
Devang Pateld1095402009-07-08 22:25:56 +00001657 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Devang Patel1c7eea62009-07-08 19:23:54 +00001658 Elts.push_back(Context.getMDString(FwdRefName));
1659 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
1660 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
1661 ID.ConstantVal = FwdNode;
1662 }
1663 }
1664
Devang Patel923078c2009-07-01 19:21:12 +00001665 return false;
1666 }
1667
Nick Lewycky21cc4462009-04-04 07:22:01 +00001668 // MDString:
1669 // ::= '!' STRINGCONSTANT
1670 std::string Str;
1671 if (ParseStringConstant(Str)) return true;
1672
Owen Anderson12c99d82009-07-02 17:28:30 +00001673 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001674 return false;
1675 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 case lltok::APSInt:
1677 ID.APSIntVal = Lex.getAPSIntVal();
1678 ID.Kind = ValID::t_APSInt;
1679 break;
1680 case lltok::APFloat:
1681 ID.APFloatVal = Lex.getAPFloatVal();
1682 ID.Kind = ValID::t_APFloat;
1683 break;
1684 case lltok::kw_true:
Owen Andersonfba933c2009-07-01 23:57:11 +00001685 ID.ConstantVal = Context.getConstantIntTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001686 ID.Kind = ValID::t_Constant;
1687 break;
1688 case lltok::kw_false:
Owen Andersonfba933c2009-07-01 23:57:11 +00001689 ID.ConstantVal = Context.getConstantIntFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 ID.Kind = ValID::t_Constant;
1691 break;
1692 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1693 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1694 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1695
1696 case lltok::lbrace: {
1697 // ValID ::= '{' ConstVector '}'
1698 Lex.Lex();
1699 SmallVector<Constant*, 16> Elts;
1700 if (ParseGlobalValueVector(Elts) ||
1701 ParseToken(lltok::rbrace, "expected end of struct constant"))
1702 return true;
1703
Owen Andersonfba933c2009-07-01 23:57:11 +00001704 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 ID.Kind = ValID::t_Constant;
1706 return false;
1707 }
1708 case lltok::less: {
1709 // ValID ::= '<' ConstVector '>' --> Vector.
1710 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1711 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001712 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001713
1714 SmallVector<Constant*, 16> Elts;
1715 LocTy FirstEltLoc = Lex.getLoc();
1716 if (ParseGlobalValueVector(Elts) ||
1717 (isPackedStruct &&
1718 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1719 ParseToken(lltok::greater, "expected end of constant"))
1720 return true;
1721
1722 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001723 ID.ConstantVal =
1724 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001725 ID.Kind = ValID::t_Constant;
1726 return false;
1727 }
1728
1729 if (Elts.empty())
1730 return Error(ID.Loc, "constant vector must not be empty");
1731
1732 if (!Elts[0]->getType()->isInteger() &&
1733 !Elts[0]->getType()->isFloatingPoint())
1734 return Error(FirstEltLoc,
1735 "vector elements must have integer or floating point type");
1736
1737 // Verify that all the vector elements have the same type.
1738 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1739 if (Elts[i]->getType() != Elts[0]->getType())
1740 return Error(FirstEltLoc,
1741 "vector element #" + utostr(i) +
1742 " is not of type '" + Elts[0]->getType()->getDescription());
1743
Owen Andersonfba933c2009-07-01 23:57:11 +00001744 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 ID.Kind = ValID::t_Constant;
1746 return false;
1747 }
1748 case lltok::lsquare: { // Array Constant
1749 Lex.Lex();
1750 SmallVector<Constant*, 16> Elts;
1751 LocTy FirstEltLoc = Lex.getLoc();
1752 if (ParseGlobalValueVector(Elts) ||
1753 ParseToken(lltok::rsquare, "expected end of array constant"))
1754 return true;
1755
1756 // Handle empty element.
1757 if (Elts.empty()) {
1758 // Use undef instead of an array because it's inconvenient to determine
1759 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001760 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 return false;
1762 }
1763
1764 if (!Elts[0]->getType()->isFirstClassType())
1765 return Error(FirstEltLoc, "invalid array element type: " +
1766 Elts[0]->getType()->getDescription());
1767
Owen Andersonfba933c2009-07-01 23:57:11 +00001768 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001769
1770 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001771 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 if (Elts[i]->getType() != Elts[0]->getType())
1773 return Error(FirstEltLoc,
1774 "array element #" + utostr(i) +
1775 " is not of type '" +Elts[0]->getType()->getDescription());
1776 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001777
Owen Andersonfba933c2009-07-01 23:57:11 +00001778 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 ID.Kind = ValID::t_Constant;
1780 return false;
1781 }
1782 case lltok::kw_c: // c "foo"
1783 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001784 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1786 ID.Kind = ValID::t_Constant;
1787 return false;
1788
1789 case lltok::kw_asm: {
1790 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1791 bool HasSideEffect;
1792 Lex.Lex();
1793 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001794 ParseStringConstant(ID.StrVal) ||
1795 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001796 ParseToken(lltok::StringConstant, "expected constraint string"))
1797 return true;
1798 ID.StrVal2 = Lex.getStrVal();
1799 ID.UIntVal = HasSideEffect;
1800 ID.Kind = ValID::t_InlineAsm;
1801 return false;
1802 }
1803
1804 case lltok::kw_trunc:
1805 case lltok::kw_zext:
1806 case lltok::kw_sext:
1807 case lltok::kw_fptrunc:
1808 case lltok::kw_fpext:
1809 case lltok::kw_bitcast:
1810 case lltok::kw_uitofp:
1811 case lltok::kw_sitofp:
1812 case lltok::kw_fptoui:
1813 case lltok::kw_fptosi:
1814 case lltok::kw_inttoptr:
1815 case lltok::kw_ptrtoint: {
1816 unsigned Opc = Lex.getUIntVal();
1817 PATypeHolder DestTy(Type::VoidTy);
1818 Constant *SrcVal;
1819 Lex.Lex();
1820 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1821 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001822 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 ParseType(DestTy) ||
1824 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1825 return true;
1826 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1827 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1828 SrcVal->getType()->getDescription() + "' to '" +
1829 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001830 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1831 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 ID.Kind = ValID::t_Constant;
1833 return false;
1834 }
1835 case lltok::kw_extractvalue: {
1836 Lex.Lex();
1837 Constant *Val;
1838 SmallVector<unsigned, 4> Indices;
1839 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1840 ParseGlobalTypeAndValue(Val) ||
1841 ParseIndexList(Indices) ||
1842 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1843 return true;
1844 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1845 return Error(ID.Loc, "extractvalue operand must be array or struct");
1846 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1847 Indices.end()))
1848 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001849 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001850 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 ID.Kind = ValID::t_Constant;
1852 return false;
1853 }
1854 case lltok::kw_insertvalue: {
1855 Lex.Lex();
1856 Constant *Val0, *Val1;
1857 SmallVector<unsigned, 4> Indices;
1858 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1859 ParseGlobalTypeAndValue(Val0) ||
1860 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1861 ParseGlobalTypeAndValue(Val1) ||
1862 ParseIndexList(Indices) ||
1863 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1864 return true;
1865 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1866 return Error(ID.Loc, "extractvalue operand must be array or struct");
1867 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1868 Indices.end()))
1869 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001870 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1871 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 ID.Kind = ValID::t_Constant;
1873 return false;
1874 }
1875 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001876 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 unsigned PredVal, Opc = Lex.getUIntVal();
1878 Constant *Val0, *Val1;
1879 Lex.Lex();
1880 if (ParseCmpPredicate(PredVal, Opc) ||
1881 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1882 ParseGlobalTypeAndValue(Val0) ||
1883 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1884 ParseGlobalTypeAndValue(Val1) ||
1885 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1886 return true;
1887
1888 if (Val0->getType() != Val1->getType())
1889 return Error(ID.Loc, "compare operands must have the same type");
1890
1891 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1892
1893 if (Opc == Instruction::FCmp) {
1894 if (!Val0->getType()->isFPOrFPVector())
1895 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001896 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001897 } else {
1898 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001899 if (!Val0->getType()->isIntOrIntVector() &&
1900 !isa<PointerType>(Val0->getType()))
1901 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001902 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 }
1904 ID.Kind = ValID::t_Constant;
1905 return false;
1906 }
1907
1908 // Binary Operators.
1909 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001910 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001911 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001912 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001914 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001915 case lltok::kw_udiv:
1916 case lltok::kw_sdiv:
1917 case lltok::kw_fdiv:
1918 case lltok::kw_urem:
1919 case lltok::kw_srem:
1920 case lltok::kw_frem: {
1921 unsigned Opc = Lex.getUIntVal();
1922 Constant *Val0, *Val1;
1923 Lex.Lex();
1924 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1925 ParseGlobalTypeAndValue(Val0) ||
1926 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1927 ParseGlobalTypeAndValue(Val1) ||
1928 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1929 return true;
1930 if (Val0->getType() != Val1->getType())
1931 return Error(ID.Loc, "operands of constexpr must have same type");
1932 if (!Val0->getType()->isIntOrIntVector() &&
1933 !Val0->getType()->isFPOrFPVector())
1934 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001935 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001936 ID.Kind = ValID::t_Constant;
1937 return false;
1938 }
1939
1940 // Logical Operations
1941 case lltok::kw_shl:
1942 case lltok::kw_lshr:
1943 case lltok::kw_ashr:
1944 case lltok::kw_and:
1945 case lltok::kw_or:
1946 case lltok::kw_xor: {
1947 unsigned Opc = Lex.getUIntVal();
1948 Constant *Val0, *Val1;
1949 Lex.Lex();
1950 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1951 ParseGlobalTypeAndValue(Val0) ||
1952 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1953 ParseGlobalTypeAndValue(Val1) ||
1954 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1955 return true;
1956 if (Val0->getType() != Val1->getType())
1957 return Error(ID.Loc, "operands of constexpr must have same type");
1958 if (!Val0->getType()->isIntOrIntVector())
1959 return Error(ID.Loc,
1960 "constexpr requires integer or integer vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001961 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001962 ID.Kind = ValID::t_Constant;
1963 return false;
1964 }
1965
1966 case lltok::kw_getelementptr:
1967 case lltok::kw_shufflevector:
1968 case lltok::kw_insertelement:
1969 case lltok::kw_extractelement:
1970 case lltok::kw_select: {
1971 unsigned Opc = Lex.getUIntVal();
1972 SmallVector<Constant*, 16> Elts;
1973 Lex.Lex();
1974 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1975 ParseGlobalValueVector(Elts) ||
1976 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1977 return true;
1978
1979 if (Opc == Instruction::GetElementPtr) {
1980 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1981 return Error(ID.Loc, "getelementptr requires pointer operand");
1982
1983 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1984 (Value**)&Elts[1], Elts.size()-1))
1985 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00001986 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00001987 &Elts[1], Elts.size()-1);
1988 } else if (Opc == Instruction::Select) {
1989 if (Elts.size() != 3)
1990 return Error(ID.Loc, "expected three operands to select");
1991 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1992 Elts[2]))
1993 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00001994 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 } else if (Opc == Instruction::ShuffleVector) {
1996 if (Elts.size() != 3)
1997 return Error(ID.Loc, "expected three operands to shufflevector");
1998 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1999 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002000 ID.ConstantVal =
2001 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 } else if (Opc == Instruction::ExtractElement) {
2003 if (Elts.size() != 2)
2004 return Error(ID.Loc, "expected two operands to extractelement");
2005 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2006 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002007 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 } else {
2009 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2010 if (Elts.size() != 3)
2011 return Error(ID.Loc, "expected three operands to insertelement");
2012 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2013 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002014 ID.ConstantVal =
2015 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 }
2017
2018 ID.Kind = ValID::t_Constant;
2019 return false;
2020 }
2021 }
2022
2023 Lex.Lex();
2024 return false;
2025}
2026
2027/// ParseGlobalValue - Parse a global value with the specified type.
2028bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2029 V = 0;
2030 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002031 return ParseValID(ID) ||
2032 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002033}
2034
2035/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2036/// constant.
2037bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2038 Constant *&V) {
2039 if (isa<FunctionType>(Ty))
2040 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2041
2042 switch (ID.Kind) {
2043 default: assert(0 && "Unknown ValID!");
2044 case ValID::t_LocalID:
2045 case ValID::t_LocalName:
2046 return Error(ID.Loc, "invalid use of function-local name");
2047 case ValID::t_InlineAsm:
2048 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2049 case ValID::t_GlobalName:
2050 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2051 return V == 0;
2052 case ValID::t_GlobalID:
2053 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2054 return V == 0;
2055 case ValID::t_APSInt:
2056 if (!isa<IntegerType>(Ty))
2057 return Error(ID.Loc, "integer constant must have integer type");
2058 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002059 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 return false;
2061 case ValID::t_APFloat:
2062 if (!Ty->isFloatingPoint() ||
2063 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2064 return Error(ID.Loc, "floating point constant invalid for type");
2065
2066 // The lexer has no type info, so builds all float and double FP constants
2067 // as double. Fix this here. Long double does not need this.
2068 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2069 Ty == Type::FloatTy) {
2070 bool Ignored;
2071 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2072 &Ignored);
2073 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002074 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002075
2076 if (V->getType() != Ty)
2077 return Error(ID.Loc, "floating point constant does not have type '" +
2078 Ty->getDescription() + "'");
2079
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 return false;
2081 case ValID::t_Null:
2082 if (!isa<PointerType>(Ty))
2083 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002084 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 return false;
2086 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002087 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002088 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2089 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002090 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002091 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002093 case ValID::t_EmptyArray:
2094 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2095 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002096 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002097 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002099 // FIXME: LabelTy should not be a first-class type.
2100 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002102 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 return false;
2104 case ValID::t_Constant:
2105 if (ID.ConstantVal->getType() != Ty)
2106 return Error(ID.Loc, "constant expression type mismatch");
2107 V = ID.ConstantVal;
2108 return false;
2109 }
2110}
2111
2112bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2113 PATypeHolder Type(Type::VoidTy);
2114 return ParseType(Type) ||
2115 ParseGlobalValue(Type, V);
2116}
2117
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002118/// ParseGlobalValueVector
2119/// ::= /*empty*/
2120/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002121bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2122 // Empty list.
2123 if (Lex.getKind() == lltok::rbrace ||
2124 Lex.getKind() == lltok::rsquare ||
2125 Lex.getKind() == lltok::greater ||
2126 Lex.getKind() == lltok::rparen)
2127 return false;
2128
2129 Constant *C;
2130 if (ParseGlobalTypeAndValue(C)) return true;
2131 Elts.push_back(C);
2132
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002133 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002134 if (ParseGlobalTypeAndValue(C)) return true;
2135 Elts.push_back(C);
2136 }
2137
2138 return false;
2139}
2140
2141
2142//===----------------------------------------------------------------------===//
2143// Function Parsing.
2144//===----------------------------------------------------------------------===//
2145
2146bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2147 PerFunctionState &PFS) {
2148 if (ID.Kind == ValID::t_LocalID)
2149 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2150 else if (ID.Kind == ValID::t_LocalName)
2151 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002152 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2154 const FunctionType *FTy =
2155 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2156 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2157 return Error(ID.Loc, "invalid type for inline asm constraint string");
2158 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2159 return false;
2160 } else {
2161 Constant *C;
2162 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2163 V = C;
2164 return false;
2165 }
2166
2167 return V == 0;
2168}
2169
2170bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2171 V = 0;
2172 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002173 return ParseValID(ID) ||
2174 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002175}
2176
2177bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2178 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002179 return ParseType(T) ||
2180 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002181}
2182
2183/// FunctionHeader
2184/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2185/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2186/// OptionalAlign OptGC
2187bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2188 // Parse the linkage.
2189 LocTy LinkageLoc = Lex.getLoc();
2190 unsigned Linkage;
2191
2192 unsigned Visibility, CC, RetAttrs;
2193 PATypeHolder RetType(Type::VoidTy);
2194 LocTy RetTypeLoc = Lex.getLoc();
2195 if (ParseOptionalLinkage(Linkage) ||
2196 ParseOptionalVisibility(Visibility) ||
2197 ParseOptionalCallingConv(CC) ||
2198 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002199 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 return true;
2201
2202 // Verify that the linkage is ok.
2203 switch ((GlobalValue::LinkageTypes)Linkage) {
2204 case GlobalValue::ExternalLinkage:
2205 break; // always ok.
2206 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002207 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 if (isDefine)
2209 return Error(LinkageLoc, "invalid linkage for function definition");
2210 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002211 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002213 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002214 case GlobalValue::LinkOnceAnyLinkage:
2215 case GlobalValue::LinkOnceODRLinkage:
2216 case GlobalValue::WeakAnyLinkage:
2217 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 case GlobalValue::DLLExportLinkage:
2219 if (!isDefine)
2220 return Error(LinkageLoc, "invalid linkage for function declaration");
2221 break;
2222 case GlobalValue::AppendingLinkage:
2223 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002224 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 return Error(LinkageLoc, "invalid function linkage type");
2226 }
2227
Chris Lattner99bb3152009-01-05 08:00:30 +00002228 if (!FunctionType::isValidReturnType(RetType) ||
2229 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 return Error(RetTypeLoc, "invalid function return type");
2231
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002233
2234 std::string FunctionName;
2235 if (Lex.getKind() == lltok::GlobalVar) {
2236 FunctionName = Lex.getStrVal();
2237 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2238 unsigned NameID = Lex.getUIntVal();
2239
2240 if (NameID != NumberedVals.size())
2241 return TokError("function expected to be numbered '%" +
2242 utostr(NumberedVals.size()) + "'");
2243 } else {
2244 return TokError("expected function name");
2245 }
2246
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002247 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002248
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002249 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 return TokError("expected '(' in function argument list");
2251
2252 std::vector<ArgInfo> ArgList;
2253 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002257 std::string GC;
2258
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002259 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002260 ParseOptionalAttrs(FuncAttrs, 2) ||
2261 (EatIfPresent(lltok::kw_section) &&
2262 ParseStringConstant(Section)) ||
2263 ParseOptionalAlignment(Alignment) ||
2264 (EatIfPresent(lltok::kw_gc) &&
2265 ParseStringConstant(GC)))
2266 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002267
2268 // If the alignment was parsed as an attribute, move to the alignment field.
2269 if (FuncAttrs & Attribute::Alignment) {
2270 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2271 FuncAttrs &= ~Attribute::Alignment;
2272 }
2273
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 // Okay, if we got here, the function is syntactically valid. Convert types
2275 // and do semantic checks.
2276 std::vector<const Type*> ParamTypeList;
2277 SmallVector<AttributeWithIndex, 8> Attrs;
2278 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2279 // attributes.
2280 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2281 if (FuncAttrs & ObsoleteFuncAttrs) {
2282 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2283 FuncAttrs &= ~ObsoleteFuncAttrs;
2284 }
2285
2286 if (RetAttrs != Attribute::None)
2287 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2288
2289 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2290 ParamTypeList.push_back(ArgList[i].Type);
2291 if (ArgList[i].Attrs != Attribute::None)
2292 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2293 }
2294
2295 if (FuncAttrs != Attribute::None)
2296 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2297
2298 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2299
Chris Lattnera9a9e072009-03-09 04:49:14 +00002300 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2301 RetType != Type::VoidTy)
2302 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2303
Owen Andersonfba933c2009-07-01 23:57:11 +00002304 const FunctionType *FT =
2305 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2306 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002307
2308 Fn = 0;
2309 if (!FunctionName.empty()) {
2310 // If this was a definition of a forward reference, remove the definition
2311 // from the forward reference table and fill in the forward ref.
2312 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2313 ForwardRefVals.find(FunctionName);
2314 if (FRVI != ForwardRefVals.end()) {
2315 Fn = M->getFunction(FunctionName);
2316 ForwardRefVals.erase(FRVI);
2317 } else if ((Fn = M->getFunction(FunctionName))) {
2318 // If this function already exists in the symbol table, then it is
2319 // multiply defined. We accept a few cases for old backwards compat.
2320 // FIXME: Remove this stuff for LLVM 3.0.
2321 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2322 (!Fn->isDeclaration() && isDefine)) {
2323 // If the redefinition has different type or different attributes,
2324 // reject it. If both have bodies, reject it.
2325 return Error(NameLoc, "invalid redefinition of function '" +
2326 FunctionName + "'");
2327 } else if (Fn->isDeclaration()) {
2328 // Make sure to strip off any argument names so we can't get conflicts.
2329 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2330 AI != AE; ++AI)
2331 AI->setName("");
2332 }
2333 }
2334
2335 } else if (FunctionName.empty()) {
2336 // If this is a definition of a forward referenced function, make sure the
2337 // types agree.
2338 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2339 = ForwardRefValIDs.find(NumberedVals.size());
2340 if (I != ForwardRefValIDs.end()) {
2341 Fn = cast<Function>(I->second.first);
2342 if (Fn->getType() != PFT)
2343 return Error(NameLoc, "type of definition and forward reference of '@" +
2344 utostr(NumberedVals.size()) +"' disagree");
2345 ForwardRefValIDs.erase(I);
2346 }
2347 }
2348
2349 if (Fn == 0)
2350 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2351 else // Move the forward-reference to the correct spot in the module.
2352 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2353
2354 if (FunctionName.empty())
2355 NumberedVals.push_back(Fn);
2356
2357 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2358 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2359 Fn->setCallingConv(CC);
2360 Fn->setAttributes(PAL);
2361 Fn->setAlignment(Alignment);
2362 Fn->setSection(Section);
2363 if (!GC.empty()) Fn->setGC(GC.c_str());
2364
2365 // Add all of the arguments we parsed to the function.
2366 Function::arg_iterator ArgIt = Fn->arg_begin();
2367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2368 // If the argument has a name, insert it into the argument symbol table.
2369 if (ArgList[i].Name.empty()) continue;
2370
2371 // Set the name, if it conflicted, it will be auto-renamed.
2372 ArgIt->setName(ArgList[i].Name);
2373
2374 if (ArgIt->getNameStr() != ArgList[i].Name)
2375 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2376 ArgList[i].Name + "'");
2377 }
2378
2379 return false;
2380}
2381
2382
2383/// ParseFunctionBody
2384/// ::= '{' BasicBlock+ '}'
2385/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2386///
2387bool LLParser::ParseFunctionBody(Function &Fn) {
2388 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2389 return TokError("expected '{' in function body");
2390 Lex.Lex(); // eat the {.
2391
2392 PerFunctionState PFS(*this, Fn);
2393
2394 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2395 if (ParseBasicBlock(PFS)) return true;
2396
2397 // Eat the }.
2398 Lex.Lex();
2399
2400 // Verify function is ok.
2401 return PFS.VerifyFunctionComplete();
2402}
2403
2404/// ParseBasicBlock
2405/// ::= LabelStr? Instruction*
2406bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2407 // If this basic block starts out with a name, remember it.
2408 std::string Name;
2409 LocTy NameLoc = Lex.getLoc();
2410 if (Lex.getKind() == lltok::LabelStr) {
2411 Name = Lex.getStrVal();
2412 Lex.Lex();
2413 }
2414
2415 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2416 if (BB == 0) return true;
2417
2418 std::string NameStr;
2419
2420 // Parse the instructions in this block until we get a terminator.
2421 Instruction *Inst;
2422 do {
2423 // This instruction may have three possibilities for a name: a) none
2424 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2425 LocTy NameLoc = Lex.getLoc();
2426 int NameID = -1;
2427 NameStr = "";
2428
2429 if (Lex.getKind() == lltok::LocalVarID) {
2430 NameID = Lex.getUIntVal();
2431 Lex.Lex();
2432 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2433 return true;
2434 } else if (Lex.getKind() == lltok::LocalVar ||
2435 // FIXME: REMOVE IN LLVM 3.0
2436 Lex.getKind() == lltok::StringConstant) {
2437 NameStr = Lex.getStrVal();
2438 Lex.Lex();
2439 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2440 return true;
2441 }
2442
2443 if (ParseInstruction(Inst, BB, PFS)) return true;
2444
2445 BB->getInstList().push_back(Inst);
2446
2447 // Set the name on the instruction.
2448 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2449 } while (!isa<TerminatorInst>(Inst));
2450
2451 return false;
2452}
2453
2454//===----------------------------------------------------------------------===//
2455// Instruction Parsing.
2456//===----------------------------------------------------------------------===//
2457
2458/// ParseInstruction - Parse one of the many different instructions.
2459///
2460bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2461 PerFunctionState &PFS) {
2462 lltok::Kind Token = Lex.getKind();
2463 if (Token == lltok::Eof)
2464 return TokError("found end of file when expecting more instructions");
2465 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002466 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002467 Lex.Lex(); // Eat the keyword.
2468
2469 switch (Token) {
2470 default: return Error(Loc, "expected instruction opcode");
2471 // Terminator Instructions.
2472 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2473 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2474 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2475 case lltok::kw_br: return ParseBr(Inst, PFS);
2476 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2477 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2478 // Binary Operators.
2479 case lltok::kw_add:
2480 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002481 case lltok::kw_mul:
2482 // API compatibility: Accept either integer or floating-point types.
2483 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2484 case lltok::kw_fadd:
2485 case lltok::kw_fsub:
2486 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2487
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 case lltok::kw_udiv:
2489 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002490 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002491 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002492 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002493 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 case lltok::kw_shl:
2495 case lltok::kw_lshr:
2496 case lltok::kw_ashr:
2497 case lltok::kw_and:
2498 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002499 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002500 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002501 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002502 // Casts.
2503 case lltok::kw_trunc:
2504 case lltok::kw_zext:
2505 case lltok::kw_sext:
2506 case lltok::kw_fptrunc:
2507 case lltok::kw_fpext:
2508 case lltok::kw_bitcast:
2509 case lltok::kw_uitofp:
2510 case lltok::kw_sitofp:
2511 case lltok::kw_fptoui:
2512 case lltok::kw_fptosi:
2513 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002514 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002515 // Other.
2516 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002517 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002518 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2519 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2520 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2521 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2522 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2523 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2524 // Memory.
2525 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002526 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002527 case lltok::kw_free: return ParseFree(Inst, PFS);
2528 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2529 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2530 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002531 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002533 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002534 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002535 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002536 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2538 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2539 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2540 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2541 }
2542}
2543
2544/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2545bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002546 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 switch (Lex.getKind()) {
2548 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2549 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2550 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2551 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2552 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2553 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2554 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2555 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2556 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2557 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2558 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2559 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2560 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2561 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2562 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2563 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2564 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2565 }
2566 } else {
2567 switch (Lex.getKind()) {
2568 default: TokError("expected icmp predicate (e.g. 'eq')");
2569 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2570 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2571 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2572 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2573 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2574 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2575 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2576 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2577 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2578 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2579 }
2580 }
2581 Lex.Lex();
2582 return false;
2583}
2584
2585//===----------------------------------------------------------------------===//
2586// Terminator Instructions.
2587//===----------------------------------------------------------------------===//
2588
2589/// ParseRet - Parse a return instruction.
2590/// ::= 'ret' void
2591/// ::= 'ret' TypeAndValue
2592/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2593bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2594 PerFunctionState &PFS) {
2595 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002596 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002597
2598 if (Ty == Type::VoidTy) {
2599 Inst = ReturnInst::Create();
2600 return false;
2601 }
2602
2603 Value *RV;
2604 if (ParseValue(Ty, RV, PFS)) return true;
2605
2606 // The normal case is one return value.
2607 if (Lex.getKind() == lltok::comma) {
2608 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2609 // of 'ret {i32,i32} {i32 1, i32 2}'
2610 SmallVector<Value*, 8> RVs;
2611 RVs.push_back(RV);
2612
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002613 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 if (ParseTypeAndValue(RV, PFS)) return true;
2615 RVs.push_back(RV);
2616 }
2617
Owen Andersonb43eae72009-07-02 17:04:01 +00002618 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2620 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2621 BB->getInstList().push_back(I);
2622 RV = I;
2623 }
2624 }
2625 Inst = ReturnInst::Create(RV);
2626 return false;
2627}
2628
2629
2630/// ParseBr
2631/// ::= 'br' TypeAndValue
2632/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2633bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2634 LocTy Loc, Loc2;
2635 Value *Op0, *Op1, *Op2;
2636 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2637
2638 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2639 Inst = BranchInst::Create(BB);
2640 return false;
2641 }
2642
2643 if (Op0->getType() != Type::Int1Ty)
2644 return Error(Loc, "branch condition must have 'i1' type");
2645
2646 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2647 ParseTypeAndValue(Op1, Loc, PFS) ||
2648 ParseToken(lltok::comma, "expected ',' after true destination") ||
2649 ParseTypeAndValue(Op2, Loc2, PFS))
2650 return true;
2651
2652 if (!isa<BasicBlock>(Op1))
2653 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 if (!isa<BasicBlock>(Op2))
2655 return Error(Loc2, "true destination of branch must be a basic block");
2656
2657 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2658 return false;
2659}
2660
2661/// ParseSwitch
2662/// Instruction
2663/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2664/// JumpTable
2665/// ::= (TypeAndValue ',' TypeAndValue)*
2666bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2667 LocTy CondLoc, BBLoc;
2668 Value *Cond, *DefaultBB;
2669 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2670 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2671 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2672 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2673 return true;
2674
2675 if (!isa<IntegerType>(Cond->getType()))
2676 return Error(CondLoc, "switch condition must have integer type");
2677 if (!isa<BasicBlock>(DefaultBB))
2678 return Error(BBLoc, "default destination must be a basic block");
2679
2680 // Parse the jump table pairs.
2681 SmallPtrSet<Value*, 32> SeenCases;
2682 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2683 while (Lex.getKind() != lltok::rsquare) {
2684 Value *Constant, *DestBB;
2685
2686 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2687 ParseToken(lltok::comma, "expected ',' after case value") ||
2688 ParseTypeAndValue(DestBB, BBLoc, PFS))
2689 return true;
2690
2691 if (!SeenCases.insert(Constant))
2692 return Error(CondLoc, "duplicate case value in switch");
2693 if (!isa<ConstantInt>(Constant))
2694 return Error(CondLoc, "case value is not a constant integer");
2695 if (!isa<BasicBlock>(DestBB))
2696 return Error(BBLoc, "case destination is not a basic block");
2697
2698 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2699 cast<BasicBlock>(DestBB)));
2700 }
2701
2702 Lex.Lex(); // Eat the ']'.
2703
2704 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2705 Table.size());
2706 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2707 SI->addCase(Table[i].first, Table[i].second);
2708 Inst = SI;
2709 return false;
2710}
2711
2712/// ParseInvoke
2713/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2714/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2715bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2716 LocTy CallLoc = Lex.getLoc();
2717 unsigned CC, RetAttrs, FnAttrs;
2718 PATypeHolder RetType(Type::VoidTy);
2719 LocTy RetTypeLoc;
2720 ValID CalleeID;
2721 SmallVector<ParamInfo, 16> ArgList;
2722
2723 Value *NormalBB, *UnwindBB;
2724 if (ParseOptionalCallingConv(CC) ||
2725 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002726 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 ParseValID(CalleeID) ||
2728 ParseParameterList(ArgList, PFS) ||
2729 ParseOptionalAttrs(FnAttrs, 2) ||
2730 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2731 ParseTypeAndValue(NormalBB, PFS) ||
2732 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2733 ParseTypeAndValue(UnwindBB, PFS))
2734 return true;
2735
2736 if (!isa<BasicBlock>(NormalBB))
2737 return Error(CallLoc, "normal destination is not a basic block");
2738 if (!isa<BasicBlock>(UnwindBB))
2739 return Error(CallLoc, "unwind destination is not a basic block");
2740
2741 // If RetType is a non-function pointer type, then this is the short syntax
2742 // for the call, which means that RetType is just the return type. Infer the
2743 // rest of the function argument types from the arguments that are present.
2744 const PointerType *PFTy = 0;
2745 const FunctionType *Ty = 0;
2746 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2747 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2748 // Pull out the types of all of the arguments...
2749 std::vector<const Type*> ParamTypes;
2750 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2751 ParamTypes.push_back(ArgList[i].V->getType());
2752
2753 if (!FunctionType::isValidReturnType(RetType))
2754 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2755
Owen Andersonfba933c2009-07-01 23:57:11 +00002756 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2757 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 }
2759
2760 // Look up the callee.
2761 Value *Callee;
2762 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2763
2764 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2765 // function attributes.
2766 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2767 if (FnAttrs & ObsoleteFuncAttrs) {
2768 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2769 FnAttrs &= ~ObsoleteFuncAttrs;
2770 }
2771
2772 // Set up the Attributes for the function.
2773 SmallVector<AttributeWithIndex, 8> Attrs;
2774 if (RetAttrs != Attribute::None)
2775 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2776
2777 SmallVector<Value*, 8> Args;
2778
2779 // Loop through FunctionType's arguments and ensure they are specified
2780 // correctly. Also, gather any parameter attributes.
2781 FunctionType::param_iterator I = Ty->param_begin();
2782 FunctionType::param_iterator E = Ty->param_end();
2783 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2784 const Type *ExpectedTy = 0;
2785 if (I != E) {
2786 ExpectedTy = *I++;
2787 } else if (!Ty->isVarArg()) {
2788 return Error(ArgList[i].Loc, "too many arguments specified");
2789 }
2790
2791 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2792 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2793 ExpectedTy->getDescription() + "'");
2794 Args.push_back(ArgList[i].V);
2795 if (ArgList[i].Attrs != Attribute::None)
2796 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2797 }
2798
2799 if (I != E)
2800 return Error(CallLoc, "not enough parameters specified for call");
2801
2802 if (FnAttrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2804
2805 // Finish off the Attributes and check them
2806 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2807
2808 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2809 cast<BasicBlock>(UnwindBB),
2810 Args.begin(), Args.end());
2811 II->setCallingConv(CC);
2812 II->setAttributes(PAL);
2813 Inst = II;
2814 return false;
2815}
2816
2817
2818
2819//===----------------------------------------------------------------------===//
2820// Binary Operators.
2821//===----------------------------------------------------------------------===//
2822
2823/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002824/// ::= ArithmeticOps TypeAndValue ',' Value
2825///
2826/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2827/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002828bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002829 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002830 LocTy Loc; Value *LHS, *RHS;
2831 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2832 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2833 ParseValue(LHS->getType(), RHS, PFS))
2834 return true;
2835
Chris Lattnere914b592009-01-05 08:24:46 +00002836 bool Valid;
2837 switch (OperandType) {
2838 default: assert(0 && "Unknown operand type!");
2839 case 0: // int or FP.
2840 Valid = LHS->getType()->isIntOrIntVector() ||
2841 LHS->getType()->isFPOrFPVector();
2842 break;
2843 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2844 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2845 }
2846
2847 if (!Valid)
2848 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002849
2850 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2851 return false;
2852}
2853
2854/// ParseLogical
2855/// ::= ArithmeticOps TypeAndValue ',' Value {
2856bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2857 unsigned Opc) {
2858 LocTy Loc; Value *LHS, *RHS;
2859 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2860 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2861 ParseValue(LHS->getType(), RHS, PFS))
2862 return true;
2863
2864 if (!LHS->getType()->isIntOrIntVector())
2865 return Error(Loc,"instruction requires integer or integer vector operands");
2866
2867 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2868 return false;
2869}
2870
2871
2872/// ParseCompare
2873/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2874/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002875bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2876 unsigned Opc) {
2877 // Parse the integer/fp comparison predicate.
2878 LocTy Loc;
2879 unsigned Pred;
2880 Value *LHS, *RHS;
2881 if (ParseCmpPredicate(Pred, Opc) ||
2882 ParseTypeAndValue(LHS, Loc, PFS) ||
2883 ParseToken(lltok::comma, "expected ',' after compare value") ||
2884 ParseValue(LHS->getType(), RHS, PFS))
2885 return true;
2886
2887 if (Opc == Instruction::FCmp) {
2888 if (!LHS->getType()->isFPOrFPVector())
2889 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002890 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002891 } else {
2892 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 if (!LHS->getType()->isIntOrIntVector() &&
2894 !isa<PointerType>(LHS->getType()))
2895 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00002896 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 }
2898 return false;
2899}
2900
2901//===----------------------------------------------------------------------===//
2902// Other Instructions.
2903//===----------------------------------------------------------------------===//
2904
2905
2906/// ParseCast
2907/// ::= CastOpc TypeAndValue 'to' Type
2908bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2909 unsigned Opc) {
2910 LocTy Loc; Value *Op;
2911 PATypeHolder DestTy(Type::VoidTy);
2912 if (ParseTypeAndValue(Op, Loc, PFS) ||
2913 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2914 ParseType(DestTy))
2915 return true;
2916
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002917 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2918 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 return Error(Loc, "invalid cast opcode for cast from '" +
2920 Op->getType()->getDescription() + "' to '" +
2921 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002922 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2924 return false;
2925}
2926
2927/// ParseSelect
2928/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2929bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2930 LocTy Loc;
2931 Value *Op0, *Op1, *Op2;
2932 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after select condition") ||
2934 ParseTypeAndValue(Op1, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after select value") ||
2936 ParseTypeAndValue(Op2, PFS))
2937 return true;
2938
2939 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2940 return Error(Loc, Reason);
2941
2942 Inst = SelectInst::Create(Op0, Op1, Op2);
2943 return false;
2944}
2945
Chris Lattner0088a5c2009-01-05 08:18:44 +00002946/// ParseVA_Arg
2947/// ::= 'va_arg' TypeAndValue ',' Type
2948bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002949 Value *Op;
2950 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002951 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002952 if (ParseTypeAndValue(Op, PFS) ||
2953 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002954 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002955 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002956
2957 if (!EltTy->isFirstClassType())
2958 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002959
2960 Inst = new VAArgInst(Op, EltTy);
2961 return false;
2962}
2963
2964/// ParseExtractElement
2965/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2966bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2967 LocTy Loc;
2968 Value *Op0, *Op1;
2969 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after extract value") ||
2971 ParseTypeAndValue(Op1, PFS))
2972 return true;
2973
2974 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2975 return Error(Loc, "invalid extractelement operands");
2976
2977 Inst = new ExtractElementInst(Op0, Op1);
2978 return false;
2979}
2980
2981/// ParseInsertElement
2982/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2983bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2984 LocTy Loc;
2985 Value *Op0, *Op1, *Op2;
2986 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2987 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2988 ParseTypeAndValue(Op1, PFS) ||
2989 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2990 ParseTypeAndValue(Op2, PFS))
2991 return true;
2992
2993 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2994 return Error(Loc, "invalid extractelement operands");
2995
2996 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2997 return false;
2998}
2999
3000/// ParseShuffleVector
3001/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3002bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3003 LocTy Loc;
3004 Value *Op0, *Op1, *Op2;
3005 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3006 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3007 ParseTypeAndValue(Op1, PFS) ||
3008 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3009 ParseTypeAndValue(Op2, PFS))
3010 return true;
3011
3012 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3013 return Error(Loc, "invalid extractelement operands");
3014
3015 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3016 return false;
3017}
3018
3019/// ParsePHI
3020/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3021bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3022 PATypeHolder Ty(Type::VoidTy);
3023 Value *Op0, *Op1;
3024 LocTy TypeLoc = Lex.getLoc();
3025
3026 if (ParseType(Ty) ||
3027 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3028 ParseValue(Ty, Op0, PFS) ||
3029 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3030 ParseValue(Type::LabelTy, Op1, PFS) ||
3031 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3032 return true;
3033
3034 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3035 while (1) {
3036 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3037
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003038 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003039 break;
3040
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003041 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 ParseValue(Ty, Op0, PFS) ||
3043 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3044 ParseValue(Type::LabelTy, Op1, PFS) ||
3045 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3046 return true;
3047 }
3048
3049 if (!Ty->isFirstClassType())
3050 return Error(TypeLoc, "phi node must have first class type");
3051
3052 PHINode *PN = PHINode::Create(Ty);
3053 PN->reserveOperandSpace(PHIVals.size());
3054 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3055 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3056 Inst = PN;
3057 return false;
3058}
3059
3060/// ParseCall
3061/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3062/// ParameterList OptionalAttrs
3063bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3064 bool isTail) {
3065 unsigned CC, RetAttrs, FnAttrs;
3066 PATypeHolder RetType(Type::VoidTy);
3067 LocTy RetTypeLoc;
3068 ValID CalleeID;
3069 SmallVector<ParamInfo, 16> ArgList;
3070 LocTy CallLoc = Lex.getLoc();
3071
3072 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3073 ParseOptionalCallingConv(CC) ||
3074 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003075 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 ParseValID(CalleeID) ||
3077 ParseParameterList(ArgList, PFS) ||
3078 ParseOptionalAttrs(FnAttrs, 2))
3079 return true;
3080
3081 // If RetType is a non-function pointer type, then this is the short syntax
3082 // for the call, which means that RetType is just the return type. Infer the
3083 // rest of the function argument types from the arguments that are present.
3084 const PointerType *PFTy = 0;
3085 const FunctionType *Ty = 0;
3086 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3087 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3088 // Pull out the types of all of the arguments...
3089 std::vector<const Type*> ParamTypes;
3090 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3091 ParamTypes.push_back(ArgList[i].V->getType());
3092
3093 if (!FunctionType::isValidReturnType(RetType))
3094 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3095
Owen Andersonfba933c2009-07-01 23:57:11 +00003096 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3097 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 }
3099
3100 // Look up the callee.
3101 Value *Callee;
3102 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3105 // function attributes.
3106 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3107 if (FnAttrs & ObsoleteFuncAttrs) {
3108 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3109 FnAttrs &= ~ObsoleteFuncAttrs;
3110 }
3111
3112 // Set up the Attributes for the function.
3113 SmallVector<AttributeWithIndex, 8> Attrs;
3114 if (RetAttrs != Attribute::None)
3115 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3116
3117 SmallVector<Value*, 8> Args;
3118
3119 // Loop through FunctionType's arguments and ensure they are specified
3120 // correctly. Also, gather any parameter attributes.
3121 FunctionType::param_iterator I = Ty->param_begin();
3122 FunctionType::param_iterator E = Ty->param_end();
3123 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3124 const Type *ExpectedTy = 0;
3125 if (I != E) {
3126 ExpectedTy = *I++;
3127 } else if (!Ty->isVarArg()) {
3128 return Error(ArgList[i].Loc, "too many arguments specified");
3129 }
3130
3131 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3132 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3133 ExpectedTy->getDescription() + "'");
3134 Args.push_back(ArgList[i].V);
3135 if (ArgList[i].Attrs != Attribute::None)
3136 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3137 }
3138
3139 if (I != E)
3140 return Error(CallLoc, "not enough parameters specified for call");
3141
3142 if (FnAttrs != Attribute::None)
3143 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3144
3145 // Finish off the Attributes and check them
3146 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3147
3148 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3149 CI->setTailCall(isTail);
3150 CI->setCallingConv(CC);
3151 CI->setAttributes(PAL);
3152 Inst = CI;
3153 return false;
3154}
3155
3156//===----------------------------------------------------------------------===//
3157// Memory Instructions.
3158//===----------------------------------------------------------------------===//
3159
3160/// ParseAlloc
3161/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3162/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3163bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3164 unsigned Opc) {
3165 PATypeHolder Ty(Type::VoidTy);
3166 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003167 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003168 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003169 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003170
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003171 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003172 if (Lex.getKind() == lltok::kw_align) {
3173 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003174 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3175 ParseOptionalCommaAlignment(Alignment)) {
3176 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003177 }
3178 }
3179
3180 if (Size && Size->getType() != Type::Int32Ty)
3181 return Error(SizeLoc, "element count must be i32");
3182
3183 if (Opc == Instruction::Malloc)
3184 Inst = new MallocInst(Ty, Size, Alignment);
3185 else
3186 Inst = new AllocaInst(Ty, Size, Alignment);
3187 return false;
3188}
3189
3190/// ParseFree
3191/// ::= 'free' TypeAndValue
3192bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3193 Value *Val; LocTy Loc;
3194 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3195 if (!isa<PointerType>(Val->getType()))
3196 return Error(Loc, "operand to free must be a pointer");
3197 Inst = new FreeInst(Val);
3198 return false;
3199}
3200
3201/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003202/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003203bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3204 bool isVolatile) {
3205 Value *Val; LocTy Loc;
3206 unsigned Alignment;
3207 if (ParseTypeAndValue(Val, Loc, PFS) ||
3208 ParseOptionalCommaAlignment(Alignment))
3209 return true;
3210
3211 if (!isa<PointerType>(Val->getType()) ||
3212 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3213 return Error(Loc, "load operand must be a pointer to a first class type");
3214
3215 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3216 return false;
3217}
3218
3219/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003220/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003221bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3222 bool isVolatile) {
3223 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3224 unsigned Alignment;
3225 if (ParseTypeAndValue(Val, Loc, PFS) ||
3226 ParseToken(lltok::comma, "expected ',' after store operand") ||
3227 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3228 ParseOptionalCommaAlignment(Alignment))
3229 return true;
3230
3231 if (!isa<PointerType>(Ptr->getType()))
3232 return Error(PtrLoc, "store operand must be a pointer");
3233 if (!Val->getType()->isFirstClassType())
3234 return Error(Loc, "store operand must be a first class value");
3235 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3236 return Error(Loc, "stored value and pointer type do not match");
3237
3238 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3239 return false;
3240}
3241
3242/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003243/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003244/// FIXME: Remove support for getresult in LLVM 3.0
3245bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3246 Value *Val; LocTy ValLoc, EltLoc;
3247 unsigned Element;
3248 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3249 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003250 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 return true;
3252
3253 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3254 return Error(ValLoc, "getresult inst requires an aggregate operand");
3255 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3256 return Error(EltLoc, "invalid getresult index for value");
3257 Inst = ExtractValueInst::Create(Val, Element);
3258 return false;
3259}
3260
3261/// ParseGetElementPtr
3262/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3263bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3264 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003265 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003266
3267 if (!isa<PointerType>(Ptr->getType()))
3268 return Error(Loc, "base of getelementptr must be a pointer");
3269
3270 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003271 while (EatIfPresent(lltok::comma)) {
3272 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 if (!isa<IntegerType>(Val->getType()))
3274 return Error(EltLoc, "getelementptr index must be an integer");
3275 Indices.push_back(Val);
3276 }
3277
3278 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3279 Indices.begin(), Indices.end()))
3280 return Error(Loc, "invalid getelementptr indices");
3281 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3282 return false;
3283}
3284
3285/// ParseExtractValue
3286/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3287bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3288 Value *Val; LocTy Loc;
3289 SmallVector<unsigned, 4> Indices;
3290 if (ParseTypeAndValue(Val, Loc, PFS) ||
3291 ParseIndexList(Indices))
3292 return true;
3293
3294 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3295 return Error(Loc, "extractvalue operand must be array or struct");
3296
3297 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3298 Indices.end()))
3299 return Error(Loc, "invalid indices for extractvalue");
3300 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3301 return false;
3302}
3303
3304/// ParseInsertValue
3305/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3306bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3307 Value *Val0, *Val1; LocTy Loc0, Loc1;
3308 SmallVector<unsigned, 4> Indices;
3309 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3310 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3311 ParseTypeAndValue(Val1, Loc1, PFS) ||
3312 ParseIndexList(Indices))
3313 return true;
3314
3315 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3316 return Error(Loc0, "extractvalue operand must be array or struct");
3317
3318 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3319 Indices.end()))
3320 return Error(Loc0, "invalid indices for insertvalue");
3321 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3322 return false;
3323}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003324
3325//===----------------------------------------------------------------------===//
3326// Embedded metadata.
3327//===----------------------------------------------------------------------===//
3328
3329/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003330/// ::= Element (',' Element)*
3331/// Element
3332/// ::= 'null' | TypeAndValue
3333bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003334 assert(Lex.getKind() == lltok::lbrace);
3335 Lex.Lex();
3336 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003337 Value *V;
3338 if (Lex.getKind() == lltok::kw_null) {
3339 Lex.Lex();
3340 V = 0;
3341 } else {
3342 Constant *C;
3343 if (ParseGlobalTypeAndValue(C)) return true;
3344 V = C;
3345 }
3346 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003347 } while (EatIfPresent(lltok::comma));
3348
3349 return false;
3350}