blob: 8c30ab5a7015dc7ae3001994c803ca92c7670a25 [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
87 // Look for intrinsic functions and CallInst that need to be upgraded
88 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
89 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
90
91 return false;
92}
93
94//===----------------------------------------------------------------------===//
95// Top-Level Entities
96//===----------------------------------------------------------------------===//
97
98bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +000099 while (1) {
100 switch (Lex.getKind()) {
101 default: return TokError("expected top-level entity");
102 case lltok::Eof: return false;
103 //case lltok::kw_define:
104 case lltok::kw_declare: if (ParseDeclare()) return true; break;
105 case lltok::kw_define: if (ParseDefine()) return true; break;
106 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
107 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
108 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
109 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
110 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
111 case lltok::LocalVar: if (ParseNamedType()) return true; break;
112 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000113 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000114
115 // The Global variable production with no name can have many different
116 // optional leading prefixes, the production is:
117 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
118 // OptionalAddrSpace ('constant'|'global') ...
Rafael Espindolabb46f522009-01-15 20:18:42 +0000119 case lltok::kw_private: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 case lltok::kw_internal: // OptionalLinkage
121 case lltok::kw_weak: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000122 case lltok::kw_weak_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::kw_linkonce: // OptionalLinkage
Duncan Sands667d4b82009-03-07 15:45:40 +0000124 case lltok::kw_linkonce_odr: // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000125 case lltok::kw_appending: // OptionalLinkage
126 case lltok::kw_dllexport: // OptionalLinkage
127 case lltok::kw_common: // OptionalLinkage
128 case lltok::kw_dllimport: // OptionalLinkage
129 case lltok::kw_extern_weak: // OptionalLinkage
130 case lltok::kw_external: { // OptionalLinkage
131 unsigned Linkage, Visibility;
132 if (ParseOptionalLinkage(Linkage) ||
133 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000134 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000135 return true;
136 break;
137 }
138 case lltok::kw_default: // OptionalVisibility
139 case lltok::kw_hidden: // OptionalVisibility
140 case lltok::kw_protected: { // OptionalVisibility
141 unsigned Visibility;
142 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000143 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000144 return true;
145 break;
146 }
147
148 case lltok::kw_thread_local: // OptionalThreadLocal
149 case lltok::kw_addrspace: // OptionalAddrSpace
150 case lltok::kw_constant: // GlobalType
151 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000152 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000153 break;
154 }
155 }
156}
157
158
159/// toplevelentity
160/// ::= 'module' 'asm' STRINGCONSTANT
161bool LLParser::ParseModuleAsm() {
162 assert(Lex.getKind() == lltok::kw_module);
163 Lex.Lex();
164
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000165 std::string AsmStr;
166 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
167 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168
169 const std::string &AsmSoFar = M->getModuleInlineAsm();
170 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000171 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000172 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000173 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000174 return false;
175}
176
177/// toplevelentity
178/// ::= 'target' 'triple' '=' STRINGCONSTANT
179/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
180bool LLParser::ParseTargetDefinition() {
181 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000183 switch (Lex.Lex()) {
184 default: return TokError("unknown target property");
185 case lltok::kw_triple:
186 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
188 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000189 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000190 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 return false;
192 case lltok::kw_datalayout:
193 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000194 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
195 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000196 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000197 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000198 return false;
199 }
200}
201
202/// toplevelentity
203/// ::= 'deplibs' '=' '[' ']'
204/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
205bool LLParser::ParseDepLibs() {
206 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000208 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
209 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
210 return true;
211
212 if (EatIfPresent(lltok::rsquare))
213 return false;
214
215 std::string Str;
216 if (ParseStringConstant(Str)) return true;
217 M->addLibrary(Str);
218
219 while (EatIfPresent(lltok::comma)) {
220 if (ParseStringConstant(Str)) return true;
221 M->addLibrary(Str);
222 }
223
224 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000225}
226
227/// toplevelentity
228/// ::= 'type' type
229bool LLParser::ParseUnnamedType() {
230 assert(Lex.getKind() == lltok::kw_type);
231 LocTy TypeLoc = Lex.getLoc();
232 Lex.Lex(); // eat kw_type
233
234 PATypeHolder Ty(Type::VoidTy);
235 if (ParseType(Ty)) return true;
236
237 unsigned TypeID = NumberedTypes.size();
238
Chris Lattnerdf986172009-01-02 07:01:27 +0000239 // See if this type was previously referenced.
240 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
241 FI = ForwardRefTypeIDs.find(TypeID);
242 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000243 if (FI->second.first.get() == Ty)
244 return Error(TypeLoc, "self referential type is invalid");
245
Chris Lattnerdf986172009-01-02 07:01:27 +0000246 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
247 Ty = FI->second.first.get();
248 ForwardRefTypeIDs.erase(FI);
249 }
250
251 NumberedTypes.push_back(Ty);
252
253 return false;
254}
255
256/// toplevelentity
257/// ::= LocalVar '=' 'type' type
258bool LLParser::ParseNamedType() {
259 std::string Name = Lex.getStrVal();
260 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000262
263 PATypeHolder Ty(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000264
265 if (ParseToken(lltok::equal, "expected '=' after name") ||
266 ParseToken(lltok::kw_type, "expected 'type' after name") ||
267 ParseType(Ty))
268 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000269
Chris Lattnerdf986172009-01-02 07:01:27 +0000270 // Set the type name, checking for conflicts as we do so.
271 bool AlreadyExists = M->addTypeName(Name, Ty);
272 if (!AlreadyExists) return false;
273
274 // See if this type is a forward reference. We need to eagerly resolve
275 // types to allow recursive type redefinitions below.
276 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
277 FI = ForwardRefTypes.find(Name);
278 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000279 if (FI->second.first.get() == Ty)
280 return Error(NameLoc, "self referential type is invalid");
281
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
283 Ty = FI->second.first.get();
284 ForwardRefTypes.erase(FI);
285 }
286
287 // Inserting a name that is already defined, get the existing name.
288 const Type *Existing = M->getTypeByName(Name);
289 assert(Existing && "Conflict but no matching type?!");
290
291 // Otherwise, this is an attempt to redefine a type. That's okay if
292 // the redefinition is identical to the original.
293 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
294 if (Existing == Ty) return false;
295
296 // Any other kind of (non-equivalent) redefinition is an error.
297 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
298 Ty->getDescription() + "'");
299}
300
301
302/// toplevelentity
303/// ::= 'declare' FunctionHeader
304bool LLParser::ParseDeclare() {
305 assert(Lex.getKind() == lltok::kw_declare);
306 Lex.Lex();
307
308 Function *F;
309 return ParseFunctionHeader(F, false);
310}
311
312/// toplevelentity
313/// ::= 'define' FunctionHeader '{' ...
314bool LLParser::ParseDefine() {
315 assert(Lex.getKind() == lltok::kw_define);
316 Lex.Lex();
317
318 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000319 return ParseFunctionHeader(F, true) ||
320 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000321}
322
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000323/// ParseGlobalType
324/// ::= 'constant'
325/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000326bool LLParser::ParseGlobalType(bool &IsConstant) {
327 if (Lex.getKind() == lltok::kw_constant)
328 IsConstant = true;
329 else if (Lex.getKind() == lltok::kw_global)
330 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000331 else {
332 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000334 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000335 Lex.Lex();
336 return false;
337}
338
339/// ParseNamedGlobal:
340/// GlobalVar '=' OptionalVisibility ALIAS ...
341/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
346 Lex.Lex();
347
348 bool HasLinkage;
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
353 return true;
354
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
358}
359
Devang Patel923078c2009-07-01 19:21:12 +0000360/// ParseStandaloneMetadata:
361/// !42 = !{...}
362bool LLParser::ParseStandaloneMetadata() {
363 assert(Lex.getKind() == lltok::Metadata);
364 Lex.Lex();
365 unsigned MetadataID = 0;
366 if (ParseUInt32(MetadataID))
367 return true;
368 if (MetadataCache.find(MetadataID) != MetadataCache.end())
369 return TokError("Metadata id is already used");
370 if (ParseToken(lltok::equal, "expected '=' here"))
371 return true;
372
373 LocTy TyLoc;
374 bool IsConstant;
375 PATypeHolder Ty(Type::VoidTy);
376 if (ParseGlobalType(IsConstant) ||
377 ParseType(Ty, TyLoc))
378 return true;
379
380 Constant *Init = 0;
381 if (ParseGlobalValue(Ty, Init))
382 return true;
383
384 MetadataCache[MetadataID] = Init;
385 return false;
386}
387
Chris Lattnerdf986172009-01-02 07:01:27 +0000388/// ParseAlias:
389/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
390/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000391/// ::= TypeAndValue
392/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
393/// ::= 'getelementptr' '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000394///
395/// Everything through visibility has already been parsed.
396///
397bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
398 unsigned Visibility) {
399 assert(Lex.getKind() == lltok::kw_alias);
400 Lex.Lex();
401 unsigned Linkage;
402 LocTy LinkageLoc = Lex.getLoc();
403 if (ParseOptionalLinkage(Linkage))
404 return true;
405
406 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000407 Linkage != GlobalValue::WeakAnyLinkage &&
408 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000409 Linkage != GlobalValue::InternalLinkage &&
410 Linkage != GlobalValue::PrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000411 return Error(LinkageLoc, "invalid linkage type for alias");
412
413 Constant *Aliasee;
414 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000415 if (Lex.getKind() != lltok::kw_bitcast &&
416 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000417 if (ParseGlobalTypeAndValue(Aliasee)) return true;
418 } else {
419 // The bitcast dest type is not present, it is implied by the dest type.
420 ValID ID;
421 if (ParseValID(ID)) return true;
422 if (ID.Kind != ValID::t_Constant)
423 return Error(AliaseeLoc, "invalid aliasee");
424 Aliasee = ID.ConstantVal;
425 }
426
427 if (!isa<PointerType>(Aliasee->getType()))
428 return Error(AliaseeLoc, "alias must have pointer type");
429
430 // Okay, create the alias but do not insert it into the module yet.
431 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
432 (GlobalValue::LinkageTypes)Linkage, Name,
433 Aliasee);
434 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
435
436 // See if this value already exists in the symbol table. If so, it is either
437 // a redefinition or a definition of a forward reference.
438 if (GlobalValue *Val =
439 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
440 // See if this was a redefinition. If so, there is no entry in
441 // ForwardRefVals.
442 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
443 I = ForwardRefVals.find(Name);
444 if (I == ForwardRefVals.end())
445 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
446
447 // Otherwise, this was a definition of forward ref. Verify that types
448 // agree.
449 if (Val->getType() != GA->getType())
450 return Error(NameLoc,
451 "forward reference and definition of alias have different types");
452
453 // If they agree, just RAUW the old value with the alias and remove the
454 // forward ref info.
455 Val->replaceAllUsesWith(GA);
456 Val->eraseFromParent();
457 ForwardRefVals.erase(I);
458 }
459
460 // Insert into the module, we know its name won't collide now.
461 M->getAliasList().push_back(GA);
462 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
463
464 return false;
465}
466
467/// ParseGlobal
468/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
469/// OptionalAddrSpace GlobalType Type Const
470/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
471/// OptionalAddrSpace GlobalType Type Const
472///
473/// Everything through visibility has been parsed already.
474///
475bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
476 unsigned Linkage, bool HasLinkage,
477 unsigned Visibility) {
478 unsigned AddrSpace;
479 bool ThreadLocal, IsConstant;
480 LocTy TyLoc;
481
482 PATypeHolder Ty(Type::VoidTy);
483 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
484 ParseOptionalAddrSpace(AddrSpace) ||
485 ParseGlobalType(IsConstant) ||
486 ParseType(Ty, TyLoc))
487 return true;
488
489 // If the linkage is specified and is external, then no initializer is
490 // present.
491 Constant *Init = 0;
492 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000493 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000494 Linkage != GlobalValue::ExternalLinkage)) {
495 if (ParseGlobalValue(Ty, Init))
496 return true;
497 }
498
Chris Lattnera9a9e072009-03-09 04:49:14 +0000499 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
Chris Lattner4a2f1122009-02-08 20:00:15 +0000500 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000501
502 GlobalVariable *GV = 0;
503
504 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000505 if (!Name.empty()) {
506 if ((GV = M->getGlobalVariable(Name, true)) &&
507 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000508 return Error(NameLoc, "redefinition of global '@" + Name + "'");
509 } else {
510 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefValIDs.find(NumberedVals.size());
512 if (I != ForwardRefValIDs.end()) {
513 GV = cast<GlobalVariable>(I->second.first);
514 ForwardRefValIDs.erase(I);
515 }
516 }
517
518 if (GV == 0) {
Owen Anderson3d29df32009-07-08 01:26:06 +0000519 GV = new GlobalVariable(Context, Ty, false,
520 GlobalValue::ExternalLinkage, 0, Name,
Chris Lattnerdf986172009-01-02 07:01:27 +0000521 M, false, AddrSpace);
522 } else {
523 if (GV->getType()->getElementType() != Ty)
524 return Error(TyLoc,
525 "forward reference and definition of global have different types");
526
527 // Move the forward-reference to the correct spot in the module.
528 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
529 }
530
531 if (Name.empty())
532 NumberedVals.push_back(GV);
533
534 // Set the parsed properties on the global.
535 if (Init)
536 GV->setInitializer(Init);
537 GV->setConstant(IsConstant);
538 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
539 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
540 GV->setThreadLocal(ThreadLocal);
541
542 // Parse attributes on the global.
543 while (Lex.getKind() == lltok::comma) {
544 Lex.Lex();
545
546 if (Lex.getKind() == lltok::kw_section) {
547 Lex.Lex();
548 GV->setSection(Lex.getStrVal());
549 if (ParseToken(lltok::StringConstant, "expected global section string"))
550 return true;
551 } else if (Lex.getKind() == lltok::kw_align) {
552 unsigned Alignment;
553 if (ParseOptionalAlignment(Alignment)) return true;
554 GV->setAlignment(Alignment);
555 } else {
556 TokError("unknown global variable property!");
557 }
558 }
559
560 return false;
561}
562
563
564//===----------------------------------------------------------------------===//
565// GlobalValue Reference/Resolution Routines.
566//===----------------------------------------------------------------------===//
567
568/// GetGlobalVal - Get a value with the specified name or ID, creating a
569/// forward reference record if needed. This can return null if the value
570/// exists but does not have the right type.
571GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
572 LocTy Loc) {
573 const PointerType *PTy = dyn_cast<PointerType>(Ty);
574 if (PTy == 0) {
575 Error(Loc, "global variable reference must have pointer type");
576 return 0;
577 }
578
579 // Look this name up in the normal function symbol table.
580 GlobalValue *Val =
581 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
582
583 // If this is a forward reference for the value, see if we already created a
584 // forward ref record.
585 if (Val == 0) {
586 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
587 I = ForwardRefVals.find(Name);
588 if (I != ForwardRefVals.end())
589 Val = I->second.first;
590 }
591
592 // If we have the value in the symbol table or fwd-ref table, return it.
593 if (Val) {
594 if (Val->getType() == Ty) return Val;
595 Error(Loc, "'@" + Name + "' defined with type '" +
596 Val->getType()->getDescription() + "'");
597 return 0;
598 }
599
600 // Otherwise, create a new forward reference for this value and remember it.
601 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000602 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
603 // Function types can return opaque but functions can't.
604 if (isa<OpaqueType>(FT->getReturnType())) {
605 Error(Loc, "function may not return opaque type");
606 return 0;
607 }
608
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000609 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000610 } else {
Owen Anderson3d29df32009-07-08 01:26:06 +0000611 FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000612 GlobalValue::ExternalWeakLinkage, 0, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000613 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000614
615 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
616 return FwdVal;
617}
618
619GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
620 const PointerType *PTy = dyn_cast<PointerType>(Ty);
621 if (PTy == 0) {
622 Error(Loc, "global variable reference must have pointer type");
623 return 0;
624 }
625
626 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
627
628 // If this is a forward reference for the value, see if we already created a
629 // forward ref record.
630 if (Val == 0) {
631 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
632 I = ForwardRefValIDs.find(ID);
633 if (I != ForwardRefValIDs.end())
634 Val = I->second.first;
635 }
636
637 // If we have the value in the symbol table or fwd-ref table, return it.
638 if (Val) {
639 if (Val->getType() == Ty) return Val;
640 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
641 Val->getType()->getDescription() + "'");
642 return 0;
643 }
644
645 // Otherwise, create a new forward reference for this value and remember it.
646 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000647 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
648 // Function types can return opaque but functions can't.
649 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000650 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000651 return 0;
652 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000653 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000654 } else {
Owen Anderson3d29df32009-07-08 01:26:06 +0000655 FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000656 GlobalValue::ExternalWeakLinkage, 0, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000657 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000658
659 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
660 return FwdVal;
661}
662
663
664//===----------------------------------------------------------------------===//
665// Helper Routines.
666//===----------------------------------------------------------------------===//
667
668/// ParseToken - If the current token has the specified kind, eat it and return
669/// success. Otherwise, emit the specified error and return failure.
670bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
671 if (Lex.getKind() != T)
672 return TokError(ErrMsg);
673 Lex.Lex();
674 return false;
675}
676
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000677/// ParseStringConstant
678/// ::= StringConstant
679bool LLParser::ParseStringConstant(std::string &Result) {
680 if (Lex.getKind() != lltok::StringConstant)
681 return TokError("expected string constant");
682 Result = Lex.getStrVal();
683 Lex.Lex();
684 return false;
685}
686
687/// ParseUInt32
688/// ::= uint32
689bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000690 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
691 return TokError("expected integer");
692 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
693 if (Val64 != unsigned(Val64))
694 return TokError("expected 32-bit integer (too large)");
695 Val = Val64;
696 Lex.Lex();
697 return false;
698}
699
700
701/// ParseOptionalAddrSpace
702/// := /*empty*/
703/// := 'addrspace' '(' uint32 ')'
704bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
705 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000706 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000707 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000708 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000709 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 ParseToken(lltok::rparen, "expected ')' in address space");
711}
712
713/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
714/// indicates what kind of attribute list this is: 0: function arg, 1: result,
715/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000716/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000717bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
718 Attrs = Attribute::None;
719 LocTy AttrLoc = Lex.getLoc();
720
721 while (1) {
722 switch (Lex.getKind()) {
723 case lltok::kw_sext:
724 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000725 // Treat these as signext/zeroext if they occur in the argument list after
726 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
727 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
728 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000729 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000730 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000731 if (Lex.getKind() == lltok::kw_sext)
732 Attrs |= Attribute::SExt;
733 else
734 Attrs |= Attribute::ZExt;
735 break;
736 }
737 // FALL THROUGH.
738 default: // End of attributes.
739 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
740 return Error(AttrLoc, "invalid use of function-only attribute");
741
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000742 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000743 return Error(AttrLoc, "invalid use of parameter-only attribute");
744
745 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000746 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
747 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
748 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
749 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
750 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
751 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
752 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
753 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000754
Devang Patel578efa92009-06-05 21:57:13 +0000755 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
756 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
757 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
758 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
759 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
760 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
761 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
762 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
763 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
764 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
765 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000766
767 case lltok::kw_align: {
768 unsigned Alignment;
769 if (ParseOptionalAlignment(Alignment))
770 return true;
771 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
772 continue;
773 }
774 }
775 Lex.Lex();
776 }
777}
778
779/// ParseOptionalLinkage
780/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000781/// ::= 'private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000782/// ::= 'internal'
783/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000784/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000785/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000786/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000787/// ::= 'appending'
788/// ::= 'dllexport'
789/// ::= 'common'
790/// ::= 'dllimport'
791/// ::= 'extern_weak'
792/// ::= 'external'
793bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
794 HasLinkage = false;
795 switch (Lex.getKind()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000796 default: Res = GlobalValue::ExternalLinkage; return false;
797 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
798 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
799 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
800 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
801 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
802 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000803 case lltok::kw_available_externally:
804 Res = GlobalValue::AvailableExternallyLinkage;
805 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000806 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
807 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000808 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000809 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000810 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000811 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 }
813 Lex.Lex();
814 HasLinkage = true;
815 return false;
816}
817
818/// ParseOptionalVisibility
819/// ::= /*empty*/
820/// ::= 'default'
821/// ::= 'hidden'
822/// ::= 'protected'
823///
824bool LLParser::ParseOptionalVisibility(unsigned &Res) {
825 switch (Lex.getKind()) {
826 default: Res = GlobalValue::DefaultVisibility; return false;
827 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
828 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
829 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
830 }
831 Lex.Lex();
832 return false;
833}
834
835/// ParseOptionalCallingConv
836/// ::= /*empty*/
837/// ::= 'ccc'
838/// ::= 'fastcc'
839/// ::= 'coldcc'
840/// ::= 'x86_stdcallcc'
841/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000842/// ::= 'arm_apcscc'
843/// ::= 'arm_aapcscc'
844/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000845/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000846///
Chris Lattnerdf986172009-01-02 07:01:27 +0000847bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
848 switch (Lex.getKind()) {
849 default: CC = CallingConv::C; return false;
850 case lltok::kw_ccc: CC = CallingConv::C; break;
851 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
852 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
853 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
854 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000855 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
856 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
857 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000858 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 }
860 Lex.Lex();
861 return false;
862}
863
864/// ParseOptionalAlignment
865/// ::= /* empty */
866/// ::= 'align' 4
867bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
868 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000869 if (!EatIfPresent(lltok::kw_align))
870 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +0000871 LocTy AlignLoc = Lex.getLoc();
872 if (ParseUInt32(Alignment)) return true;
873 if (!isPowerOf2_32(Alignment))
874 return Error(AlignLoc, "alignment is not a power of two");
875 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000876}
877
878/// ParseOptionalCommaAlignment
879/// ::= /* empty */
880/// ::= ',' 'align' 4
881bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
882 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000883 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +0000884 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000885 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000886 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +0000887}
888
889/// ParseIndexList
890/// ::= (',' uint32)+
891bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
892 if (Lex.getKind() != lltok::comma)
893 return TokError("expected ',' as start of index list");
894
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000895 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000897 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000898 Indices.push_back(Idx);
899 }
900
901 return false;
902}
903
904//===----------------------------------------------------------------------===//
905// Type Parsing.
906//===----------------------------------------------------------------------===//
907
908/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +0000909bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
910 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000911 if (ParseTypeRec(Result)) return true;
912
913 // Verify no unresolved uprefs.
914 if (!UpRefs.empty())
915 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +0000916
Chris Lattnera9a9e072009-03-09 04:49:14 +0000917 if (!AllowVoid && Result.get() == Type::VoidTy)
918 return Error(TypeLoc, "void type only allowed for function results");
919
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 return false;
921}
922
923/// HandleUpRefs - Every time we finish a new layer of types, this function is
924/// called. It loops through the UpRefs vector, which is a list of the
925/// currently active types. For each type, if the up-reference is contained in
926/// the newly completed type, we decrement the level count. When the level
927/// count reaches zero, the up-referenced type is the type that is passed in:
928/// thus we can complete the cycle.
929///
930PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
931 // If Ty isn't abstract, or if there are no up-references in it, then there is
932 // nothing to resolve here.
933 if (!ty->isAbstract() || UpRefs.empty()) return ty;
934
935 PATypeHolder Ty(ty);
936#if 0
937 errs() << "Type '" << Ty->getDescription()
938 << "' newly formed. Resolving upreferences.\n"
939 << UpRefs.size() << " upreferences active!\n";
940#endif
941
942 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
943 // to zero), we resolve them all together before we resolve them to Ty. At
944 // the end of the loop, if there is anything to resolve to Ty, it will be in
945 // this variable.
946 OpaqueType *TypeToResolve = 0;
947
948 for (unsigned i = 0; i != UpRefs.size(); ++i) {
949 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
950 bool ContainsType =
951 std::find(Ty->subtype_begin(), Ty->subtype_end(),
952 UpRefs[i].LastContainedTy) != Ty->subtype_end();
953
954#if 0
955 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
956 << UpRefs[i].LastContainedTy->getDescription() << ") = "
957 << (ContainsType ? "true" : "false")
958 << " level=" << UpRefs[i].NestingLevel << "\n";
959#endif
960 if (!ContainsType)
961 continue;
962
963 // Decrement level of upreference
964 unsigned Level = --UpRefs[i].NestingLevel;
965 UpRefs[i].LastContainedTy = Ty;
966
967 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
968 if (Level != 0)
969 continue;
970
971#if 0
972 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
973#endif
974 if (!TypeToResolve)
975 TypeToResolve = UpRefs[i].UpRefTy;
976 else
977 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
978 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
979 --i; // Do not skip the next element.
980 }
981
982 if (TypeToResolve)
983 TypeToResolve->refineAbstractTypeTo(Ty);
984
985 return Ty;
986}
987
988
989/// ParseTypeRec - The recursive function used to process the internal
990/// implementation details of types.
991bool LLParser::ParseTypeRec(PATypeHolder &Result) {
992 switch (Lex.getKind()) {
993 default:
994 return TokError("expected type");
995 case lltok::Type:
996 // TypeRec ::= 'float' | 'void' (etc)
997 Result = Lex.getTyVal();
998 Lex.Lex();
999 break;
1000 case lltok::kw_opaque:
1001 // TypeRec ::= 'opaque'
Owen Andersonfba933c2009-07-01 23:57:11 +00001002 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 Lex.Lex();
1004 break;
1005 case lltok::lbrace:
1006 // TypeRec ::= '{' ... '}'
1007 if (ParseStructType(Result, false))
1008 return true;
1009 break;
1010 case lltok::lsquare:
1011 // TypeRec ::= '[' ... ']'
1012 Lex.Lex(); // eat the lsquare.
1013 if (ParseArrayVectorType(Result, false))
1014 return true;
1015 break;
1016 case lltok::less: // Either vector or packed struct.
1017 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001018 Lex.Lex();
1019 if (Lex.getKind() == lltok::lbrace) {
1020 if (ParseStructType(Result, true) ||
1021 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001022 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001023 } else if (ParseArrayVectorType(Result, true))
1024 return true;
1025 break;
1026 case lltok::LocalVar:
1027 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1028 // TypeRec ::= %foo
1029 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1030 Result = T;
1031 } else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001032 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001033 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1034 std::make_pair(Result,
1035 Lex.getLoc())));
1036 M->addTypeName(Lex.getStrVal(), Result.get());
1037 }
1038 Lex.Lex();
1039 break;
1040
1041 case lltok::LocalVarID:
1042 // TypeRec ::= %4
1043 if (Lex.getUIntVal() < NumberedTypes.size())
1044 Result = NumberedTypes[Lex.getUIntVal()];
1045 else {
1046 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1047 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1048 if (I != ForwardRefTypeIDs.end())
1049 Result = I->second.first;
1050 else {
Owen Andersonfba933c2009-07-01 23:57:11 +00001051 Result = Context.getOpaqueType();
Chris Lattnerdf986172009-01-02 07:01:27 +00001052 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1053 std::make_pair(Result,
1054 Lex.getLoc())));
1055 }
1056 }
1057 Lex.Lex();
1058 break;
1059 case lltok::backslash: {
1060 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001061 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001062 unsigned Val;
1063 if (ParseUInt32(Val)) return true;
Owen Andersonfba933c2009-07-01 23:57:11 +00001064 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001065 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1066 Result = OT;
1067 break;
1068 }
1069 }
1070
1071 // Parse the type suffixes.
1072 while (1) {
1073 switch (Lex.getKind()) {
1074 // End of type.
1075 default: return false;
1076
1077 // TypeRec ::= TypeRec '*'
1078 case lltok::star:
1079 if (Result.get() == Type::LabelTy)
1080 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001081 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001082 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001083 if (!PointerType::isValidElementType(Result.get()))
1084 return TokError("pointer to this type is invalid");
Owen Andersonfba933c2009-07-01 23:57:11 +00001085 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001086 Lex.Lex();
1087 break;
1088
1089 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1090 case lltok::kw_addrspace: {
1091 if (Result.get() == Type::LabelTy)
1092 return TokError("basic block pointers are invalid");
Chris Lattnerb4bd16f2009-02-08 19:56:22 +00001093 if (Result.get() == Type::VoidTy)
Dan Gohmanb9070d32009-02-09 17:41:21 +00001094 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001095 if (!PointerType::isValidElementType(Result.get()))
1096 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001097 unsigned AddrSpace;
1098 if (ParseOptionalAddrSpace(AddrSpace) ||
1099 ParseToken(lltok::star, "expected '*' in address space"))
1100 return true;
1101
Owen Andersonfba933c2009-07-01 23:57:11 +00001102 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001103 break;
1104 }
1105
1106 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1107 case lltok::lparen:
1108 if (ParseFunctionType(Result))
1109 return true;
1110 break;
1111 }
1112 }
1113}
1114
1115/// ParseParameterList
1116/// ::= '(' ')'
1117/// ::= '(' Arg (',' Arg)* ')'
1118/// Arg
1119/// ::= Type OptionalAttributes Value OptionalAttributes
1120bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1121 PerFunctionState &PFS) {
1122 if (ParseToken(lltok::lparen, "expected '(' in call"))
1123 return true;
1124
1125 while (Lex.getKind() != lltok::rparen) {
1126 // If this isn't the first argument, we need a comma.
1127 if (!ArgList.empty() &&
1128 ParseToken(lltok::comma, "expected ',' in argument list"))
1129 return true;
1130
1131 // Parse the argument.
1132 LocTy ArgLoc;
1133 PATypeHolder ArgTy(Type::VoidTy);
1134 unsigned ArgAttrs1, ArgAttrs2;
1135 Value *V;
1136 if (ParseType(ArgTy, ArgLoc) ||
1137 ParseOptionalAttrs(ArgAttrs1, 0) ||
1138 ParseValue(ArgTy, V, PFS) ||
1139 // FIXME: Should not allow attributes after the argument, remove this in
1140 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001141 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001142 return true;
1143 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1144 }
1145
1146 Lex.Lex(); // Lex the ')'.
1147 return false;
1148}
1149
1150
1151
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001152/// ParseArgumentList - Parse the argument list for a function type or function
1153/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001154/// ::= '(' ArgTypeListI ')'
1155/// ArgTypeListI
1156/// ::= /*empty*/
1157/// ::= '...'
1158/// ::= ArgTypeList ',' '...'
1159/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001160///
Chris Lattnerdf986172009-01-02 07:01:27 +00001161bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001162 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001163 isVarArg = false;
1164 assert(Lex.getKind() == lltok::lparen);
1165 Lex.Lex(); // eat the (.
1166
1167 if (Lex.getKind() == lltok::rparen) {
1168 // empty
1169 } else if (Lex.getKind() == lltok::dotdotdot) {
1170 isVarArg = true;
1171 Lex.Lex();
1172 } else {
1173 LocTy TypeLoc = Lex.getLoc();
1174 PATypeHolder ArgTy(Type::VoidTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001176 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001177
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001178 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1179 // types (such as a function returning a pointer to itself). If parsing a
1180 // function prototype, we require fully resolved types.
1181 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001182 ParseOptionalAttrs(Attrs, 0)) return true;
1183
Chris Lattnera9a9e072009-03-09 04:49:14 +00001184 if (ArgTy == Type::VoidTy)
1185 return Error(TypeLoc, "argument can not have void type");
1186
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 if (Lex.getKind() == lltok::LocalVar ||
1188 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1189 Name = Lex.getStrVal();
1190 Lex.Lex();
1191 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001192
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001193 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001194 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001195
1196 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1197
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001198 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001199 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001200 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001201 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001202 break;
1203 }
1204
1205 // Otherwise must be an argument type.
1206 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001207 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001208 ParseOptionalAttrs(Attrs, 0)) return true;
1209
Chris Lattnera9a9e072009-03-09 04:49:14 +00001210 if (ArgTy == Type::VoidTy)
1211 return Error(TypeLoc, "argument can not have void type");
1212
Chris Lattnerdf986172009-01-02 07:01:27 +00001213 if (Lex.getKind() == lltok::LocalVar ||
1214 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1215 Name = Lex.getStrVal();
1216 Lex.Lex();
1217 } else {
1218 Name = "";
1219 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001220
1221 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1222 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001223
1224 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1225 }
1226 }
1227
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001228 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001229}
1230
1231/// ParseFunctionType
1232/// ::= Type ArgumentList OptionalAttrs
1233bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1234 assert(Lex.getKind() == lltok::lparen);
1235
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001236 if (!FunctionType::isValidReturnType(Result))
1237 return TokError("invalid function return type");
1238
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 std::vector<ArgInfo> ArgList;
1240 bool isVarArg;
1241 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001242 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 // FIXME: Allow, but ignore attributes on function types!
1244 // FIXME: Remove in LLVM 3.0
1245 ParseOptionalAttrs(Attrs, 2))
1246 return true;
1247
1248 // Reject names on the arguments lists.
1249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1250 if (!ArgList[i].Name.empty())
1251 return Error(ArgList[i].Loc, "argument name invalid in function type");
1252 if (!ArgList[i].Attrs != 0) {
1253 // Allow but ignore attributes on function types; this permits
1254 // auto-upgrade.
1255 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1256 }
1257 }
1258
1259 std::vector<const Type*> ArgListTy;
1260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1261 ArgListTy.push_back(ArgList[i].Type);
1262
Owen Andersonfba933c2009-07-01 23:57:11 +00001263 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1264 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001265 return false;
1266}
1267
1268/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1269/// TypeRec
1270/// ::= '{' '}'
1271/// ::= '{' TypeRec (',' TypeRec)* '}'
1272/// ::= '<' '{' '}' '>'
1273/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1274bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1275 assert(Lex.getKind() == lltok::lbrace);
1276 Lex.Lex(); // Consume the '{'
1277
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001278 if (EatIfPresent(lltok::rbrace)) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001279 Result = Context.getStructType(Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 return false;
1281 }
1282
1283 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001284 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 if (ParseTypeRec(Result)) return true;
1286 ParamsList.push_back(Result);
1287
Chris Lattnera9a9e072009-03-09 04:49:14 +00001288 if (Result == Type::VoidTy)
1289 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001290 if (!StructType::isValidElementType(Result))
1291 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001292
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001293 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001294 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001296
1297 if (Result == Type::VoidTy)
1298 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001299 if (!StructType::isValidElementType(Result))
1300 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001301
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 ParamsList.push_back(Result);
1303 }
1304
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001305 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1306 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001307
1308 std::vector<const Type*> ParamsListTy;
1309 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1310 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersonfba933c2009-07-01 23:57:11 +00001311 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 return false;
1313}
1314
1315/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1316/// token has already been consumed.
1317/// TypeRec
1318/// ::= '[' APSINTVAL 'x' Types ']'
1319/// ::= '<' APSINTVAL 'x' Types '>'
1320bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1321 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1322 Lex.getAPSIntVal().getBitWidth() > 64)
1323 return TokError("expected number in address space");
1324
1325 LocTy SizeLoc = Lex.getLoc();
1326 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001327 Lex.Lex();
1328
1329 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1330 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001331
1332 LocTy TypeLoc = Lex.getLoc();
1333 PATypeHolder EltTy(Type::VoidTy);
1334 if (ParseTypeRec(EltTy)) return true;
1335
Chris Lattnera9a9e072009-03-09 04:49:14 +00001336 if (EltTy == Type::VoidTy)
1337 return Error(TypeLoc, "array and vector element type cannot be void");
1338
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001339 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1340 "expected end of sequential type"))
1341 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001342
1343 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001344 if (Size == 0)
1345 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 if ((unsigned)Size != Size)
1347 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001348 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001349 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersonfba933c2009-07-01 23:57:11 +00001350 Result = Context.getVectorType(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001352 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 return Error(TypeLoc, "invalid array element type");
Owen Andersonfba933c2009-07-01 23:57:11 +00001354 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 }
1356 return false;
1357}
1358
1359//===----------------------------------------------------------------------===//
1360// Function Semantic Analysis.
1361//===----------------------------------------------------------------------===//
1362
1363LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1364 : P(p), F(f) {
1365
1366 // Insert unnamed arguments into the NumberedVals list.
1367 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1368 AI != E; ++AI)
1369 if (!AI->hasName())
1370 NumberedVals.push_back(AI);
1371}
1372
1373LLParser::PerFunctionState::~PerFunctionState() {
1374 // If there were any forward referenced non-basicblock values, delete them.
1375 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1376 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1377 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001378 I->second.first->replaceAllUsesWith(
1379 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001380 delete I->second.first;
1381 I->second.first = 0;
1382 }
1383
1384 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1385 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1386 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001387 I->second.first->replaceAllUsesWith(
1388 P.getContext().getUndef(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001389 delete I->second.first;
1390 I->second.first = 0;
1391 }
1392}
1393
1394bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1395 if (!ForwardRefVals.empty())
1396 return P.Error(ForwardRefVals.begin()->second.second,
1397 "use of undefined value '%" + ForwardRefVals.begin()->first +
1398 "'");
1399 if (!ForwardRefValIDs.empty())
1400 return P.Error(ForwardRefValIDs.begin()->second.second,
1401 "use of undefined value '%" +
1402 utostr(ForwardRefValIDs.begin()->first) + "'");
1403 return false;
1404}
1405
1406
1407/// GetVal - Get a value with the specified name or ID, creating a
1408/// forward reference record if needed. This can return null if the value
1409/// exists but does not have the right type.
1410Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1411 const Type *Ty, LocTy Loc) {
1412 // Look this name up in the normal function symbol table.
1413 Value *Val = F.getValueSymbolTable().lookup(Name);
1414
1415 // If this is a forward reference for the value, see if we already created a
1416 // forward ref record.
1417 if (Val == 0) {
1418 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1419 I = ForwardRefVals.find(Name);
1420 if (I != ForwardRefVals.end())
1421 Val = I->second.first;
1422 }
1423
1424 // If we have the value in the symbol table or fwd-ref table, return it.
1425 if (Val) {
1426 if (Val->getType() == Ty) return Val;
1427 if (Ty == Type::LabelTy)
1428 P.Error(Loc, "'%" + Name + "' is not a basic block");
1429 else
1430 P.Error(Loc, "'%" + Name + "' defined with type '" +
1431 Val->getType()->getDescription() + "'");
1432 return 0;
1433 }
1434
1435 // Don't make placeholders with invalid type.
1436 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1437 P.Error(Loc, "invalid use of a non-first-class type");
1438 return 0;
1439 }
1440
1441 // Otherwise, create a new forward reference for this value and remember it.
1442 Value *FwdVal;
1443 if (Ty == Type::LabelTy)
1444 FwdVal = BasicBlock::Create(Name, &F);
1445 else
1446 FwdVal = new Argument(Ty, Name);
1447
1448 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1449 return FwdVal;
1450}
1451
1452Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1453 LocTy Loc) {
1454 // Look this name up in the normal function symbol table.
1455 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1456
1457 // If this is a forward reference for the value, see if we already created a
1458 // forward ref record.
1459 if (Val == 0) {
1460 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1461 I = ForwardRefValIDs.find(ID);
1462 if (I != ForwardRefValIDs.end())
1463 Val = I->second.first;
1464 }
1465
1466 // If we have the value in the symbol table or fwd-ref table, return it.
1467 if (Val) {
1468 if (Val->getType() == Ty) return Val;
1469 if (Ty == Type::LabelTy)
1470 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1471 else
1472 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1473 Val->getType()->getDescription() + "'");
1474 return 0;
1475 }
1476
1477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1478 P.Error(Loc, "invalid use of a non-first-class type");
1479 return 0;
1480 }
1481
1482 // Otherwise, create a new forward reference for this value and remember it.
1483 Value *FwdVal;
1484 if (Ty == Type::LabelTy)
1485 FwdVal = BasicBlock::Create("", &F);
1486 else
1487 FwdVal = new Argument(Ty);
1488
1489 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1490 return FwdVal;
1491}
1492
1493/// SetInstName - After an instruction is parsed and inserted into its
1494/// basic block, this installs its name.
1495bool LLParser::PerFunctionState::SetInstName(int NameID,
1496 const std::string &NameStr,
1497 LocTy NameLoc, Instruction *Inst) {
1498 // If this instruction has void type, it cannot have a name or ID specified.
1499 if (Inst->getType() == Type::VoidTy) {
1500 if (NameID != -1 || !NameStr.empty())
1501 return P.Error(NameLoc, "instructions returning void cannot have a name");
1502 return false;
1503 }
1504
1505 // If this was a numbered instruction, verify that the instruction is the
1506 // expected value and resolve any forward references.
1507 if (NameStr.empty()) {
1508 // If neither a name nor an ID was specified, just use the next ID.
1509 if (NameID == -1)
1510 NameID = NumberedVals.size();
1511
1512 if (unsigned(NameID) != NumberedVals.size())
1513 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1514 utostr(NumberedVals.size()) + "'");
1515
1516 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1517 ForwardRefValIDs.find(NameID);
1518 if (FI != ForwardRefValIDs.end()) {
1519 if (FI->second.first->getType() != Inst->getType())
1520 return P.Error(NameLoc, "instruction forward referenced with type '" +
1521 FI->second.first->getType()->getDescription() + "'");
1522 FI->second.first->replaceAllUsesWith(Inst);
1523 ForwardRefValIDs.erase(FI);
1524 }
1525
1526 NumberedVals.push_back(Inst);
1527 return false;
1528 }
1529
1530 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1531 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1532 FI = ForwardRefVals.find(NameStr);
1533 if (FI != ForwardRefVals.end()) {
1534 if (FI->second.first->getType() != Inst->getType())
1535 return P.Error(NameLoc, "instruction forward referenced with type '" +
1536 FI->second.first->getType()->getDescription() + "'");
1537 FI->second.first->replaceAllUsesWith(Inst);
1538 ForwardRefVals.erase(FI);
1539 }
1540
1541 // Set the name on the instruction.
1542 Inst->setName(NameStr);
1543
1544 if (Inst->getNameStr() != NameStr)
1545 return P.Error(NameLoc, "multiple definition of local value named '" +
1546 NameStr + "'");
1547 return false;
1548}
1549
1550/// GetBB - Get a basic block with the specified name or ID, creating a
1551/// forward reference record if needed.
1552BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1553 LocTy Loc) {
1554 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1555}
1556
1557BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1558 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1559}
1560
1561/// DefineBB - Define the specified basic block, which is either named or
1562/// unnamed. If there is an error, this returns null otherwise it returns
1563/// the block being defined.
1564BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1565 LocTy Loc) {
1566 BasicBlock *BB;
1567 if (Name.empty())
1568 BB = GetBB(NumberedVals.size(), Loc);
1569 else
1570 BB = GetBB(Name, Loc);
1571 if (BB == 0) return 0; // Already diagnosed error.
1572
1573 // Move the block to the end of the function. Forward ref'd blocks are
1574 // inserted wherever they happen to be referenced.
1575 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1576
1577 // Remove the block from forward ref sets.
1578 if (Name.empty()) {
1579 ForwardRefValIDs.erase(NumberedVals.size());
1580 NumberedVals.push_back(BB);
1581 } else {
1582 // BB forward references are already in the function symbol table.
1583 ForwardRefVals.erase(Name);
1584 }
1585
1586 return BB;
1587}
1588
1589//===----------------------------------------------------------------------===//
1590// Constants.
1591//===----------------------------------------------------------------------===//
1592
1593/// ParseValID - Parse an abstract value that doesn't necessarily have a
1594/// type implied. For example, if we parse "4" we don't know what integer type
1595/// it has. The value will later be combined with its type and checked for
1596/// sanity.
1597bool LLParser::ParseValID(ValID &ID) {
1598 ID.Loc = Lex.getLoc();
1599 switch (Lex.getKind()) {
1600 default: return TokError("expected value token");
1601 case lltok::GlobalID: // @42
1602 ID.UIntVal = Lex.getUIntVal();
1603 ID.Kind = ValID::t_GlobalID;
1604 break;
1605 case lltok::GlobalVar: // @foo
1606 ID.StrVal = Lex.getStrVal();
1607 ID.Kind = ValID::t_GlobalName;
1608 break;
1609 case lltok::LocalVarID: // %42
1610 ID.UIntVal = Lex.getUIntVal();
1611 ID.Kind = ValID::t_LocalID;
1612 break;
1613 case lltok::LocalVar: // %foo
1614 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1615 ID.StrVal = Lex.getStrVal();
1616 ID.Kind = ValID::t_LocalName;
1617 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001618 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1619 ID.Kind = ValID::t_Constant;
1620 Lex.Lex();
1621 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001622 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001623 if (ParseMDNodeVector(Elts) ||
1624 ParseToken(lltok::rbrace, "expected end of metadata node"))
1625 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001626
Owen Andersone951bdf2009-07-02 17:20:28 +00001627 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001628 return false;
1629 }
1630
Devang Patel923078c2009-07-01 19:21:12 +00001631 // Standalone metadata reference
1632 // !{ ..., !42, ... }
1633 unsigned MID = 0;
1634 if (!ParseUInt32(MID)) {
1635 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1636 if (I == MetadataCache.end())
1637 return TokError("Unknown metadata reference");
1638 ID.ConstantVal = I->second;
1639 return false;
1640 }
1641
Nick Lewycky21cc4462009-04-04 07:22:01 +00001642 // MDString:
1643 // ::= '!' STRINGCONSTANT
1644 std::string Str;
1645 if (ParseStringConstant(Str)) return true;
1646
Owen Anderson12c99d82009-07-02 17:28:30 +00001647 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001648 return false;
1649 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001650 case lltok::APSInt:
1651 ID.APSIntVal = Lex.getAPSIntVal();
1652 ID.Kind = ValID::t_APSInt;
1653 break;
1654 case lltok::APFloat:
1655 ID.APFloatVal = Lex.getAPFloatVal();
1656 ID.Kind = ValID::t_APFloat;
1657 break;
1658 case lltok::kw_true:
Owen Andersonfba933c2009-07-01 23:57:11 +00001659 ID.ConstantVal = Context.getConstantIntTrue();
Chris Lattnerdf986172009-01-02 07:01:27 +00001660 ID.Kind = ValID::t_Constant;
1661 break;
1662 case lltok::kw_false:
Owen Andersonfba933c2009-07-01 23:57:11 +00001663 ID.ConstantVal = Context.getConstantIntFalse();
Chris Lattnerdf986172009-01-02 07:01:27 +00001664 ID.Kind = ValID::t_Constant;
1665 break;
1666 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1667 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1668 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1669
1670 case lltok::lbrace: {
1671 // ValID ::= '{' ConstVector '}'
1672 Lex.Lex();
1673 SmallVector<Constant*, 16> Elts;
1674 if (ParseGlobalValueVector(Elts) ||
1675 ParseToken(lltok::rbrace, "expected end of struct constant"))
1676 return true;
1677
Owen Andersonfba933c2009-07-01 23:57:11 +00001678 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 ID.Kind = ValID::t_Constant;
1680 return false;
1681 }
1682 case lltok::less: {
1683 // ValID ::= '<' ConstVector '>' --> Vector.
1684 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1685 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001686 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001687
1688 SmallVector<Constant*, 16> Elts;
1689 LocTy FirstEltLoc = Lex.getLoc();
1690 if (ParseGlobalValueVector(Elts) ||
1691 (isPackedStruct &&
1692 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1693 ParseToken(lltok::greater, "expected end of constant"))
1694 return true;
1695
1696 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001697 ID.ConstantVal =
1698 Context.getConstantStruct(Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 ID.Kind = ValID::t_Constant;
1700 return false;
1701 }
1702
1703 if (Elts.empty())
1704 return Error(ID.Loc, "constant vector must not be empty");
1705
1706 if (!Elts[0]->getType()->isInteger() &&
1707 !Elts[0]->getType()->isFloatingPoint())
1708 return Error(FirstEltLoc,
1709 "vector elements must have integer or floating point type");
1710
1711 // Verify that all the vector elements have the same type.
1712 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1713 if (Elts[i]->getType() != Elts[0]->getType())
1714 return Error(FirstEltLoc,
1715 "vector element #" + utostr(i) +
1716 " is not of type '" + Elts[0]->getType()->getDescription());
1717
Owen Andersonfba933c2009-07-01 23:57:11 +00001718 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001719 ID.Kind = ValID::t_Constant;
1720 return false;
1721 }
1722 case lltok::lsquare: { // Array Constant
1723 Lex.Lex();
1724 SmallVector<Constant*, 16> Elts;
1725 LocTy FirstEltLoc = Lex.getLoc();
1726 if (ParseGlobalValueVector(Elts) ||
1727 ParseToken(lltok::rsquare, "expected end of array constant"))
1728 return true;
1729
1730 // Handle empty element.
1731 if (Elts.empty()) {
1732 // Use undef instead of an array because it's inconvenient to determine
1733 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001734 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001735 return false;
1736 }
1737
1738 if (!Elts[0]->getType()->isFirstClassType())
1739 return Error(FirstEltLoc, "invalid array element type: " +
1740 Elts[0]->getType()->getDescription());
1741
Owen Andersonfba933c2009-07-01 23:57:11 +00001742 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001743
1744 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001745 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 if (Elts[i]->getType() != Elts[0]->getType())
1747 return Error(FirstEltLoc,
1748 "array element #" + utostr(i) +
1749 " is not of type '" +Elts[0]->getType()->getDescription());
1750 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001751
Owen Andersonfba933c2009-07-01 23:57:11 +00001752 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 ID.Kind = ValID::t_Constant;
1754 return false;
1755 }
1756 case lltok::kw_c: // c "foo"
1757 Lex.Lex();
Owen Andersonfba933c2009-07-01 23:57:11 +00001758 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1760 ID.Kind = ValID::t_Constant;
1761 return false;
1762
1763 case lltok::kw_asm: {
1764 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1765 bool HasSideEffect;
1766 Lex.Lex();
1767 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001768 ParseStringConstant(ID.StrVal) ||
1769 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001770 ParseToken(lltok::StringConstant, "expected constraint string"))
1771 return true;
1772 ID.StrVal2 = Lex.getStrVal();
1773 ID.UIntVal = HasSideEffect;
1774 ID.Kind = ValID::t_InlineAsm;
1775 return false;
1776 }
1777
1778 case lltok::kw_trunc:
1779 case lltok::kw_zext:
1780 case lltok::kw_sext:
1781 case lltok::kw_fptrunc:
1782 case lltok::kw_fpext:
1783 case lltok::kw_bitcast:
1784 case lltok::kw_uitofp:
1785 case lltok::kw_sitofp:
1786 case lltok::kw_fptoui:
1787 case lltok::kw_fptosi:
1788 case lltok::kw_inttoptr:
1789 case lltok::kw_ptrtoint: {
1790 unsigned Opc = Lex.getUIntVal();
1791 PATypeHolder DestTy(Type::VoidTy);
1792 Constant *SrcVal;
1793 Lex.Lex();
1794 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1795 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001796 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 ParseType(DestTy) ||
1798 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1799 return true;
1800 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1801 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1802 SrcVal->getType()->getDescription() + "' to '" +
1803 DestTy->getDescription() + "'");
Owen Andersonfba933c2009-07-01 23:57:11 +00001804 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1805 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 ID.Kind = ValID::t_Constant;
1807 return false;
1808 }
1809 case lltok::kw_extractvalue: {
1810 Lex.Lex();
1811 Constant *Val;
1812 SmallVector<unsigned, 4> Indices;
1813 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1814 ParseGlobalTypeAndValue(Val) ||
1815 ParseIndexList(Indices) ||
1816 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1817 return true;
1818 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1819 return Error(ID.Loc, "extractvalue operand must be array or struct");
1820 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1821 Indices.end()))
1822 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001823 ID.ConstantVal =
Owen Andersonfba933c2009-07-01 23:57:11 +00001824 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001825 ID.Kind = ValID::t_Constant;
1826 return false;
1827 }
1828 case lltok::kw_insertvalue: {
1829 Lex.Lex();
1830 Constant *Val0, *Val1;
1831 SmallVector<unsigned, 4> Indices;
1832 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1833 ParseGlobalTypeAndValue(Val0) ||
1834 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1835 ParseGlobalTypeAndValue(Val1) ||
1836 ParseIndexList(Indices) ||
1837 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1838 return true;
1839 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1840 return Error(ID.Loc, "extractvalue operand must be array or struct");
1841 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1842 Indices.end()))
1843 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonfba933c2009-07-01 23:57:11 +00001844 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1845 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001846 ID.Kind = ValID::t_Constant;
1847 return false;
1848 }
1849 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001850 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001851 unsigned PredVal, Opc = Lex.getUIntVal();
1852 Constant *Val0, *Val1;
1853 Lex.Lex();
1854 if (ParseCmpPredicate(PredVal, Opc) ||
1855 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1856 ParseGlobalTypeAndValue(Val0) ||
1857 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1858 ParseGlobalTypeAndValue(Val1) ||
1859 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1860 return true;
1861
1862 if (Val0->getType() != Val1->getType())
1863 return Error(ID.Loc, "compare operands must have the same type");
1864
1865 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1866
1867 if (Opc == Instruction::FCmp) {
1868 if (!Val0->getType()->isFPOrFPVector())
1869 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001870 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001871 } else {
1872 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 if (!Val0->getType()->isIntOrIntVector() &&
1874 !isa<PointerType>(Val0->getType()))
1875 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001876 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 }
1878 ID.Kind = ValID::t_Constant;
1879 return false;
1880 }
1881
1882 // Binary Operators.
1883 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001884 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00001885 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001886 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001888 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00001889 case lltok::kw_udiv:
1890 case lltok::kw_sdiv:
1891 case lltok::kw_fdiv:
1892 case lltok::kw_urem:
1893 case lltok::kw_srem:
1894 case lltok::kw_frem: {
1895 unsigned Opc = Lex.getUIntVal();
1896 Constant *Val0, *Val1;
1897 Lex.Lex();
1898 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1899 ParseGlobalTypeAndValue(Val0) ||
1900 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1901 ParseGlobalTypeAndValue(Val1) ||
1902 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1903 return true;
1904 if (Val0->getType() != Val1->getType())
1905 return Error(ID.Loc, "operands of constexpr must have same type");
1906 if (!Val0->getType()->isIntOrIntVector() &&
1907 !Val0->getType()->isFPOrFPVector())
1908 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001909 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001910 ID.Kind = ValID::t_Constant;
1911 return false;
1912 }
1913
1914 // Logical Operations
1915 case lltok::kw_shl:
1916 case lltok::kw_lshr:
1917 case lltok::kw_ashr:
1918 case lltok::kw_and:
1919 case lltok::kw_or:
1920 case lltok::kw_xor: {
1921 unsigned Opc = Lex.getUIntVal();
1922 Constant *Val0, *Val1;
1923 Lex.Lex();
1924 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1925 ParseGlobalTypeAndValue(Val0) ||
1926 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1927 ParseGlobalTypeAndValue(Val1) ||
1928 ParseToken(lltok::rparen, "expected ')' in logical 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 return Error(ID.Loc,
1934 "constexpr requires integer or integer 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 case lltok::kw_getelementptr:
1941 case lltok::kw_shufflevector:
1942 case lltok::kw_insertelement:
1943 case lltok::kw_extractelement:
1944 case lltok::kw_select: {
1945 unsigned Opc = Lex.getUIntVal();
1946 SmallVector<Constant*, 16> Elts;
1947 Lex.Lex();
1948 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1949 ParseGlobalValueVector(Elts) ||
1950 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1951 return true;
1952
1953 if (Opc == Instruction::GetElementPtr) {
1954 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1955 return Error(ID.Loc, "getelementptr requires pointer operand");
1956
1957 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1958 (Value**)&Elts[1], Elts.size()-1))
1959 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonfba933c2009-07-01 23:57:11 +00001960 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
Chris Lattnerdf986172009-01-02 07:01:27 +00001961 &Elts[1], Elts.size()-1);
1962 } else if (Opc == Instruction::Select) {
1963 if (Elts.size() != 3)
1964 return Error(ID.Loc, "expected three operands to select");
1965 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1966 Elts[2]))
1967 return Error(ID.Loc, Reason);
Owen Andersonfba933c2009-07-01 23:57:11 +00001968 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 } else if (Opc == Instruction::ShuffleVector) {
1970 if (Elts.size() != 3)
1971 return Error(ID.Loc, "expected three operands to shufflevector");
1972 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1973 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00001974 ID.ConstantVal =
1975 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 } else if (Opc == Instruction::ExtractElement) {
1977 if (Elts.size() != 2)
1978 return Error(ID.Loc, "expected two operands to extractelement");
1979 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1980 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001981 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001982 } else {
1983 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1984 if (Elts.size() != 3)
1985 return Error(ID.Loc, "expected three operands to insertelement");
1986 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1987 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00001988 ID.ConstantVal =
1989 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00001990 }
1991
1992 ID.Kind = ValID::t_Constant;
1993 return false;
1994 }
1995 }
1996
1997 Lex.Lex();
1998 return false;
1999}
2000
2001/// ParseGlobalValue - Parse a global value with the specified type.
2002bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2003 V = 0;
2004 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002005 return ParseValID(ID) ||
2006 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002007}
2008
2009/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2010/// constant.
2011bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2012 Constant *&V) {
2013 if (isa<FunctionType>(Ty))
2014 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2015
2016 switch (ID.Kind) {
2017 default: assert(0 && "Unknown ValID!");
2018 case ValID::t_LocalID:
2019 case ValID::t_LocalName:
2020 return Error(ID.Loc, "invalid use of function-local name");
2021 case ValID::t_InlineAsm:
2022 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2023 case ValID::t_GlobalName:
2024 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2025 return V == 0;
2026 case ValID::t_GlobalID:
2027 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2028 return V == 0;
2029 case ValID::t_APSInt:
2030 if (!isa<IntegerType>(Ty))
2031 return Error(ID.Loc, "integer constant must have integer type");
2032 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersonfba933c2009-07-01 23:57:11 +00002033 V = Context.getConstantInt(ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002034 return false;
2035 case ValID::t_APFloat:
2036 if (!Ty->isFloatingPoint() ||
2037 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2038 return Error(ID.Loc, "floating point constant invalid for type");
2039
2040 // The lexer has no type info, so builds all float and double FP constants
2041 // as double. Fix this here. Long double does not need this.
2042 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2043 Ty == Type::FloatTy) {
2044 bool Ignored;
2045 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2046 &Ignored);
2047 }
Owen Andersonfba933c2009-07-01 23:57:11 +00002048 V = Context.getConstantFP(ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002049
2050 if (V->getType() != Ty)
2051 return Error(ID.Loc, "floating point constant does not have type '" +
2052 Ty->getDescription() + "'");
2053
Chris Lattnerdf986172009-01-02 07:01:27 +00002054 return false;
2055 case ValID::t_Null:
2056 if (!isa<PointerType>(Ty))
2057 return Error(ID.Loc, "null must be a pointer type");
Owen Andersonfba933c2009-07-01 23:57:11 +00002058 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002059 return false;
2060 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002061 // FIXME: LabelTy should not be a first-class type.
Chris Lattner0b616352009-01-05 18:12:21 +00002062 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2063 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002064 return Error(ID.Loc, "invalid type for undef constant");
Owen Andersonb43eae72009-07-02 17:04:01 +00002065 V = Context.getUndef(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002067 case ValID::t_EmptyArray:
2068 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2069 return Error(ID.Loc, "invalid empty array initializer");
Owen Andersonb43eae72009-07-02 17:04:01 +00002070 V = Context.getUndef(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002071 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002073 // FIXME: LabelTy should not be a first-class type.
2074 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 return Error(ID.Loc, "invalid type for null constant");
Owen Andersonfba933c2009-07-01 23:57:11 +00002076 V = Context.getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 return false;
2078 case ValID::t_Constant:
2079 if (ID.ConstantVal->getType() != Ty)
2080 return Error(ID.Loc, "constant expression type mismatch");
2081 V = ID.ConstantVal;
2082 return false;
2083 }
2084}
2085
2086bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2087 PATypeHolder Type(Type::VoidTy);
2088 return ParseType(Type) ||
2089 ParseGlobalValue(Type, V);
2090}
2091
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002092/// ParseGlobalValueVector
2093/// ::= /*empty*/
2094/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002095bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2096 // Empty list.
2097 if (Lex.getKind() == lltok::rbrace ||
2098 Lex.getKind() == lltok::rsquare ||
2099 Lex.getKind() == lltok::greater ||
2100 Lex.getKind() == lltok::rparen)
2101 return false;
2102
2103 Constant *C;
2104 if (ParseGlobalTypeAndValue(C)) return true;
2105 Elts.push_back(C);
2106
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002107 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 if (ParseGlobalTypeAndValue(C)) return true;
2109 Elts.push_back(C);
2110 }
2111
2112 return false;
2113}
2114
2115
2116//===----------------------------------------------------------------------===//
2117// Function Parsing.
2118//===----------------------------------------------------------------------===//
2119
2120bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2121 PerFunctionState &PFS) {
2122 if (ID.Kind == ValID::t_LocalID)
2123 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2124 else if (ID.Kind == ValID::t_LocalName)
2125 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002126 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002127 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2128 const FunctionType *FTy =
2129 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2130 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2131 return Error(ID.Loc, "invalid type for inline asm constraint string");
2132 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2133 return false;
2134 } else {
2135 Constant *C;
2136 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2137 V = C;
2138 return false;
2139 }
2140
2141 return V == 0;
2142}
2143
2144bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2145 V = 0;
2146 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002147 return ParseValID(ID) ||
2148 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002149}
2150
2151bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2152 PATypeHolder T(Type::VoidTy);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002153 return ParseType(T) ||
2154 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002155}
2156
2157/// FunctionHeader
2158/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2159/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2160/// OptionalAlign OptGC
2161bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2162 // Parse the linkage.
2163 LocTy LinkageLoc = Lex.getLoc();
2164 unsigned Linkage;
2165
2166 unsigned Visibility, CC, RetAttrs;
2167 PATypeHolder RetType(Type::VoidTy);
2168 LocTy RetTypeLoc = Lex.getLoc();
2169 if (ParseOptionalLinkage(Linkage) ||
2170 ParseOptionalVisibility(Visibility) ||
2171 ParseOptionalCallingConv(CC) ||
2172 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002173 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 return true;
2175
2176 // Verify that the linkage is ok.
2177 switch ((GlobalValue::LinkageTypes)Linkage) {
2178 case GlobalValue::ExternalLinkage:
2179 break; // always ok.
2180 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002181 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 if (isDefine)
2183 return Error(LinkageLoc, "invalid linkage for function definition");
2184 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002185 case GlobalValue::PrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002187 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002188 case GlobalValue::LinkOnceAnyLinkage:
2189 case GlobalValue::LinkOnceODRLinkage:
2190 case GlobalValue::WeakAnyLinkage:
2191 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 case GlobalValue::DLLExportLinkage:
2193 if (!isDefine)
2194 return Error(LinkageLoc, "invalid linkage for function declaration");
2195 break;
2196 case GlobalValue::AppendingLinkage:
2197 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002198 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002199 return Error(LinkageLoc, "invalid function linkage type");
2200 }
2201
Chris Lattner99bb3152009-01-05 08:00:30 +00002202 if (!FunctionType::isValidReturnType(RetType) ||
2203 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002204 return Error(RetTypeLoc, "invalid function return type");
2205
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002207
2208 std::string FunctionName;
2209 if (Lex.getKind() == lltok::GlobalVar) {
2210 FunctionName = Lex.getStrVal();
2211 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2212 unsigned NameID = Lex.getUIntVal();
2213
2214 if (NameID != NumberedVals.size())
2215 return TokError("function expected to be numbered '%" +
2216 utostr(NumberedVals.size()) + "'");
2217 } else {
2218 return TokError("expected function name");
2219 }
2220
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002221 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002222
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002223 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 return TokError("expected '(' in function argument list");
2225
2226 std::vector<ArgInfo> ArgList;
2227 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002231 std::string GC;
2232
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002233 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002234 ParseOptionalAttrs(FuncAttrs, 2) ||
2235 (EatIfPresent(lltok::kw_section) &&
2236 ParseStringConstant(Section)) ||
2237 ParseOptionalAlignment(Alignment) ||
2238 (EatIfPresent(lltok::kw_gc) &&
2239 ParseStringConstant(GC)))
2240 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002241
2242 // If the alignment was parsed as an attribute, move to the alignment field.
2243 if (FuncAttrs & Attribute::Alignment) {
2244 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2245 FuncAttrs &= ~Attribute::Alignment;
2246 }
2247
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 // Okay, if we got here, the function is syntactically valid. Convert types
2249 // and do semantic checks.
2250 std::vector<const Type*> ParamTypeList;
2251 SmallVector<AttributeWithIndex, 8> Attrs;
2252 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2253 // attributes.
2254 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2255 if (FuncAttrs & ObsoleteFuncAttrs) {
2256 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2257 FuncAttrs &= ~ObsoleteFuncAttrs;
2258 }
2259
2260 if (RetAttrs != Attribute::None)
2261 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2262
2263 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2264 ParamTypeList.push_back(ArgList[i].Type);
2265 if (ArgList[i].Attrs != Attribute::None)
2266 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2267 }
2268
2269 if (FuncAttrs != Attribute::None)
2270 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2271
2272 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2273
Chris Lattnera9a9e072009-03-09 04:49:14 +00002274 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2275 RetType != Type::VoidTy)
2276 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2277
Owen Andersonfba933c2009-07-01 23:57:11 +00002278 const FunctionType *FT =
2279 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2280 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002281
2282 Fn = 0;
2283 if (!FunctionName.empty()) {
2284 // If this was a definition of a forward reference, remove the definition
2285 // from the forward reference table and fill in the forward ref.
2286 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2287 ForwardRefVals.find(FunctionName);
2288 if (FRVI != ForwardRefVals.end()) {
2289 Fn = M->getFunction(FunctionName);
2290 ForwardRefVals.erase(FRVI);
2291 } else if ((Fn = M->getFunction(FunctionName))) {
2292 // If this function already exists in the symbol table, then it is
2293 // multiply defined. We accept a few cases for old backwards compat.
2294 // FIXME: Remove this stuff for LLVM 3.0.
2295 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2296 (!Fn->isDeclaration() && isDefine)) {
2297 // If the redefinition has different type or different attributes,
2298 // reject it. If both have bodies, reject it.
2299 return Error(NameLoc, "invalid redefinition of function '" +
2300 FunctionName + "'");
2301 } else if (Fn->isDeclaration()) {
2302 // Make sure to strip off any argument names so we can't get conflicts.
2303 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2304 AI != AE; ++AI)
2305 AI->setName("");
2306 }
2307 }
2308
2309 } else if (FunctionName.empty()) {
2310 // If this is a definition of a forward referenced function, make sure the
2311 // types agree.
2312 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2313 = ForwardRefValIDs.find(NumberedVals.size());
2314 if (I != ForwardRefValIDs.end()) {
2315 Fn = cast<Function>(I->second.first);
2316 if (Fn->getType() != PFT)
2317 return Error(NameLoc, "type of definition and forward reference of '@" +
2318 utostr(NumberedVals.size()) +"' disagree");
2319 ForwardRefValIDs.erase(I);
2320 }
2321 }
2322
2323 if (Fn == 0)
2324 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2325 else // Move the forward-reference to the correct spot in the module.
2326 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2327
2328 if (FunctionName.empty())
2329 NumberedVals.push_back(Fn);
2330
2331 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2332 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2333 Fn->setCallingConv(CC);
2334 Fn->setAttributes(PAL);
2335 Fn->setAlignment(Alignment);
2336 Fn->setSection(Section);
2337 if (!GC.empty()) Fn->setGC(GC.c_str());
2338
2339 // Add all of the arguments we parsed to the function.
2340 Function::arg_iterator ArgIt = Fn->arg_begin();
2341 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2342 // If the argument has a name, insert it into the argument symbol table.
2343 if (ArgList[i].Name.empty()) continue;
2344
2345 // Set the name, if it conflicted, it will be auto-renamed.
2346 ArgIt->setName(ArgList[i].Name);
2347
2348 if (ArgIt->getNameStr() != ArgList[i].Name)
2349 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2350 ArgList[i].Name + "'");
2351 }
2352
2353 return false;
2354}
2355
2356
2357/// ParseFunctionBody
2358/// ::= '{' BasicBlock+ '}'
2359/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2360///
2361bool LLParser::ParseFunctionBody(Function &Fn) {
2362 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2363 return TokError("expected '{' in function body");
2364 Lex.Lex(); // eat the {.
2365
2366 PerFunctionState PFS(*this, Fn);
2367
2368 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2369 if (ParseBasicBlock(PFS)) return true;
2370
2371 // Eat the }.
2372 Lex.Lex();
2373
2374 // Verify function is ok.
2375 return PFS.VerifyFunctionComplete();
2376}
2377
2378/// ParseBasicBlock
2379/// ::= LabelStr? Instruction*
2380bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2381 // If this basic block starts out with a name, remember it.
2382 std::string Name;
2383 LocTy NameLoc = Lex.getLoc();
2384 if (Lex.getKind() == lltok::LabelStr) {
2385 Name = Lex.getStrVal();
2386 Lex.Lex();
2387 }
2388
2389 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2390 if (BB == 0) return true;
2391
2392 std::string NameStr;
2393
2394 // Parse the instructions in this block until we get a terminator.
2395 Instruction *Inst;
2396 do {
2397 // This instruction may have three possibilities for a name: a) none
2398 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2399 LocTy NameLoc = Lex.getLoc();
2400 int NameID = -1;
2401 NameStr = "";
2402
2403 if (Lex.getKind() == lltok::LocalVarID) {
2404 NameID = Lex.getUIntVal();
2405 Lex.Lex();
2406 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2407 return true;
2408 } else if (Lex.getKind() == lltok::LocalVar ||
2409 // FIXME: REMOVE IN LLVM 3.0
2410 Lex.getKind() == lltok::StringConstant) {
2411 NameStr = Lex.getStrVal();
2412 Lex.Lex();
2413 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2414 return true;
2415 }
2416
2417 if (ParseInstruction(Inst, BB, PFS)) return true;
2418
2419 BB->getInstList().push_back(Inst);
2420
2421 // Set the name on the instruction.
2422 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2423 } while (!isa<TerminatorInst>(Inst));
2424
2425 return false;
2426}
2427
2428//===----------------------------------------------------------------------===//
2429// Instruction Parsing.
2430//===----------------------------------------------------------------------===//
2431
2432/// ParseInstruction - Parse one of the many different instructions.
2433///
2434bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2435 PerFunctionState &PFS) {
2436 lltok::Kind Token = Lex.getKind();
2437 if (Token == lltok::Eof)
2438 return TokError("found end of file when expecting more instructions");
2439 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002440 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 Lex.Lex(); // Eat the keyword.
2442
2443 switch (Token) {
2444 default: return Error(Loc, "expected instruction opcode");
2445 // Terminator Instructions.
2446 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2447 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2448 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2449 case lltok::kw_br: return ParseBr(Inst, PFS);
2450 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2451 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2452 // Binary Operators.
2453 case lltok::kw_add:
2454 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002455 case lltok::kw_mul:
2456 // API compatibility: Accept either integer or floating-point types.
2457 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2458 case lltok::kw_fadd:
2459 case lltok::kw_fsub:
2460 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2461
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 case lltok::kw_udiv:
2463 case lltok::kw_sdiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002464 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002465 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002466 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002467 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 case lltok::kw_shl:
2469 case lltok::kw_lshr:
2470 case lltok::kw_ashr:
2471 case lltok::kw_and:
2472 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002473 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002474 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002475 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002476 // Casts.
2477 case lltok::kw_trunc:
2478 case lltok::kw_zext:
2479 case lltok::kw_sext:
2480 case lltok::kw_fptrunc:
2481 case lltok::kw_fpext:
2482 case lltok::kw_bitcast:
2483 case lltok::kw_uitofp:
2484 case lltok::kw_sitofp:
2485 case lltok::kw_fptoui:
2486 case lltok::kw_fptosi:
2487 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002488 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 // Other.
2490 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002491 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002492 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2493 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2494 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2495 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2496 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2497 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2498 // Memory.
2499 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002500 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002501 case lltok::kw_free: return ParseFree(Inst, PFS);
2502 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2503 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2504 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002505 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002507 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002509 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002511 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2512 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2513 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2514 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2515 }
2516}
2517
2518/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2519bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002520 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 switch (Lex.getKind()) {
2522 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2523 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2524 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2525 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2526 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2527 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2528 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2529 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2530 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2531 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2532 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2533 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2534 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2535 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2536 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2537 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2538 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2539 }
2540 } else {
2541 switch (Lex.getKind()) {
2542 default: TokError("expected icmp predicate (e.g. 'eq')");
2543 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2544 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2545 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2546 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2547 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2548 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2549 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2550 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2551 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2552 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2553 }
2554 }
2555 Lex.Lex();
2556 return false;
2557}
2558
2559//===----------------------------------------------------------------------===//
2560// Terminator Instructions.
2561//===----------------------------------------------------------------------===//
2562
2563/// ParseRet - Parse a return instruction.
2564/// ::= 'ret' void
2565/// ::= 'ret' TypeAndValue
2566/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2567bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2568 PerFunctionState &PFS) {
2569 PATypeHolder Ty(Type::VoidTy);
Chris Lattnera9a9e072009-03-09 04:49:14 +00002570 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002571
2572 if (Ty == Type::VoidTy) {
2573 Inst = ReturnInst::Create();
2574 return false;
2575 }
2576
2577 Value *RV;
2578 if (ParseValue(Ty, RV, PFS)) return true;
2579
2580 // The normal case is one return value.
2581 if (Lex.getKind() == lltok::comma) {
2582 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2583 // of 'ret {i32,i32} {i32 1, i32 2}'
2584 SmallVector<Value*, 8> RVs;
2585 RVs.push_back(RV);
2586
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002587 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 if (ParseTypeAndValue(RV, PFS)) return true;
2589 RVs.push_back(RV);
2590 }
2591
Owen Andersonb43eae72009-07-02 17:04:01 +00002592 RV = Context.getUndef(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2594 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2595 BB->getInstList().push_back(I);
2596 RV = I;
2597 }
2598 }
2599 Inst = ReturnInst::Create(RV);
2600 return false;
2601}
2602
2603
2604/// ParseBr
2605/// ::= 'br' TypeAndValue
2606/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2607bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2608 LocTy Loc, Loc2;
2609 Value *Op0, *Op1, *Op2;
2610 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2611
2612 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2613 Inst = BranchInst::Create(BB);
2614 return false;
2615 }
2616
2617 if (Op0->getType() != Type::Int1Ty)
2618 return Error(Loc, "branch condition must have 'i1' type");
2619
2620 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2621 ParseTypeAndValue(Op1, Loc, PFS) ||
2622 ParseToken(lltok::comma, "expected ',' after true destination") ||
2623 ParseTypeAndValue(Op2, Loc2, PFS))
2624 return true;
2625
2626 if (!isa<BasicBlock>(Op1))
2627 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002628 if (!isa<BasicBlock>(Op2))
2629 return Error(Loc2, "true destination of branch must be a basic block");
2630
2631 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2632 return false;
2633}
2634
2635/// ParseSwitch
2636/// Instruction
2637/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2638/// JumpTable
2639/// ::= (TypeAndValue ',' TypeAndValue)*
2640bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2641 LocTy CondLoc, BBLoc;
2642 Value *Cond, *DefaultBB;
2643 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2644 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2645 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2646 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2647 return true;
2648
2649 if (!isa<IntegerType>(Cond->getType()))
2650 return Error(CondLoc, "switch condition must have integer type");
2651 if (!isa<BasicBlock>(DefaultBB))
2652 return Error(BBLoc, "default destination must be a basic block");
2653
2654 // Parse the jump table pairs.
2655 SmallPtrSet<Value*, 32> SeenCases;
2656 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2657 while (Lex.getKind() != lltok::rsquare) {
2658 Value *Constant, *DestBB;
2659
2660 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2661 ParseToken(lltok::comma, "expected ',' after case value") ||
2662 ParseTypeAndValue(DestBB, BBLoc, PFS))
2663 return true;
2664
2665 if (!SeenCases.insert(Constant))
2666 return Error(CondLoc, "duplicate case value in switch");
2667 if (!isa<ConstantInt>(Constant))
2668 return Error(CondLoc, "case value is not a constant integer");
2669 if (!isa<BasicBlock>(DestBB))
2670 return Error(BBLoc, "case destination is not a basic block");
2671
2672 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2673 cast<BasicBlock>(DestBB)));
2674 }
2675
2676 Lex.Lex(); // Eat the ']'.
2677
2678 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2679 Table.size());
2680 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2681 SI->addCase(Table[i].first, Table[i].second);
2682 Inst = SI;
2683 return false;
2684}
2685
2686/// ParseInvoke
2687/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2688/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2689bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2690 LocTy CallLoc = Lex.getLoc();
2691 unsigned CC, RetAttrs, FnAttrs;
2692 PATypeHolder RetType(Type::VoidTy);
2693 LocTy RetTypeLoc;
2694 ValID CalleeID;
2695 SmallVector<ParamInfo, 16> ArgList;
2696
2697 Value *NormalBB, *UnwindBB;
2698 if (ParseOptionalCallingConv(CC) ||
2699 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002700 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 ParseValID(CalleeID) ||
2702 ParseParameterList(ArgList, PFS) ||
2703 ParseOptionalAttrs(FnAttrs, 2) ||
2704 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2705 ParseTypeAndValue(NormalBB, PFS) ||
2706 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2707 ParseTypeAndValue(UnwindBB, PFS))
2708 return true;
2709
2710 if (!isa<BasicBlock>(NormalBB))
2711 return Error(CallLoc, "normal destination is not a basic block");
2712 if (!isa<BasicBlock>(UnwindBB))
2713 return Error(CallLoc, "unwind destination is not a basic block");
2714
2715 // If RetType is a non-function pointer type, then this is the short syntax
2716 // for the call, which means that RetType is just the return type. Infer the
2717 // rest of the function argument types from the arguments that are present.
2718 const PointerType *PFTy = 0;
2719 const FunctionType *Ty = 0;
2720 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2721 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2722 // Pull out the types of all of the arguments...
2723 std::vector<const Type*> ParamTypes;
2724 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2725 ParamTypes.push_back(ArgList[i].V->getType());
2726
2727 if (!FunctionType::isValidReturnType(RetType))
2728 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2729
Owen Andersonfba933c2009-07-01 23:57:11 +00002730 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2731 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 }
2733
2734 // Look up the callee.
2735 Value *Callee;
2736 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2737
2738 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2739 // function attributes.
2740 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2741 if (FnAttrs & ObsoleteFuncAttrs) {
2742 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2743 FnAttrs &= ~ObsoleteFuncAttrs;
2744 }
2745
2746 // Set up the Attributes for the function.
2747 SmallVector<AttributeWithIndex, 8> Attrs;
2748 if (RetAttrs != Attribute::None)
2749 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2750
2751 SmallVector<Value*, 8> Args;
2752
2753 // Loop through FunctionType's arguments and ensure they are specified
2754 // correctly. Also, gather any parameter attributes.
2755 FunctionType::param_iterator I = Ty->param_begin();
2756 FunctionType::param_iterator E = Ty->param_end();
2757 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2758 const Type *ExpectedTy = 0;
2759 if (I != E) {
2760 ExpectedTy = *I++;
2761 } else if (!Ty->isVarArg()) {
2762 return Error(ArgList[i].Loc, "too many arguments specified");
2763 }
2764
2765 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2766 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2767 ExpectedTy->getDescription() + "'");
2768 Args.push_back(ArgList[i].V);
2769 if (ArgList[i].Attrs != Attribute::None)
2770 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2771 }
2772
2773 if (I != E)
2774 return Error(CallLoc, "not enough parameters specified for call");
2775
2776 if (FnAttrs != Attribute::None)
2777 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2778
2779 // Finish off the Attributes and check them
2780 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2781
2782 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2783 cast<BasicBlock>(UnwindBB),
2784 Args.begin(), Args.end());
2785 II->setCallingConv(CC);
2786 II->setAttributes(PAL);
2787 Inst = II;
2788 return false;
2789}
2790
2791
2792
2793//===----------------------------------------------------------------------===//
2794// Binary Operators.
2795//===----------------------------------------------------------------------===//
2796
2797/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00002798/// ::= ArithmeticOps TypeAndValue ',' Value
2799///
2800/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2801/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00002802bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00002803 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002804 LocTy Loc; Value *LHS, *RHS;
2805 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2806 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2807 ParseValue(LHS->getType(), RHS, PFS))
2808 return true;
2809
Chris Lattnere914b592009-01-05 08:24:46 +00002810 bool Valid;
2811 switch (OperandType) {
2812 default: assert(0 && "Unknown operand type!");
2813 case 0: // int or FP.
2814 Valid = LHS->getType()->isIntOrIntVector() ||
2815 LHS->getType()->isFPOrFPVector();
2816 break;
2817 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2818 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2819 }
2820
2821 if (!Valid)
2822 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00002823
2824 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2825 return false;
2826}
2827
2828/// ParseLogical
2829/// ::= ArithmeticOps TypeAndValue ',' Value {
2830bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2831 unsigned Opc) {
2832 LocTy Loc; Value *LHS, *RHS;
2833 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2834 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2835 ParseValue(LHS->getType(), RHS, PFS))
2836 return true;
2837
2838 if (!LHS->getType()->isIntOrIntVector())
2839 return Error(Loc,"instruction requires integer or integer vector operands");
2840
2841 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2842 return false;
2843}
2844
2845
2846/// ParseCompare
2847/// ::= 'icmp' IPredicates TypeAndValue ',' Value
2848/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00002849bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2850 unsigned Opc) {
2851 // Parse the integer/fp comparison predicate.
2852 LocTy Loc;
2853 unsigned Pred;
2854 Value *LHS, *RHS;
2855 if (ParseCmpPredicate(Pred, Opc) ||
2856 ParseTypeAndValue(LHS, Loc, PFS) ||
2857 ParseToken(lltok::comma, "expected ',' after compare value") ||
2858 ParseValue(LHS->getType(), RHS, PFS))
2859 return true;
2860
2861 if (Opc == Instruction::FCmp) {
2862 if (!LHS->getType()->isFPOrFPVector())
2863 return Error(Loc, "fcmp requires floating point operands");
2864 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002865 } else {
2866 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002867 if (!LHS->getType()->isIntOrIntVector() &&
2868 !isa<PointerType>(LHS->getType()))
2869 return Error(Loc, "icmp requires integer operands");
2870 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 }
2872 return false;
2873}
2874
2875//===----------------------------------------------------------------------===//
2876// Other Instructions.
2877//===----------------------------------------------------------------------===//
2878
2879
2880/// ParseCast
2881/// ::= CastOpc TypeAndValue 'to' Type
2882bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2883 unsigned Opc) {
2884 LocTy Loc; Value *Op;
2885 PATypeHolder DestTy(Type::VoidTy);
2886 if (ParseTypeAndValue(Op, Loc, PFS) ||
2887 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2888 ParseType(DestTy))
2889 return true;
2890
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002891 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2892 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 return Error(Loc, "invalid cast opcode for cast from '" +
2894 Op->getType()->getDescription() + "' to '" +
2895 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002896 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002897 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2898 return false;
2899}
2900
2901/// ParseSelect
2902/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2903bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2904 LocTy Loc;
2905 Value *Op0, *Op1, *Op2;
2906 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2907 ParseToken(lltok::comma, "expected ',' after select condition") ||
2908 ParseTypeAndValue(Op1, PFS) ||
2909 ParseToken(lltok::comma, "expected ',' after select value") ||
2910 ParseTypeAndValue(Op2, PFS))
2911 return true;
2912
2913 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2914 return Error(Loc, Reason);
2915
2916 Inst = SelectInst::Create(Op0, Op1, Op2);
2917 return false;
2918}
2919
Chris Lattner0088a5c2009-01-05 08:18:44 +00002920/// ParseVA_Arg
2921/// ::= 'va_arg' TypeAndValue ',' Type
2922bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 Value *Op;
2924 PATypeHolder EltTy(Type::VoidTy);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002925 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00002926 if (ParseTypeAndValue(Op, PFS) ||
2927 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00002928 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00002930
2931 if (!EltTy->isFirstClassType())
2932 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002933
2934 Inst = new VAArgInst(Op, EltTy);
2935 return false;
2936}
2937
2938/// ParseExtractElement
2939/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2940bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2941 LocTy Loc;
2942 Value *Op0, *Op1;
2943 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2944 ParseToken(lltok::comma, "expected ',' after extract value") ||
2945 ParseTypeAndValue(Op1, PFS))
2946 return true;
2947
2948 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2949 return Error(Loc, "invalid extractelement operands");
2950
2951 Inst = new ExtractElementInst(Op0, Op1);
2952 return false;
2953}
2954
2955/// ParseInsertElement
2956/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2957bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2958 LocTy Loc;
2959 Value *Op0, *Op1, *Op2;
2960 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2961 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2962 ParseTypeAndValue(Op1, PFS) ||
2963 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2964 ParseTypeAndValue(Op2, PFS))
2965 return true;
2966
2967 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2968 return Error(Loc, "invalid extractelement operands");
2969
2970 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2971 return false;
2972}
2973
2974/// ParseShuffleVector
2975/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2976bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2977 LocTy Loc;
2978 Value *Op0, *Op1, *Op2;
2979 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2980 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2981 ParseTypeAndValue(Op1, PFS) ||
2982 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2983 ParseTypeAndValue(Op2, PFS))
2984 return true;
2985
2986 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2987 return Error(Loc, "invalid extractelement operands");
2988
2989 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2990 return false;
2991}
2992
2993/// ParsePHI
2994/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2995bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2996 PATypeHolder Ty(Type::VoidTy);
2997 Value *Op0, *Op1;
2998 LocTy TypeLoc = Lex.getLoc();
2999
3000 if (ParseType(Ty) ||
3001 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3002 ParseValue(Ty, Op0, PFS) ||
3003 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3004 ParseValue(Type::LabelTy, Op1, PFS) ||
3005 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3006 return true;
3007
3008 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3009 while (1) {
3010 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3011
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003012 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 break;
3014
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003015 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003016 ParseValue(Ty, Op0, PFS) ||
3017 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3018 ParseValue(Type::LabelTy, Op1, PFS) ||
3019 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3020 return true;
3021 }
3022
3023 if (!Ty->isFirstClassType())
3024 return Error(TypeLoc, "phi node must have first class type");
3025
3026 PHINode *PN = PHINode::Create(Ty);
3027 PN->reserveOperandSpace(PHIVals.size());
3028 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3029 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3030 Inst = PN;
3031 return false;
3032}
3033
3034/// ParseCall
3035/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3036/// ParameterList OptionalAttrs
3037bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3038 bool isTail) {
3039 unsigned CC, RetAttrs, FnAttrs;
3040 PATypeHolder RetType(Type::VoidTy);
3041 LocTy RetTypeLoc;
3042 ValID CalleeID;
3043 SmallVector<ParamInfo, 16> ArgList;
3044 LocTy CallLoc = Lex.getLoc();
3045
3046 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3047 ParseOptionalCallingConv(CC) ||
3048 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003049 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003050 ParseValID(CalleeID) ||
3051 ParseParameterList(ArgList, PFS) ||
3052 ParseOptionalAttrs(FnAttrs, 2))
3053 return true;
3054
3055 // If RetType is a non-function pointer type, then this is the short syntax
3056 // for the call, which means that RetType is just the return type. Infer the
3057 // rest of the function argument types from the arguments that are present.
3058 const PointerType *PFTy = 0;
3059 const FunctionType *Ty = 0;
3060 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3061 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3062 // Pull out the types of all of the arguments...
3063 std::vector<const Type*> ParamTypes;
3064 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3065 ParamTypes.push_back(ArgList[i].V->getType());
3066
3067 if (!FunctionType::isValidReturnType(RetType))
3068 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3069
Owen Andersonfba933c2009-07-01 23:57:11 +00003070 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3071 PFTy = Context.getPointerTypeUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 }
3073
3074 // Look up the callee.
3075 Value *Callee;
3076 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3077
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3079 // function attributes.
3080 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3081 if (FnAttrs & ObsoleteFuncAttrs) {
3082 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3083 FnAttrs &= ~ObsoleteFuncAttrs;
3084 }
3085
3086 // Set up the Attributes for the function.
3087 SmallVector<AttributeWithIndex, 8> Attrs;
3088 if (RetAttrs != Attribute::None)
3089 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3090
3091 SmallVector<Value*, 8> Args;
3092
3093 // Loop through FunctionType's arguments and ensure they are specified
3094 // correctly. Also, gather any parameter attributes.
3095 FunctionType::param_iterator I = Ty->param_begin();
3096 FunctionType::param_iterator E = Ty->param_end();
3097 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3098 const Type *ExpectedTy = 0;
3099 if (I != E) {
3100 ExpectedTy = *I++;
3101 } else if (!Ty->isVarArg()) {
3102 return Error(ArgList[i].Loc, "too many arguments specified");
3103 }
3104
3105 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3106 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3107 ExpectedTy->getDescription() + "'");
3108 Args.push_back(ArgList[i].V);
3109 if (ArgList[i].Attrs != Attribute::None)
3110 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3111 }
3112
3113 if (I != E)
3114 return Error(CallLoc, "not enough parameters specified for call");
3115
3116 if (FnAttrs != Attribute::None)
3117 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3118
3119 // Finish off the Attributes and check them
3120 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3121
3122 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3123 CI->setTailCall(isTail);
3124 CI->setCallingConv(CC);
3125 CI->setAttributes(PAL);
3126 Inst = CI;
3127 return false;
3128}
3129
3130//===----------------------------------------------------------------------===//
3131// Memory Instructions.
3132//===----------------------------------------------------------------------===//
3133
3134/// ParseAlloc
3135/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3136/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3137bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3138 unsigned Opc) {
3139 PATypeHolder Ty(Type::VoidTy);
3140 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003141 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003142 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003143 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003144
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003145 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003146 if (Lex.getKind() == lltok::kw_align) {
3147 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003148 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3149 ParseOptionalCommaAlignment(Alignment)) {
3150 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003151 }
3152 }
3153
3154 if (Size && Size->getType() != Type::Int32Ty)
3155 return Error(SizeLoc, "element count must be i32");
3156
3157 if (Opc == Instruction::Malloc)
3158 Inst = new MallocInst(Ty, Size, Alignment);
3159 else
3160 Inst = new AllocaInst(Ty, Size, Alignment);
3161 return false;
3162}
3163
3164/// ParseFree
3165/// ::= 'free' TypeAndValue
3166bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3167 Value *Val; LocTy Loc;
3168 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3169 if (!isa<PointerType>(Val->getType()))
3170 return Error(Loc, "operand to free must be a pointer");
3171 Inst = new FreeInst(Val);
3172 return false;
3173}
3174
3175/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003176/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003177bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3178 bool isVolatile) {
3179 Value *Val; LocTy Loc;
3180 unsigned Alignment;
3181 if (ParseTypeAndValue(Val, Loc, PFS) ||
3182 ParseOptionalCommaAlignment(Alignment))
3183 return true;
3184
3185 if (!isa<PointerType>(Val->getType()) ||
3186 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3187 return Error(Loc, "load operand must be a pointer to a first class type");
3188
3189 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3190 return false;
3191}
3192
3193/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003194/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003195bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3196 bool isVolatile) {
3197 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3198 unsigned Alignment;
3199 if (ParseTypeAndValue(Val, Loc, PFS) ||
3200 ParseToken(lltok::comma, "expected ',' after store operand") ||
3201 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3202 ParseOptionalCommaAlignment(Alignment))
3203 return true;
3204
3205 if (!isa<PointerType>(Ptr->getType()))
3206 return Error(PtrLoc, "store operand must be a pointer");
3207 if (!Val->getType()->isFirstClassType())
3208 return Error(Loc, "store operand must be a first class value");
3209 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3210 return Error(Loc, "stored value and pointer type do not match");
3211
3212 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3213 return false;
3214}
3215
3216/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003217/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003218/// FIXME: Remove support for getresult in LLVM 3.0
3219bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3220 Value *Val; LocTy ValLoc, EltLoc;
3221 unsigned Element;
3222 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3223 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003224 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 return true;
3226
3227 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3228 return Error(ValLoc, "getresult inst requires an aggregate operand");
3229 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3230 return Error(EltLoc, "invalid getresult index for value");
3231 Inst = ExtractValueInst::Create(Val, Element);
3232 return false;
3233}
3234
3235/// ParseGetElementPtr
3236/// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3237bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3238 Value *Ptr, *Val; LocTy Loc, EltLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003239 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003240
3241 if (!isa<PointerType>(Ptr->getType()))
3242 return Error(Loc, "base of getelementptr must be a pointer");
3243
3244 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003245 while (EatIfPresent(lltok::comma)) {
3246 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 if (!isa<IntegerType>(Val->getType()))
3248 return Error(EltLoc, "getelementptr index must be an integer");
3249 Indices.push_back(Val);
3250 }
3251
3252 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3253 Indices.begin(), Indices.end()))
3254 return Error(Loc, "invalid getelementptr indices");
3255 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3256 return false;
3257}
3258
3259/// ParseExtractValue
3260/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3261bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3262 Value *Val; LocTy Loc;
3263 SmallVector<unsigned, 4> Indices;
3264 if (ParseTypeAndValue(Val, Loc, PFS) ||
3265 ParseIndexList(Indices))
3266 return true;
3267
3268 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3269 return Error(Loc, "extractvalue operand must be array or struct");
3270
3271 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3272 Indices.end()))
3273 return Error(Loc, "invalid indices for extractvalue");
3274 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3275 return false;
3276}
3277
3278/// ParseInsertValue
3279/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3280bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3281 Value *Val0, *Val1; LocTy Loc0, Loc1;
3282 SmallVector<unsigned, 4> Indices;
3283 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3284 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3285 ParseTypeAndValue(Val1, Loc1, PFS) ||
3286 ParseIndexList(Indices))
3287 return true;
3288
3289 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3290 return Error(Loc0, "extractvalue operand must be array or struct");
3291
3292 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3293 Indices.end()))
3294 return Error(Loc0, "invalid indices for insertvalue");
3295 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3296 return false;
3297}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003298
3299//===----------------------------------------------------------------------===//
3300// Embedded metadata.
3301//===----------------------------------------------------------------------===//
3302
3303/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003304/// ::= Element (',' Element)*
3305/// Element
3306/// ::= 'null' | TypeAndValue
3307bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003308 assert(Lex.getKind() == lltok::lbrace);
3309 Lex.Lex();
3310 do {
Nick Lewyckycb337992009-05-10 20:57:05 +00003311 Value *V;
3312 if (Lex.getKind() == lltok::kw_null) {
3313 Lex.Lex();
3314 V = 0;
3315 } else {
3316 Constant *C;
3317 if (ParseGlobalTypeAndValue(C)) return true;
3318 V = C;
3319 }
3320 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003321 } while (EatIfPresent(lltok::comma));
3322
3323 return false;
3324}