blob: ec7bc650c45e5b5cdf7d21ff18f7cddec09e8104 [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"
Devang Patel0a9f7b92009-07-28 21:49:47 +000022#include "llvm/Metadata.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000024#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000025#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000029#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
Chris Lattnerdf986172009-01-02 07:01:27 +000032namespace llvm {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000033 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
Chris Lattnerdf986172009-01-02 07:01:27 +000037 struct ValID {
38 enum {
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
Chris Lattner081b5052009-01-05 07:52:51 +000043 t_EmptyArray, // No value: []
Chris Lattnerdf986172009-01-02 07:01:27 +000044 t_Constant, // Value in ConstantVal.
Devang Patele54abc92009-07-22 17:43:22 +000045 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
Chris Lattnerdf986172009-01-02 07:01:27 +000047 } Kind;
48
49 LLParser::LocTy Loc;
50 unsigned UIntVal;
51 std::string StrVal, StrVal2;
52 APSInt APSIntVal;
53 APFloat APFloatVal;
54 Constant *ConstantVal;
Devang Patele54abc92009-07-22 17:43:22 +000055 MetadataBase *MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +000056 ValID() : APFloatVal(0.0) {}
57 };
58}
59
Chris Lattner3ed88ef2009-01-02 08:05:26 +000060/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000061bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000062 // Prime the lexer.
63 Lex.Lex();
64
Chris Lattnerad7d1e22009-01-04 20:44:11 +000065 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000067}
68
69/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70/// module.
71bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
80
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
84 "'");
85
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
90
Devang Patel1c7eea62009-07-08 19:23:54 +000091 if (!ForwardRefMDNodes.empty())
92 return Error(ForwardRefMDNodes.begin()->second.second,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes.begin()->first) + "'");
95
96
Chris Lattnerdf986172009-01-02 07:01:27 +000097 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100
101 return false;
102}
103
104//===----------------------------------------------------------------------===//
105// Top-Level Entities
106//===----------------------------------------------------------------------===//
107
108bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 while (1) {
110 switch (Lex.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare: if (ParseDeclare()) return true; break;
115 case lltok::kw_define: if (ParseDefine()) return true; break;
116 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000120 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000121 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
122 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000123 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000124 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000125 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Pateleff2ab62009-07-29 00:34:02 +0000126 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000127
128 // The Global variable production with no name can have many different
129 // optional leading prefixes, the production is:
130 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
131 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000132 case lltok::kw_private : // OptionalLinkage
133 case lltok::kw_linker_private: // OptionalLinkage
134 case lltok::kw_internal: // OptionalLinkage
135 case lltok::kw_weak: // OptionalLinkage
136 case lltok::kw_weak_odr: // OptionalLinkage
137 case lltok::kw_linkonce: // OptionalLinkage
138 case lltok::kw_linkonce_odr: // OptionalLinkage
139 case lltok::kw_appending: // OptionalLinkage
140 case lltok::kw_dllexport: // OptionalLinkage
141 case lltok::kw_common: // OptionalLinkage
142 case lltok::kw_dllimport: // OptionalLinkage
143 case lltok::kw_extern_weak: // OptionalLinkage
144 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000145 unsigned Linkage, Visibility;
146 if (ParseOptionalLinkage(Linkage) ||
147 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000148 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000149 return true;
150 break;
151 }
152 case lltok::kw_default: // OptionalVisibility
153 case lltok::kw_hidden: // OptionalVisibility
154 case lltok::kw_protected: { // OptionalVisibility
155 unsigned Visibility;
156 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000157 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000158 return true;
159 break;
160 }
161
162 case lltok::kw_thread_local: // OptionalThreadLocal
163 case lltok::kw_addrspace: // OptionalAddrSpace
164 case lltok::kw_constant: // GlobalType
165 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000166 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 break;
168 }
169 }
170}
171
172
173/// toplevelentity
174/// ::= 'module' 'asm' STRINGCONSTANT
175bool LLParser::ParseModuleAsm() {
176 assert(Lex.getKind() == lltok::kw_module);
177 Lex.Lex();
178
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000179 std::string AsmStr;
180 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
181 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000182
183 const std::string &AsmSoFar = M->getModuleInlineAsm();
184 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000185 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 return false;
189}
190
191/// toplevelentity
192/// ::= 'target' 'triple' '=' STRINGCONSTANT
193/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
194bool LLParser::ParseTargetDefinition() {
195 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000196 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000197 switch (Lex.Lex()) {
198 default: return TokError("unknown target property");
199 case lltok::kw_triple:
200 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000201 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
202 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return false;
206 case lltok::kw_datalayout:
207 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000208 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
209 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000210 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000211 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return false;
213 }
214}
215
216/// toplevelentity
217/// ::= 'deplibs' '=' '[' ']'
218/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
219bool LLParser::ParseDepLibs() {
220 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000222 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
223 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
224 return true;
225
226 if (EatIfPresent(lltok::rsquare))
227 return false;
228
229 std::string Str;
230 if (ParseStringConstant(Str)) return true;
231 M->addLibrary(Str);
232
233 while (EatIfPresent(lltok::comma)) {
234 if (ParseStringConstant(Str)) return true;
235 M->addLibrary(Str);
236 }
237
238 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000239}
240
Dan Gohman3845e502009-08-12 23:32:33 +0000241/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000242/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000243/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000244bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000245 unsigned TypeID = NumberedTypes.size();
246
247 // Handle the LocalVarID form.
248 if (Lex.getKind() == lltok::LocalVarID) {
249 if (Lex.getUIntVal() != TypeID)
250 return Error(Lex.getLoc(), "type expected to be numbered '%" +
251 utostr(TypeID) + "'");
252 Lex.Lex(); // eat LocalVarID;
253
254 if (ParseToken(lltok::equal, "expected '=' after name"))
255 return true;
256 }
257
Chris Lattnerdf986172009-01-02 07:01:27 +0000258 assert(Lex.getKind() == lltok::kw_type);
259 LocTy TypeLoc = Lex.getLoc();
260 Lex.Lex(); // eat kw_type
261
Owen Anderson1d0be152009-08-13 21:58:54 +0000262 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000263 if (ParseType(Ty)) return true;
264
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 // See if this type was previously referenced.
266 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
267 FI = ForwardRefTypeIDs.find(TypeID);
268 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000269 if (FI->second.first.get() == Ty)
270 return Error(TypeLoc, "self referential type is invalid");
271
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
273 Ty = FI->second.first.get();
274 ForwardRefTypeIDs.erase(FI);
275 }
276
277 NumberedTypes.push_back(Ty);
278
279 return false;
280}
281
282/// toplevelentity
283/// ::= LocalVar '=' 'type' type
284bool LLParser::ParseNamedType() {
285 std::string Name = Lex.getStrVal();
286 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000287 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000288
Owen Anderson1d0be152009-08-13 21:58:54 +0000289 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000290
291 if (ParseToken(lltok::equal, "expected '=' after name") ||
292 ParseToken(lltok::kw_type, "expected 'type' after name") ||
293 ParseType(Ty))
294 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296 // Set the type name, checking for conflicts as we do so.
297 bool AlreadyExists = M->addTypeName(Name, Ty);
298 if (!AlreadyExists) return false;
299
300 // See if this type is a forward reference. We need to eagerly resolve
301 // types to allow recursive type redefinitions below.
302 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
303 FI = ForwardRefTypes.find(Name);
304 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000305 if (FI->second.first.get() == Ty)
306 return Error(NameLoc, "self referential type is invalid");
307
Chris Lattnerdf986172009-01-02 07:01:27 +0000308 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
309 Ty = FI->second.first.get();
310 ForwardRefTypes.erase(FI);
311 }
312
313 // Inserting a name that is already defined, get the existing name.
314 const Type *Existing = M->getTypeByName(Name);
315 assert(Existing && "Conflict but no matching type?!");
316
317 // Otherwise, this is an attempt to redefine a type. That's okay if
318 // the redefinition is identical to the original.
319 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
320 if (Existing == Ty) return false;
321
322 // Any other kind of (non-equivalent) redefinition is an error.
323 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
324 Ty->getDescription() + "'");
325}
326
327
328/// toplevelentity
329/// ::= 'declare' FunctionHeader
330bool LLParser::ParseDeclare() {
331 assert(Lex.getKind() == lltok::kw_declare);
332 Lex.Lex();
333
334 Function *F;
335 return ParseFunctionHeader(F, false);
336}
337
338/// toplevelentity
339/// ::= 'define' FunctionHeader '{' ...
340bool LLParser::ParseDefine() {
341 assert(Lex.getKind() == lltok::kw_define);
342 Lex.Lex();
343
344 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000345 return ParseFunctionHeader(F, true) ||
346 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000347}
348
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000349/// ParseGlobalType
350/// ::= 'constant'
351/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000352bool LLParser::ParseGlobalType(bool &IsConstant) {
353 if (Lex.getKind() == lltok::kw_constant)
354 IsConstant = true;
355 else if (Lex.getKind() == lltok::kw_global)
356 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000357 else {
358 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000359 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000360 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 Lex.Lex();
362 return false;
363}
364
Dan Gohman3845e502009-08-12 23:32:33 +0000365/// ParseUnnamedGlobal:
366/// OptionalVisibility ALIAS ...
367/// OptionalLinkage OptionalVisibility ... -> global variable
368/// GlobalID '=' OptionalVisibility ALIAS ...
369/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
370bool LLParser::ParseUnnamedGlobal() {
371 unsigned VarID = NumberedVals.size();
372 std::string Name;
373 LocTy NameLoc = Lex.getLoc();
374
375 // Handle the GlobalID form.
376 if (Lex.getKind() == lltok::GlobalID) {
377 if (Lex.getUIntVal() != VarID)
378 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
379 utostr(VarID) + "'");
380 Lex.Lex(); // eat GlobalID;
381
382 if (ParseToken(lltok::equal, "expected '=' after name"))
383 return true;
384 }
385
386 bool HasLinkage;
387 unsigned Linkage, Visibility;
388 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
389 ParseOptionalVisibility(Visibility))
390 return true;
391
392 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
393 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
394 return ParseAlias(Name, NameLoc, Visibility);
395}
396
Chris Lattnerdf986172009-01-02 07:01:27 +0000397/// ParseNamedGlobal:
398/// GlobalVar '=' OptionalVisibility ALIAS ...
399/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
400bool LLParser::ParseNamedGlobal() {
401 assert(Lex.getKind() == lltok::GlobalVar);
402 LocTy NameLoc = Lex.getLoc();
403 std::string Name = Lex.getStrVal();
404 Lex.Lex();
405
406 bool HasLinkage;
407 unsigned Linkage, Visibility;
408 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
409 ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
411 return true;
412
413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
416}
417
Devang Patel256be962009-07-20 19:00:08 +0000418// MDString:
419// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000420bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000421 std::string Str;
422 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000423 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000424 return false;
425}
426
427// MDNode:
428// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000429bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000430 // !{ ..., !42, ... }
431 unsigned MID = 0;
432 if (ParseUInt32(MID)) return true;
433
434 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000435 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000436 if (I != MetadataCache.end()) {
437 Node = I->second;
438 return false;
439 }
440
441 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000442 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000443 FI = ForwardRefMDNodes.find(MID);
444 if (FI != ForwardRefMDNodes.end()) {
445 Node = FI->second.first;
446 return false;
447 }
448
449 // Create MDNode forward reference
450 SmallVector<Value *, 1> Elts;
451 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000452 Elts.push_back(MDString::get(Context, FwdRefName));
453 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000454 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
455 Node = FwdNode;
456 return false;
457}
458
Devang Pateleff2ab62009-07-29 00:34:02 +0000459///ParseNamedMetadata:
460/// !foo = !{ !1, !2 }
461bool LLParser::ParseNamedMetadata() {
462 assert(Lex.getKind() == lltok::NamedMD);
463 Lex.Lex();
464 std::string Name = Lex.getStrVal();
465
466 if (ParseToken(lltok::equal, "expected '=' here"))
467 return true;
468
469 if (Lex.getKind() != lltok::Metadata)
470 return TokError("Expected '!' here");
471 Lex.Lex();
472
473 if (Lex.getKind() != lltok::lbrace)
474 return TokError("Expected '{' here");
475 Lex.Lex();
476 SmallVector<MetadataBase *, 8> Elts;
477 do {
478 if (Lex.getKind() != lltok::Metadata)
479 return TokError("Expected '!' here");
480 Lex.Lex();
481 MetadataBase *N = 0;
482 if (ParseMDNode(N)) return true;
483 Elts.push_back(N);
484 } while (EatIfPresent(lltok::comma));
485
486 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
487 return true;
488
Owen Anderson1d0be152009-08-13 21:58:54 +0000489 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000490 return false;
491}
492
Devang Patel923078c2009-07-01 19:21:12 +0000493/// ParseStandaloneMetadata:
494/// !42 = !{...}
495bool LLParser::ParseStandaloneMetadata() {
496 assert(Lex.getKind() == lltok::Metadata);
497 Lex.Lex();
498 unsigned MetadataID = 0;
499 if (ParseUInt32(MetadataID))
500 return true;
501 if (MetadataCache.find(MetadataID) != MetadataCache.end())
502 return TokError("Metadata id is already used");
503 if (ParseToken(lltok::equal, "expected '=' here"))
504 return true;
505
506 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000507 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000508 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000509 return true;
510
Devang Patel104cf9e2009-07-23 01:07:34 +0000511 if (Lex.getKind() != lltok::Metadata)
512 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000513
Devang Patel104cf9e2009-07-23 01:07:34 +0000514 Lex.Lex();
515 if (Lex.getKind() != lltok::lbrace)
516 return TokError("Expected '{' here");
517
518 SmallVector<Value *, 16> Elts;
519 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000520 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000521 return true;
522
Owen Anderson647e3012009-07-31 21:35:40 +0000523 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000524 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000525 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000526 FI = ForwardRefMDNodes.find(MetadataID);
527 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000528 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000529 FwdNode->replaceAllUsesWith(Init);
530 ForwardRefMDNodes.erase(FI);
531 }
532
Devang Patel923078c2009-07-01 19:21:12 +0000533 return false;
534}
535
Chris Lattnerdf986172009-01-02 07:01:27 +0000536/// ParseAlias:
537/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
538/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000539/// ::= TypeAndValue
540/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000541/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000542///
543/// Everything through visibility has already been parsed.
544///
545bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
546 unsigned Visibility) {
547 assert(Lex.getKind() == lltok::kw_alias);
548 Lex.Lex();
549 unsigned Linkage;
550 LocTy LinkageLoc = Lex.getLoc();
551 if (ParseOptionalLinkage(Linkage))
552 return true;
553
554 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000555 Linkage != GlobalValue::WeakAnyLinkage &&
556 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000557 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000558 Linkage != GlobalValue::PrivateLinkage &&
559 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000560 return Error(LinkageLoc, "invalid linkage type for alias");
561
562 Constant *Aliasee;
563 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000564 if (Lex.getKind() != lltok::kw_bitcast &&
565 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000566 if (ParseGlobalTypeAndValue(Aliasee)) return true;
567 } else {
568 // The bitcast dest type is not present, it is implied by the dest type.
569 ValID ID;
570 if (ParseValID(ID)) return true;
571 if (ID.Kind != ValID::t_Constant)
572 return Error(AliaseeLoc, "invalid aliasee");
573 Aliasee = ID.ConstantVal;
574 }
575
576 if (!isa<PointerType>(Aliasee->getType()))
577 return Error(AliaseeLoc, "alias must have pointer type");
578
579 // Okay, create the alias but do not insert it into the module yet.
580 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
581 (GlobalValue::LinkageTypes)Linkage, Name,
582 Aliasee);
583 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
584
585 // See if this value already exists in the symbol table. If so, it is either
586 // a redefinition or a definition of a forward reference.
587 if (GlobalValue *Val =
588 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
589 // See if this was a redefinition. If so, there is no entry in
590 // ForwardRefVals.
591 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
592 I = ForwardRefVals.find(Name);
593 if (I == ForwardRefVals.end())
594 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
595
596 // Otherwise, this was a definition of forward ref. Verify that types
597 // agree.
598 if (Val->getType() != GA->getType())
599 return Error(NameLoc,
600 "forward reference and definition of alias have different types");
601
602 // If they agree, just RAUW the old value with the alias and remove the
603 // forward ref info.
604 Val->replaceAllUsesWith(GA);
605 Val->eraseFromParent();
606 ForwardRefVals.erase(I);
607 }
608
609 // Insert into the module, we know its name won't collide now.
610 M->getAliasList().push_back(GA);
611 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
612
613 return false;
614}
615
616/// ParseGlobal
617/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
618/// OptionalAddrSpace GlobalType Type Const
619/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
620/// OptionalAddrSpace GlobalType Type Const
621///
622/// Everything through visibility has been parsed already.
623///
624bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
625 unsigned Linkage, bool HasLinkage,
626 unsigned Visibility) {
627 unsigned AddrSpace;
628 bool ThreadLocal, IsConstant;
629 LocTy TyLoc;
630
Owen Anderson1d0be152009-08-13 21:58:54 +0000631 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000632 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
633 ParseOptionalAddrSpace(AddrSpace) ||
634 ParseGlobalType(IsConstant) ||
635 ParseType(Ty, TyLoc))
636 return true;
637
638 // If the linkage is specified and is external, then no initializer is
639 // present.
640 Constant *Init = 0;
641 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000642 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000643 Linkage != GlobalValue::ExternalLinkage)) {
644 if (ParseGlobalValue(Ty, Init))
645 return true;
646 }
647
Owen Anderson1d0be152009-08-13 21:58:54 +0000648 if (isa<FunctionType>(Ty) || Ty == Type::getLabelTy(Context))
Chris Lattner4a2f1122009-02-08 20:00:15 +0000649 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000650
651 GlobalVariable *GV = 0;
652
653 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000654 if (!Name.empty()) {
655 if ((GV = M->getGlobalVariable(Name, true)) &&
656 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 return Error(NameLoc, "redefinition of global '@" + Name + "'");
658 } else {
659 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefValIDs.find(NumberedVals.size());
661 if (I != ForwardRefValIDs.end()) {
662 GV = cast<GlobalVariable>(I->second.first);
663 ForwardRefValIDs.erase(I);
664 }
665 }
666
667 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000668 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
669 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 } else {
671 if (GV->getType()->getElementType() != Ty)
672 return Error(TyLoc,
673 "forward reference and definition of global have different types");
674
675 // Move the forward-reference to the correct spot in the module.
676 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
677 }
678
679 if (Name.empty())
680 NumberedVals.push_back(GV);
681
682 // Set the parsed properties on the global.
683 if (Init)
684 GV->setInitializer(Init);
685 GV->setConstant(IsConstant);
686 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
687 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
688 GV->setThreadLocal(ThreadLocal);
689
690 // Parse attributes on the global.
691 while (Lex.getKind() == lltok::comma) {
692 Lex.Lex();
693
694 if (Lex.getKind() == lltok::kw_section) {
695 Lex.Lex();
696 GV->setSection(Lex.getStrVal());
697 if (ParseToken(lltok::StringConstant, "expected global section string"))
698 return true;
699 } else if (Lex.getKind() == lltok::kw_align) {
700 unsigned Alignment;
701 if (ParseOptionalAlignment(Alignment)) return true;
702 GV->setAlignment(Alignment);
703 } else {
704 TokError("unknown global variable property!");
705 }
706 }
707
708 return false;
709}
710
711
712//===----------------------------------------------------------------------===//
713// GlobalValue Reference/Resolution Routines.
714//===----------------------------------------------------------------------===//
715
716/// GetGlobalVal - Get a value with the specified name or ID, creating a
717/// forward reference record if needed. This can return null if the value
718/// exists but does not have the right type.
719GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
720 LocTy Loc) {
721 const PointerType *PTy = dyn_cast<PointerType>(Ty);
722 if (PTy == 0) {
723 Error(Loc, "global variable reference must have pointer type");
724 return 0;
725 }
726
727 // Look this name up in the normal function symbol table.
728 GlobalValue *Val =
729 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
730
731 // If this is a forward reference for the value, see if we already created a
732 // forward ref record.
733 if (Val == 0) {
734 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefVals.find(Name);
736 if (I != ForwardRefVals.end())
737 Val = I->second.first;
738 }
739
740 // If we have the value in the symbol table or fwd-ref table, return it.
741 if (Val) {
742 if (Val->getType() == Ty) return Val;
743 Error(Loc, "'@" + Name + "' defined with type '" +
744 Val->getType()->getDescription() + "'");
745 return 0;
746 }
747
748 // Otherwise, create a new forward reference for this value and remember it.
749 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000750 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
751 // Function types can return opaque but functions can't.
752 if (isa<OpaqueType>(FT->getReturnType())) {
753 Error(Loc, "function may not return opaque type");
754 return 0;
755 }
756
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000757 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000758 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000759 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
760 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000761 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000762
763 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
764 return FwdVal;
765}
766
767GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
768 const PointerType *PTy = dyn_cast<PointerType>(Ty);
769 if (PTy == 0) {
770 Error(Loc, "global variable reference must have pointer type");
771 return 0;
772 }
773
774 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
775
776 // If this is a forward reference for the value, see if we already created a
777 // forward ref record.
778 if (Val == 0) {
779 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
780 I = ForwardRefValIDs.find(ID);
781 if (I != ForwardRefValIDs.end())
782 Val = I->second.first;
783 }
784
785 // If we have the value in the symbol table or fwd-ref table, return it.
786 if (Val) {
787 if (Val->getType() == Ty) return Val;
788 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
789 Val->getType()->getDescription() + "'");
790 return 0;
791 }
792
793 // Otherwise, create a new forward reference for this value and remember it.
794 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000795 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
796 // Function types can return opaque but functions can't.
797 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000798 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000799 return 0;
800 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000801 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000802 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000803 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
804 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000805 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000806
807 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
808 return FwdVal;
809}
810
811
812//===----------------------------------------------------------------------===//
813// Helper Routines.
814//===----------------------------------------------------------------------===//
815
816/// ParseToken - If the current token has the specified kind, eat it and return
817/// success. Otherwise, emit the specified error and return failure.
818bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
819 if (Lex.getKind() != T)
820 return TokError(ErrMsg);
821 Lex.Lex();
822 return false;
823}
824
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000825/// ParseStringConstant
826/// ::= StringConstant
827bool LLParser::ParseStringConstant(std::string &Result) {
828 if (Lex.getKind() != lltok::StringConstant)
829 return TokError("expected string constant");
830 Result = Lex.getStrVal();
831 Lex.Lex();
832 return false;
833}
834
835/// ParseUInt32
836/// ::= uint32
837bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
839 return TokError("expected integer");
840 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
841 if (Val64 != unsigned(Val64))
842 return TokError("expected 32-bit integer (too large)");
843 Val = Val64;
844 Lex.Lex();
845 return false;
846}
847
848
849/// ParseOptionalAddrSpace
850/// := /*empty*/
851/// := 'addrspace' '(' uint32 ')'
852bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
853 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000854 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000855 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000856 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000857 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 ParseToken(lltok::rparen, "expected ')' in address space");
859}
860
861/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
862/// indicates what kind of attribute list this is: 0: function arg, 1: result,
863/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000864/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000865bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
866 Attrs = Attribute::None;
867 LocTy AttrLoc = Lex.getLoc();
868
869 while (1) {
870 switch (Lex.getKind()) {
871 case lltok::kw_sext:
872 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000873 // Treat these as signext/zeroext if they occur in the argument list after
874 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
875 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
876 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000878 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 if (Lex.getKind() == lltok::kw_sext)
880 Attrs |= Attribute::SExt;
881 else
882 Attrs |= Attribute::ZExt;
883 break;
884 }
885 // FALL THROUGH.
886 default: // End of attributes.
887 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
888 return Error(AttrLoc, "invalid use of function-only attribute");
889
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000890 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000891 return Error(AttrLoc, "invalid use of parameter-only attribute");
892
893 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000894 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
895 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
896 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
897 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
898 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
899 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
900 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
901 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000902
Devang Patel578efa92009-06-05 21:57:13 +0000903 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
904 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
905 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
906 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
907 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
908 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
909 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
910 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
911 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
912 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
913 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000914 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000915
916 case lltok::kw_align: {
917 unsigned Alignment;
918 if (ParseOptionalAlignment(Alignment))
919 return true;
920 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
921 continue;
922 }
923 }
924 Lex.Lex();
925 }
926}
927
928/// ParseOptionalLinkage
929/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000930/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000931/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000932/// ::= 'internal'
933/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000934/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000935/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000936/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000937/// ::= 'appending'
938/// ::= 'dllexport'
939/// ::= 'common'
940/// ::= 'dllimport'
941/// ::= 'extern_weak'
942/// ::= 'external'
943bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
944 HasLinkage = false;
945 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000946 default: Res=GlobalValue::ExternalLinkage; return false;
947 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
948 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
949 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
950 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
951 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
952 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
953 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000954 case lltok::kw_available_externally:
955 Res = GlobalValue::AvailableExternallyLinkage;
956 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000957 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
958 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
959 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
960 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
961 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
962 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000963 }
964 Lex.Lex();
965 HasLinkage = true;
966 return false;
967}
968
969/// ParseOptionalVisibility
970/// ::= /*empty*/
971/// ::= 'default'
972/// ::= 'hidden'
973/// ::= 'protected'
974///
975bool LLParser::ParseOptionalVisibility(unsigned &Res) {
976 switch (Lex.getKind()) {
977 default: Res = GlobalValue::DefaultVisibility; return false;
978 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
979 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
980 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
981 }
982 Lex.Lex();
983 return false;
984}
985
986/// ParseOptionalCallingConv
987/// ::= /*empty*/
988/// ::= 'ccc'
989/// ::= 'fastcc'
990/// ::= 'coldcc'
991/// ::= 'x86_stdcallcc'
992/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000993/// ::= 'arm_apcscc'
994/// ::= 'arm_aapcscc'
995/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000996/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000997///
Chris Lattnerdf986172009-01-02 07:01:27 +0000998bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
999 switch (Lex.getKind()) {
1000 default: CC = CallingConv::C; return false;
1001 case lltok::kw_ccc: CC = CallingConv::C; break;
1002 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1003 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1004 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1005 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001006 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1007 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1008 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001009 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +00001010 }
1011 Lex.Lex();
1012 return false;
1013}
1014
1015/// ParseOptionalAlignment
1016/// ::= /* empty */
1017/// ::= 'align' 4
1018bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1019 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001020 if (!EatIfPresent(lltok::kw_align))
1021 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001022 LocTy AlignLoc = Lex.getLoc();
1023 if (ParseUInt32(Alignment)) return true;
1024 if (!isPowerOf2_32(Alignment))
1025 return Error(AlignLoc, "alignment is not a power of two");
1026 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001027}
1028
1029/// ParseOptionalCommaAlignment
1030/// ::= /* empty */
1031/// ::= ',' 'align' 4
1032bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1033 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001034 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00001035 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001036 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001037 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001038}
1039
1040/// ParseIndexList
1041/// ::= (',' uint32)+
1042bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1043 if (Lex.getKind() != lltok::comma)
1044 return TokError("expected ',' as start of index list");
1045
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001046 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001047 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001048 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001049 Indices.push_back(Idx);
1050 }
1051
1052 return false;
1053}
1054
1055//===----------------------------------------------------------------------===//
1056// Type Parsing.
1057//===----------------------------------------------------------------------===//
1058
1059/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001060bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1061 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001062 if (ParseTypeRec(Result)) return true;
1063
1064 // Verify no unresolved uprefs.
1065 if (!UpRefs.empty())
1066 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +00001067
Owen Anderson1d0be152009-08-13 21:58:54 +00001068 if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001069 return Error(TypeLoc, "void type only allowed for function results");
1070
Chris Lattnerdf986172009-01-02 07:01:27 +00001071 return false;
1072}
1073
1074/// HandleUpRefs - Every time we finish a new layer of types, this function is
1075/// called. It loops through the UpRefs vector, which is a list of the
1076/// currently active types. For each type, if the up-reference is contained in
1077/// the newly completed type, we decrement the level count. When the level
1078/// count reaches zero, the up-referenced type is the type that is passed in:
1079/// thus we can complete the cycle.
1080///
1081PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1082 // If Ty isn't abstract, or if there are no up-references in it, then there is
1083 // nothing to resolve here.
1084 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1085
1086 PATypeHolder Ty(ty);
1087#if 0
1088 errs() << "Type '" << Ty->getDescription()
1089 << "' newly formed. Resolving upreferences.\n"
1090 << UpRefs.size() << " upreferences active!\n";
1091#endif
1092
1093 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1094 // to zero), we resolve them all together before we resolve them to Ty. At
1095 // the end of the loop, if there is anything to resolve to Ty, it will be in
1096 // this variable.
1097 OpaqueType *TypeToResolve = 0;
1098
1099 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1100 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1101 bool ContainsType =
1102 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1103 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1104
1105#if 0
1106 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1107 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1108 << (ContainsType ? "true" : "false")
1109 << " level=" << UpRefs[i].NestingLevel << "\n";
1110#endif
1111 if (!ContainsType)
1112 continue;
1113
1114 // Decrement level of upreference
1115 unsigned Level = --UpRefs[i].NestingLevel;
1116 UpRefs[i].LastContainedTy = Ty;
1117
1118 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1119 if (Level != 0)
1120 continue;
1121
1122#if 0
1123 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1124#endif
1125 if (!TypeToResolve)
1126 TypeToResolve = UpRefs[i].UpRefTy;
1127 else
1128 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1129 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1130 --i; // Do not skip the next element.
1131 }
1132
1133 if (TypeToResolve)
1134 TypeToResolve->refineAbstractTypeTo(Ty);
1135
1136 return Ty;
1137}
1138
1139
1140/// ParseTypeRec - The recursive function used to process the internal
1141/// implementation details of types.
1142bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1143 switch (Lex.getKind()) {
1144 default:
1145 return TokError("expected type");
1146 case lltok::Type:
1147 // TypeRec ::= 'float' | 'void' (etc)
1148 Result = Lex.getTyVal();
1149 Lex.Lex();
1150 break;
1151 case lltok::kw_opaque:
1152 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001153 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 Lex.Lex();
1155 break;
1156 case lltok::lbrace:
1157 // TypeRec ::= '{' ... '}'
1158 if (ParseStructType(Result, false))
1159 return true;
1160 break;
1161 case lltok::lsquare:
1162 // TypeRec ::= '[' ... ']'
1163 Lex.Lex(); // eat the lsquare.
1164 if (ParseArrayVectorType(Result, false))
1165 return true;
1166 break;
1167 case lltok::less: // Either vector or packed struct.
1168 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001169 Lex.Lex();
1170 if (Lex.getKind() == lltok::lbrace) {
1171 if (ParseStructType(Result, true) ||
1172 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001173 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 } else if (ParseArrayVectorType(Result, true))
1175 return true;
1176 break;
1177 case lltok::LocalVar:
1178 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1179 // TypeRec ::= %foo
1180 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1181 Result = T;
1182 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001183 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001184 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1185 std::make_pair(Result,
1186 Lex.getLoc())));
1187 M->addTypeName(Lex.getStrVal(), Result.get());
1188 }
1189 Lex.Lex();
1190 break;
1191
1192 case lltok::LocalVarID:
1193 // TypeRec ::= %4
1194 if (Lex.getUIntVal() < NumberedTypes.size())
1195 Result = NumberedTypes[Lex.getUIntVal()];
1196 else {
1197 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1198 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1199 if (I != ForwardRefTypeIDs.end())
1200 Result = I->second.first;
1201 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001202 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001203 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1204 std::make_pair(Result,
1205 Lex.getLoc())));
1206 }
1207 }
1208 Lex.Lex();
1209 break;
1210 case lltok::backslash: {
1211 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001212 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001213 unsigned Val;
1214 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001215 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1217 Result = OT;
1218 break;
1219 }
1220 }
1221
1222 // Parse the type suffixes.
1223 while (1) {
1224 switch (Lex.getKind()) {
1225 // End of type.
1226 default: return false;
1227
1228 // TypeRec ::= TypeRec '*'
1229 case lltok::star:
Owen Anderson1d0be152009-08-13 21:58:54 +00001230 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001231 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001232 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001233 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001234 if (!PointerType::isValidElementType(Result.get()))
1235 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001236 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 Lex.Lex();
1238 break;
1239
1240 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1241 case lltok::kw_addrspace: {
Owen Anderson1d0be152009-08-13 21:58:54 +00001242 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001244 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001245 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001246 if (!PointerType::isValidElementType(Result.get()))
1247 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001248 unsigned AddrSpace;
1249 if (ParseOptionalAddrSpace(AddrSpace) ||
1250 ParseToken(lltok::star, "expected '*' in address space"))
1251 return true;
1252
Owen Andersondebcb012009-07-29 22:17:13 +00001253 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 break;
1255 }
1256
1257 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1258 case lltok::lparen:
1259 if (ParseFunctionType(Result))
1260 return true;
1261 break;
1262 }
1263 }
1264}
1265
1266/// ParseParameterList
1267/// ::= '(' ')'
1268/// ::= '(' Arg (',' Arg)* ')'
1269/// Arg
1270/// ::= Type OptionalAttributes Value OptionalAttributes
1271bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1272 PerFunctionState &PFS) {
1273 if (ParseToken(lltok::lparen, "expected '(' in call"))
1274 return true;
1275
1276 while (Lex.getKind() != lltok::rparen) {
1277 // If this isn't the first argument, we need a comma.
1278 if (!ArgList.empty() &&
1279 ParseToken(lltok::comma, "expected ',' in argument list"))
1280 return true;
1281
1282 // Parse the argument.
1283 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001284 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 unsigned ArgAttrs1, ArgAttrs2;
1286 Value *V;
1287 if (ParseType(ArgTy, ArgLoc) ||
1288 ParseOptionalAttrs(ArgAttrs1, 0) ||
1289 ParseValue(ArgTy, V, PFS) ||
1290 // FIXME: Should not allow attributes after the argument, remove this in
1291 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001292 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 return true;
1294 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1295 }
1296
1297 Lex.Lex(); // Lex the ')'.
1298 return false;
1299}
1300
1301
1302
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001303/// ParseArgumentList - Parse the argument list for a function type or function
1304/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001305/// ::= '(' ArgTypeListI ')'
1306/// ArgTypeListI
1307/// ::= /*empty*/
1308/// ::= '...'
1309/// ::= ArgTypeList ',' '...'
1310/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001311///
Chris Lattnerdf986172009-01-02 07:01:27 +00001312bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001313 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 isVarArg = false;
1315 assert(Lex.getKind() == lltok::lparen);
1316 Lex.Lex(); // eat the (.
1317
1318 if (Lex.getKind() == lltok::rparen) {
1319 // empty
1320 } else if (Lex.getKind() == lltok::dotdotdot) {
1321 isVarArg = true;
1322 Lex.Lex();
1323 } else {
1324 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001325 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001328
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001329 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1330 // types (such as a function returning a pointer to itself). If parsing a
1331 // function prototype, we require fully resolved types.
1332 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001333 ParseOptionalAttrs(Attrs, 0)) return true;
1334
Owen Anderson1d0be152009-08-13 21:58:54 +00001335 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001336 return Error(TypeLoc, "argument can not have void type");
1337
Chris Lattnerdf986172009-01-02 07:01:27 +00001338 if (Lex.getKind() == lltok::LocalVar ||
1339 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1340 Name = Lex.getStrVal();
1341 Lex.Lex();
1342 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001343
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001344 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001345 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001346
1347 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1348
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001349 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001351 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 break;
1354 }
1355
1356 // Otherwise must be an argument type.
1357 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001358 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001359 ParseOptionalAttrs(Attrs, 0)) return true;
1360
Owen Anderson1d0be152009-08-13 21:58:54 +00001361 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001362 return Error(TypeLoc, "argument can not have void type");
1363
Chris Lattnerdf986172009-01-02 07:01:27 +00001364 if (Lex.getKind() == lltok::LocalVar ||
1365 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1366 Name = Lex.getStrVal();
1367 Lex.Lex();
1368 } else {
1369 Name = "";
1370 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001371
1372 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1373 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001374
1375 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1376 }
1377 }
1378
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001379 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001380}
1381
1382/// ParseFunctionType
1383/// ::= Type ArgumentList OptionalAttrs
1384bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1385 assert(Lex.getKind() == lltok::lparen);
1386
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001387 if (!FunctionType::isValidReturnType(Result))
1388 return TokError("invalid function return type");
1389
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 std::vector<ArgInfo> ArgList;
1391 bool isVarArg;
1392 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001393 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 // FIXME: Allow, but ignore attributes on function types!
1395 // FIXME: Remove in LLVM 3.0
1396 ParseOptionalAttrs(Attrs, 2))
1397 return true;
1398
1399 // Reject names on the arguments lists.
1400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1401 if (!ArgList[i].Name.empty())
1402 return Error(ArgList[i].Loc, "argument name invalid in function type");
1403 if (!ArgList[i].Attrs != 0) {
1404 // Allow but ignore attributes on function types; this permits
1405 // auto-upgrade.
1406 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1407 }
1408 }
1409
1410 std::vector<const Type*> ArgListTy;
1411 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1412 ArgListTy.push_back(ArgList[i].Type);
1413
Owen Andersondebcb012009-07-29 22:17:13 +00001414 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001415 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 return false;
1417}
1418
1419/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1420/// TypeRec
1421/// ::= '{' '}'
1422/// ::= '{' TypeRec (',' TypeRec)* '}'
1423/// ::= '<' '{' '}' '>'
1424/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1425bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1426 assert(Lex.getKind() == lltok::lbrace);
1427 Lex.Lex(); // Consume the '{'
1428
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001429 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001430 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001431 return false;
1432 }
1433
1434 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001435 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001436 if (ParseTypeRec(Result)) return true;
1437 ParamsList.push_back(Result);
1438
Owen Anderson1d0be152009-08-13 21:58:54 +00001439 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001440 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001441 if (!StructType::isValidElementType(Result))
1442 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001443
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001444 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001445 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001446 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001447
Owen Anderson1d0be152009-08-13 21:58:54 +00001448 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001449 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001450 if (!StructType::isValidElementType(Result))
1451 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001452
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 ParamsList.push_back(Result);
1454 }
1455
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001456 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1457 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001458
1459 std::vector<const Type*> ParamsListTy;
1460 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1461 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001462 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001463 return false;
1464}
1465
1466/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1467/// token has already been consumed.
1468/// TypeRec
1469/// ::= '[' APSINTVAL 'x' Types ']'
1470/// ::= '<' APSINTVAL 'x' Types '>'
1471bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1472 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1473 Lex.getAPSIntVal().getBitWidth() > 64)
1474 return TokError("expected number in address space");
1475
1476 LocTy SizeLoc = Lex.getLoc();
1477 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001478 Lex.Lex();
1479
1480 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1481 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001482
1483 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001484 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001485 if (ParseTypeRec(EltTy)) return true;
1486
Owen Anderson1d0be152009-08-13 21:58:54 +00001487 if (EltTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001488 return Error(TypeLoc, "array and vector element type cannot be void");
1489
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001490 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1491 "expected end of sequential type"))
1492 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001493
1494 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001495 if (Size == 0)
1496 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 if ((unsigned)Size != Size)
1498 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001499 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001501 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001502 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001503 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001505 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 }
1507 return false;
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// Function Semantic Analysis.
1512//===----------------------------------------------------------------------===//
1513
1514LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1515 : P(p), F(f) {
1516
1517 // Insert unnamed arguments into the NumberedVals list.
1518 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1519 AI != E; ++AI)
1520 if (!AI->hasName())
1521 NumberedVals.push_back(AI);
1522}
1523
1524LLParser::PerFunctionState::~PerFunctionState() {
1525 // If there were any forward referenced non-basicblock values, delete them.
1526 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1527 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1528 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001529 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001530 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 delete I->second.first;
1532 I->second.first = 0;
1533 }
1534
1535 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1536 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1537 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001538 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001539 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001540 delete I->second.first;
1541 I->second.first = 0;
1542 }
1543}
1544
1545bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1546 if (!ForwardRefVals.empty())
1547 return P.Error(ForwardRefVals.begin()->second.second,
1548 "use of undefined value '%" + ForwardRefVals.begin()->first +
1549 "'");
1550 if (!ForwardRefValIDs.empty())
1551 return P.Error(ForwardRefValIDs.begin()->second.second,
1552 "use of undefined value '%" +
1553 utostr(ForwardRefValIDs.begin()->first) + "'");
1554 return false;
1555}
1556
1557
1558/// GetVal - Get a value with the specified name or ID, creating a
1559/// forward reference record if needed. This can return null if the value
1560/// exists but does not have the right type.
1561Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1562 const Type *Ty, LocTy Loc) {
1563 // Look this name up in the normal function symbol table.
1564 Value *Val = F.getValueSymbolTable().lookup(Name);
1565
1566 // If this is a forward reference for the value, see if we already created a
1567 // forward ref record.
1568 if (Val == 0) {
1569 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1570 I = ForwardRefVals.find(Name);
1571 if (I != ForwardRefVals.end())
1572 Val = I->second.first;
1573 }
1574
1575 // If we have the value in the symbol table or fwd-ref table, return it.
1576 if (Val) {
1577 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001578 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001579 P.Error(Loc, "'%" + Name + "' is not a basic block");
1580 else
1581 P.Error(Loc, "'%" + Name + "' defined with type '" +
1582 Val->getType()->getDescription() + "'");
1583 return 0;
1584 }
1585
1586 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001587 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1588 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001589 P.Error(Loc, "invalid use of a non-first-class type");
1590 return 0;
1591 }
1592
1593 // Otherwise, create a new forward reference for this value and remember it.
1594 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001595 if (Ty == Type::getLabelTy(F.getContext()))
1596 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 else
1598 FwdVal = new Argument(Ty, Name);
1599
1600 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1601 return FwdVal;
1602}
1603
1604Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1605 LocTy Loc) {
1606 // Look this name up in the normal function symbol table.
1607 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1608
1609 // If this is a forward reference for the value, see if we already created a
1610 // forward ref record.
1611 if (Val == 0) {
1612 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1613 I = ForwardRefValIDs.find(ID);
1614 if (I != ForwardRefValIDs.end())
1615 Val = I->second.first;
1616 }
1617
1618 // If we have the value in the symbol table or fwd-ref table, return it.
1619 if (Val) {
1620 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001621 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001622 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1623 else
1624 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1625 Val->getType()->getDescription() + "'");
1626 return 0;
1627 }
1628
Owen Anderson1d0be152009-08-13 21:58:54 +00001629 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1630 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001631 P.Error(Loc, "invalid use of a non-first-class type");
1632 return 0;
1633 }
1634
1635 // Otherwise, create a new forward reference for this value and remember it.
1636 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001637 if (Ty == Type::getLabelTy(F.getContext()))
1638 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001639 else
1640 FwdVal = new Argument(Ty);
1641
1642 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1643 return FwdVal;
1644}
1645
1646/// SetInstName - After an instruction is parsed and inserted into its
1647/// basic block, this installs its name.
1648bool LLParser::PerFunctionState::SetInstName(int NameID,
1649 const std::string &NameStr,
1650 LocTy NameLoc, Instruction *Inst) {
1651 // If this instruction has void type, it cannot have a name or ID specified.
Owen Anderson1d0be152009-08-13 21:58:54 +00001652 if (Inst->getType() == Type::getVoidTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 if (NameID != -1 || !NameStr.empty())
1654 return P.Error(NameLoc, "instructions returning void cannot have a name");
1655 return false;
1656 }
1657
1658 // If this was a numbered instruction, verify that the instruction is the
1659 // expected value and resolve any forward references.
1660 if (NameStr.empty()) {
1661 // If neither a name nor an ID was specified, just use the next ID.
1662 if (NameID == -1)
1663 NameID = NumberedVals.size();
1664
1665 if (unsigned(NameID) != NumberedVals.size())
1666 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1667 utostr(NumberedVals.size()) + "'");
1668
1669 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1670 ForwardRefValIDs.find(NameID);
1671 if (FI != ForwardRefValIDs.end()) {
1672 if (FI->second.first->getType() != Inst->getType())
1673 return P.Error(NameLoc, "instruction forward referenced with type '" +
1674 FI->second.first->getType()->getDescription() + "'");
1675 FI->second.first->replaceAllUsesWith(Inst);
1676 ForwardRefValIDs.erase(FI);
1677 }
1678
1679 NumberedVals.push_back(Inst);
1680 return false;
1681 }
1682
1683 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1684 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1685 FI = ForwardRefVals.find(NameStr);
1686 if (FI != ForwardRefVals.end()) {
1687 if (FI->second.first->getType() != Inst->getType())
1688 return P.Error(NameLoc, "instruction forward referenced with type '" +
1689 FI->second.first->getType()->getDescription() + "'");
1690 FI->second.first->replaceAllUsesWith(Inst);
1691 ForwardRefVals.erase(FI);
1692 }
1693
1694 // Set the name on the instruction.
1695 Inst->setName(NameStr);
1696
1697 if (Inst->getNameStr() != NameStr)
1698 return P.Error(NameLoc, "multiple definition of local value named '" +
1699 NameStr + "'");
1700 return false;
1701}
1702
1703/// GetBB - Get a basic block with the specified name or ID, creating a
1704/// forward reference record if needed.
1705BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1706 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001707 return cast_or_null<BasicBlock>(GetVal(Name,
1708 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001709}
1710
1711BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001712 return cast_or_null<BasicBlock>(GetVal(ID,
1713 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001714}
1715
1716/// DefineBB - Define the specified basic block, which is either named or
1717/// unnamed. If there is an error, this returns null otherwise it returns
1718/// the block being defined.
1719BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1720 LocTy Loc) {
1721 BasicBlock *BB;
1722 if (Name.empty())
1723 BB = GetBB(NumberedVals.size(), Loc);
1724 else
1725 BB = GetBB(Name, Loc);
1726 if (BB == 0) return 0; // Already diagnosed error.
1727
1728 // Move the block to the end of the function. Forward ref'd blocks are
1729 // inserted wherever they happen to be referenced.
1730 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1731
1732 // Remove the block from forward ref sets.
1733 if (Name.empty()) {
1734 ForwardRefValIDs.erase(NumberedVals.size());
1735 NumberedVals.push_back(BB);
1736 } else {
1737 // BB forward references are already in the function symbol table.
1738 ForwardRefVals.erase(Name);
1739 }
1740
1741 return BB;
1742}
1743
1744//===----------------------------------------------------------------------===//
1745// Constants.
1746//===----------------------------------------------------------------------===//
1747
1748/// ParseValID - Parse an abstract value that doesn't necessarily have a
1749/// type implied. For example, if we parse "4" we don't know what integer type
1750/// it has. The value will later be combined with its type and checked for
1751/// sanity.
1752bool LLParser::ParseValID(ValID &ID) {
1753 ID.Loc = Lex.getLoc();
1754 switch (Lex.getKind()) {
1755 default: return TokError("expected value token");
1756 case lltok::GlobalID: // @42
1757 ID.UIntVal = Lex.getUIntVal();
1758 ID.Kind = ValID::t_GlobalID;
1759 break;
1760 case lltok::GlobalVar: // @foo
1761 ID.StrVal = Lex.getStrVal();
1762 ID.Kind = ValID::t_GlobalName;
1763 break;
1764 case lltok::LocalVarID: // %42
1765 ID.UIntVal = Lex.getUIntVal();
1766 ID.Kind = ValID::t_LocalID;
1767 break;
1768 case lltok::LocalVar: // %foo
1769 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1770 ID.StrVal = Lex.getStrVal();
1771 ID.Kind = ValID::t_LocalName;
1772 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001773 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001774 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001775 Lex.Lex();
1776 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001777 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001778 if (ParseMDNodeVector(Elts) ||
1779 ParseToken(lltok::rbrace, "expected end of metadata node"))
1780 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001781
Owen Anderson647e3012009-07-31 21:35:40 +00001782 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001783 return false;
1784 }
1785
Devang Patel923078c2009-07-01 19:21:12 +00001786 // Standalone metadata reference
1787 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001788 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001789 return false;
Devang Patel256be962009-07-20 19:00:08 +00001790
Nick Lewycky21cc4462009-04-04 07:22:01 +00001791 // MDString:
1792 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001793 if (ParseMDString(ID.MetadataVal)) return true;
1794 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001795 return false;
1796 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 case lltok::APSInt:
1798 ID.APSIntVal = Lex.getAPSIntVal();
1799 ID.Kind = ValID::t_APSInt;
1800 break;
1801 case lltok::APFloat:
1802 ID.APFloatVal = Lex.getAPFloatVal();
1803 ID.Kind = ValID::t_APFloat;
1804 break;
1805 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001806 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001807 ID.Kind = ValID::t_Constant;
1808 break;
1809 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001810 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 ID.Kind = ValID::t_Constant;
1812 break;
1813 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1814 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1815 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1816
1817 case lltok::lbrace: {
1818 // ValID ::= '{' ConstVector '}'
1819 Lex.Lex();
1820 SmallVector<Constant*, 16> Elts;
1821 if (ParseGlobalValueVector(Elts) ||
1822 ParseToken(lltok::rbrace, "expected end of struct constant"))
1823 return true;
1824
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001825 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1826 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 ID.Kind = ValID::t_Constant;
1828 return false;
1829 }
1830 case lltok::less: {
1831 // ValID ::= '<' ConstVector '>' --> Vector.
1832 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1833 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001834 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001835
1836 SmallVector<Constant*, 16> Elts;
1837 LocTy FirstEltLoc = Lex.getLoc();
1838 if (ParseGlobalValueVector(Elts) ||
1839 (isPackedStruct &&
1840 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1841 ParseToken(lltok::greater, "expected end of constant"))
1842 return true;
1843
1844 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001845 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001846 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 ID.Kind = ValID::t_Constant;
1848 return false;
1849 }
1850
1851 if (Elts.empty())
1852 return Error(ID.Loc, "constant vector must not be empty");
1853
1854 if (!Elts[0]->getType()->isInteger() &&
1855 !Elts[0]->getType()->isFloatingPoint())
1856 return Error(FirstEltLoc,
1857 "vector elements must have integer or floating point type");
1858
1859 // Verify that all the vector elements have the same type.
1860 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1861 if (Elts[i]->getType() != Elts[0]->getType())
1862 return Error(FirstEltLoc,
1863 "vector element #" + utostr(i) +
1864 " is not of type '" + Elts[0]->getType()->getDescription());
1865
Owen Andersonaf7ec972009-07-28 21:19:26 +00001866 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 ID.Kind = ValID::t_Constant;
1868 return false;
1869 }
1870 case lltok::lsquare: { // Array Constant
1871 Lex.Lex();
1872 SmallVector<Constant*, 16> Elts;
1873 LocTy FirstEltLoc = Lex.getLoc();
1874 if (ParseGlobalValueVector(Elts) ||
1875 ParseToken(lltok::rsquare, "expected end of array constant"))
1876 return true;
1877
1878 // Handle empty element.
1879 if (Elts.empty()) {
1880 // Use undef instead of an array because it's inconvenient to determine
1881 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001882 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 return false;
1884 }
1885
1886 if (!Elts[0]->getType()->isFirstClassType())
1887 return Error(FirstEltLoc, "invalid array element type: " +
1888 Elts[0]->getType()->getDescription());
1889
Owen Andersondebcb012009-07-29 22:17:13 +00001890 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001891
1892 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001893 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 if (Elts[i]->getType() != Elts[0]->getType())
1895 return Error(FirstEltLoc,
1896 "array element #" + utostr(i) +
1897 " is not of type '" +Elts[0]->getType()->getDescription());
1898 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001899
Owen Anderson1fd70962009-07-28 18:32:17 +00001900 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 ID.Kind = ValID::t_Constant;
1902 return false;
1903 }
1904 case lltok::kw_c: // c "foo"
1905 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001906 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001907 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1908 ID.Kind = ValID::t_Constant;
1909 return false;
1910
1911 case lltok::kw_asm: {
1912 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1913 bool HasSideEffect;
1914 Lex.Lex();
1915 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001916 ParseStringConstant(ID.StrVal) ||
1917 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001918 ParseToken(lltok::StringConstant, "expected constraint string"))
1919 return true;
1920 ID.StrVal2 = Lex.getStrVal();
1921 ID.UIntVal = HasSideEffect;
1922 ID.Kind = ValID::t_InlineAsm;
1923 return false;
1924 }
1925
1926 case lltok::kw_trunc:
1927 case lltok::kw_zext:
1928 case lltok::kw_sext:
1929 case lltok::kw_fptrunc:
1930 case lltok::kw_fpext:
1931 case lltok::kw_bitcast:
1932 case lltok::kw_uitofp:
1933 case lltok::kw_sitofp:
1934 case lltok::kw_fptoui:
1935 case lltok::kw_fptosi:
1936 case lltok::kw_inttoptr:
1937 case lltok::kw_ptrtoint: {
1938 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00001939 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001940 Constant *SrcVal;
1941 Lex.Lex();
1942 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1943 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001944 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001945 ParseType(DestTy) ||
1946 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1947 return true;
1948 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1949 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1950 SrcVal->getType()->getDescription() + "' to '" +
1951 DestTy->getDescription() + "'");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001952 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00001953 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001954 ID.Kind = ValID::t_Constant;
1955 return false;
1956 }
1957 case lltok::kw_extractvalue: {
1958 Lex.Lex();
1959 Constant *Val;
1960 SmallVector<unsigned, 4> Indices;
1961 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1962 ParseGlobalTypeAndValue(Val) ||
1963 ParseIndexList(Indices) ||
1964 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1965 return true;
1966 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1967 return Error(ID.Loc, "extractvalue operand must be array or struct");
1968 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1969 Indices.end()))
1970 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001971 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001972 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 ID.Kind = ValID::t_Constant;
1974 return false;
1975 }
1976 case lltok::kw_insertvalue: {
1977 Lex.Lex();
1978 Constant *Val0, *Val1;
1979 SmallVector<unsigned, 4> Indices;
1980 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1981 ParseGlobalTypeAndValue(Val0) ||
1982 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1983 ParseGlobalTypeAndValue(Val1) ||
1984 ParseIndexList(Indices) ||
1985 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1986 return true;
1987 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1988 return Error(ID.Loc, "extractvalue operand must be array or struct");
1989 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1990 Indices.end()))
1991 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001992 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00001993 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001994 ID.Kind = ValID::t_Constant;
1995 return false;
1996 }
1997 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001998 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 unsigned PredVal, Opc = Lex.getUIntVal();
2000 Constant *Val0, *Val1;
2001 Lex.Lex();
2002 if (ParseCmpPredicate(PredVal, Opc) ||
2003 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2004 ParseGlobalTypeAndValue(Val0) ||
2005 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2006 ParseGlobalTypeAndValue(Val1) ||
2007 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2008 return true;
2009
2010 if (Val0->getType() != Val1->getType())
2011 return Error(ID.Loc, "compare operands must have the same type");
2012
2013 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2014
2015 if (Opc == Instruction::FCmp) {
2016 if (!Val0->getType()->isFPOrFPVector())
2017 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002018 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002019 } else {
2020 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002021 if (!Val0->getType()->isIntOrIntVector() &&
2022 !isa<PointerType>(Val0->getType()))
2023 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002024 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002025 }
2026 ID.Kind = ValID::t_Constant;
2027 return false;
2028 }
2029
2030 // Binary Operators.
2031 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002032 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002033 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002034 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002036 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 case lltok::kw_udiv:
2038 case lltok::kw_sdiv:
2039 case lltok::kw_fdiv:
2040 case lltok::kw_urem:
2041 case lltok::kw_srem:
2042 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002043 bool NUW = false;
2044 bool NSW = false;
2045 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002046 unsigned Opc = Lex.getUIntVal();
2047 Constant *Val0, *Val1;
2048 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002049 LocTy ModifierLoc = Lex.getLoc();
2050 if (Opc == Instruction::Add ||
2051 Opc == Instruction::Sub ||
2052 Opc == Instruction::Mul) {
2053 if (EatIfPresent(lltok::kw_nuw))
2054 NUW = true;
2055 if (EatIfPresent(lltok::kw_nsw)) {
2056 NSW = true;
2057 if (EatIfPresent(lltok::kw_nuw))
2058 NUW = true;
2059 }
2060 } else if (Opc == Instruction::SDiv) {
2061 if (EatIfPresent(lltok::kw_exact))
2062 Exact = true;
2063 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2065 ParseGlobalTypeAndValue(Val0) ||
2066 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2067 ParseGlobalTypeAndValue(Val1) ||
2068 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2069 return true;
2070 if (Val0->getType() != Val1->getType())
2071 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002072 if (!Val0->getType()->isIntOrIntVector()) {
2073 if (NUW)
2074 return Error(ModifierLoc, "nuw only applies to integer operations");
2075 if (NSW)
2076 return Error(ModifierLoc, "nsw only applies to integer operations");
2077 }
2078 // API compatibility: Accept either integer or floating-point types with
2079 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002080 if (!Val0->getType()->isIntOrIntVector() &&
2081 !Val0->getType()->isFPOrFPVector())
2082 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002083 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
Dan Gohman59858cf2009-07-27 16:11:46 +00002084 if (NUW)
2085 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2086 if (NSW)
2087 cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2088 if (Exact)
2089 cast<SDivOperator>(C)->setIsExact(true);
2090 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ID.Kind = ValID::t_Constant;
2092 return false;
2093 }
2094
2095 // Logical Operations
2096 case lltok::kw_shl:
2097 case lltok::kw_lshr:
2098 case lltok::kw_ashr:
2099 case lltok::kw_and:
2100 case lltok::kw_or:
2101 case lltok::kw_xor: {
2102 unsigned Opc = Lex.getUIntVal();
2103 Constant *Val0, *Val1;
2104 Lex.Lex();
2105 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2106 ParseGlobalTypeAndValue(Val0) ||
2107 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2108 ParseGlobalTypeAndValue(Val1) ||
2109 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2110 return true;
2111 if (Val0->getType() != Val1->getType())
2112 return Error(ID.Loc, "operands of constexpr must have same type");
2113 if (!Val0->getType()->isIntOrIntVector())
2114 return Error(ID.Loc,
2115 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002116 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 ID.Kind = ValID::t_Constant;
2118 return false;
2119 }
2120
2121 case lltok::kw_getelementptr:
2122 case lltok::kw_shufflevector:
2123 case lltok::kw_insertelement:
2124 case lltok::kw_extractelement:
2125 case lltok::kw_select: {
2126 unsigned Opc = Lex.getUIntVal();
2127 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002128 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002129 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002130 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002131 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002132 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2133 ParseGlobalValueVector(Elts) ||
2134 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2135 return true;
2136
2137 if (Opc == Instruction::GetElementPtr) {
2138 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2139 return Error(ID.Loc, "getelementptr requires pointer operand");
2140
2141 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002142 (Value**)(Elts.data() + 1),
2143 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002145 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
Eli Friedman4e9bac32009-07-24 21:56:17 +00002146 Elts.data() + 1, Elts.size() - 1);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002147 if (InBounds)
2148 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002149 } else if (Opc == Instruction::Select) {
2150 if (Elts.size() != 3)
2151 return Error(ID.Loc, "expected three operands to select");
2152 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2153 Elts[2]))
2154 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002155 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 } else if (Opc == Instruction::ShuffleVector) {
2157 if (Elts.size() != 3)
2158 return Error(ID.Loc, "expected three operands to shufflevector");
2159 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2160 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002161 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002162 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002163 } else if (Opc == Instruction::ExtractElement) {
2164 if (Elts.size() != 2)
2165 return Error(ID.Loc, "expected two operands to extractelement");
2166 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2167 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002168 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 } else {
2170 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2171 if (Elts.size() != 3)
2172 return Error(ID.Loc, "expected three operands to insertelement");
2173 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2174 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002175 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002176 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 }
2178
2179 ID.Kind = ValID::t_Constant;
2180 return false;
2181 }
2182 }
2183
2184 Lex.Lex();
2185 return false;
2186}
2187
2188/// ParseGlobalValue - Parse a global value with the specified type.
2189bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2190 V = 0;
2191 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002192 return ParseValID(ID) ||
2193 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002194}
2195
2196/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2197/// constant.
2198bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2199 Constant *&V) {
2200 if (isa<FunctionType>(Ty))
2201 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2202
2203 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002204 default: llvm_unreachable("Unknown ValID!");
2205 case ValID::t_Metadata:
2206 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 case ValID::t_LocalID:
2208 case ValID::t_LocalName:
2209 return Error(ID.Loc, "invalid use of function-local name");
2210 case ValID::t_InlineAsm:
2211 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2212 case ValID::t_GlobalName:
2213 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2214 return V == 0;
2215 case ValID::t_GlobalID:
2216 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2217 return V == 0;
2218 case ValID::t_APSInt:
2219 if (!isa<IntegerType>(Ty))
2220 return Error(ID.Loc, "integer constant must have integer type");
2221 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002222 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 return false;
2224 case ValID::t_APFloat:
2225 if (!Ty->isFloatingPoint() ||
2226 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2227 return Error(ID.Loc, "floating point constant invalid for type");
2228
2229 // The lexer has no type info, so builds all float and double FP constants
2230 // as double. Fix this here. Long double does not need this.
2231 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002232 Ty == Type::getFloatTy(Context)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002233 bool Ignored;
2234 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2235 &Ignored);
2236 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002237 V = ConstantFP::get(Context, ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002238
2239 if (V->getType() != Ty)
2240 return Error(ID.Loc, "floating point constant does not have type '" +
2241 Ty->getDescription() + "'");
2242
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 return false;
2244 case ValID::t_Null:
2245 if (!isa<PointerType>(Ty))
2246 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002247 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 return false;
2249 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002250 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002251 if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002252 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002253 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002254 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002256 case ValID::t_EmptyArray:
2257 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2258 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002259 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002260 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002262 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002263 if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002264 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002265 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002266 return false;
2267 case ValID::t_Constant:
2268 if (ID.ConstantVal->getType() != Ty)
2269 return Error(ID.Loc, "constant expression type mismatch");
2270 V = ID.ConstantVal;
2271 return false;
2272 }
2273}
2274
2275bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002276 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002277 return ParseType(Type) ||
2278 ParseGlobalValue(Type, V);
2279}
2280
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002281/// ParseGlobalValueVector
2282/// ::= /*empty*/
2283/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002284bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2285 // Empty list.
2286 if (Lex.getKind() == lltok::rbrace ||
2287 Lex.getKind() == lltok::rsquare ||
2288 Lex.getKind() == lltok::greater ||
2289 Lex.getKind() == lltok::rparen)
2290 return false;
2291
2292 Constant *C;
2293 if (ParseGlobalTypeAndValue(C)) return true;
2294 Elts.push_back(C);
2295
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002296 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002297 if (ParseGlobalTypeAndValue(C)) return true;
2298 Elts.push_back(C);
2299 }
2300
2301 return false;
2302}
2303
2304
2305//===----------------------------------------------------------------------===//
2306// Function Parsing.
2307//===----------------------------------------------------------------------===//
2308
2309bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2310 PerFunctionState &PFS) {
2311 if (ID.Kind == ValID::t_LocalID)
2312 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2313 else if (ID.Kind == ValID::t_LocalName)
2314 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002315 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2317 const FunctionType *FTy =
2318 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2319 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2320 return Error(ID.Loc, "invalid type for inline asm constraint string");
2321 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2322 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002323 } else if (ID.Kind == ValID::t_Metadata) {
2324 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002325 } else {
2326 Constant *C;
2327 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2328 V = C;
2329 return false;
2330 }
2331
2332 return V == 0;
2333}
2334
2335bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2336 V = 0;
2337 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002338 return ParseValID(ID) ||
2339 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002340}
2341
2342bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002343 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002344 return ParseType(T) ||
2345 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002346}
2347
2348/// FunctionHeader
2349/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2350/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2351/// OptionalAlign OptGC
2352bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2353 // Parse the linkage.
2354 LocTy LinkageLoc = Lex.getLoc();
2355 unsigned Linkage;
2356
2357 unsigned Visibility, CC, RetAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002358 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 LocTy RetTypeLoc = Lex.getLoc();
2360 if (ParseOptionalLinkage(Linkage) ||
2361 ParseOptionalVisibility(Visibility) ||
2362 ParseOptionalCallingConv(CC) ||
2363 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002364 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 return true;
2366
2367 // Verify that the linkage is ok.
2368 switch ((GlobalValue::LinkageTypes)Linkage) {
2369 case GlobalValue::ExternalLinkage:
2370 break; // always ok.
2371 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002372 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 if (isDefine)
2374 return Error(LinkageLoc, "invalid linkage for function definition");
2375 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002376 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002377 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002378 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002379 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002380 case GlobalValue::LinkOnceAnyLinkage:
2381 case GlobalValue::LinkOnceODRLinkage:
2382 case GlobalValue::WeakAnyLinkage:
2383 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 case GlobalValue::DLLExportLinkage:
2385 if (!isDefine)
2386 return Error(LinkageLoc, "invalid linkage for function declaration");
2387 break;
2388 case GlobalValue::AppendingLinkage:
2389 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002390 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 return Error(LinkageLoc, "invalid function linkage type");
2392 }
2393
Chris Lattner99bb3152009-01-05 08:00:30 +00002394 if (!FunctionType::isValidReturnType(RetType) ||
2395 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 return Error(RetTypeLoc, "invalid function return type");
2397
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002399
2400 std::string FunctionName;
2401 if (Lex.getKind() == lltok::GlobalVar) {
2402 FunctionName = Lex.getStrVal();
2403 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2404 unsigned NameID = Lex.getUIntVal();
2405
2406 if (NameID != NumberedVals.size())
2407 return TokError("function expected to be numbered '%" +
2408 utostr(NumberedVals.size()) + "'");
2409 } else {
2410 return TokError("expected function name");
2411 }
2412
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002413 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002414
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002415 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 return TokError("expected '(' in function argument list");
2417
2418 std::vector<ArgInfo> ArgList;
2419 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002420 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002421 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002423 std::string GC;
2424
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002425 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002426 ParseOptionalAttrs(FuncAttrs, 2) ||
2427 (EatIfPresent(lltok::kw_section) &&
2428 ParseStringConstant(Section)) ||
2429 ParseOptionalAlignment(Alignment) ||
2430 (EatIfPresent(lltok::kw_gc) &&
2431 ParseStringConstant(GC)))
2432 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002433
2434 // If the alignment was parsed as an attribute, move to the alignment field.
2435 if (FuncAttrs & Attribute::Alignment) {
2436 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2437 FuncAttrs &= ~Attribute::Alignment;
2438 }
2439
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 // Okay, if we got here, the function is syntactically valid. Convert types
2441 // and do semantic checks.
2442 std::vector<const Type*> ParamTypeList;
2443 SmallVector<AttributeWithIndex, 8> Attrs;
2444 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2445 // attributes.
2446 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2447 if (FuncAttrs & ObsoleteFuncAttrs) {
2448 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2449 FuncAttrs &= ~ObsoleteFuncAttrs;
2450 }
2451
2452 if (RetAttrs != Attribute::None)
2453 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2454
2455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2456 ParamTypeList.push_back(ArgList[i].Type);
2457 if (ArgList[i].Attrs != Attribute::None)
2458 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2459 }
2460
2461 if (FuncAttrs != Attribute::None)
2462 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2463
2464 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2465
Chris Lattnera9a9e072009-03-09 04:49:14 +00002466 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002467 RetType != Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00002468 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2469
Owen Andersonfba933c2009-07-01 23:57:11 +00002470 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002471 FunctionType::get(RetType, ParamTypeList, isVarArg);
2472 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002473
2474 Fn = 0;
2475 if (!FunctionName.empty()) {
2476 // If this was a definition of a forward reference, remove the definition
2477 // from the forward reference table and fill in the forward ref.
2478 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2479 ForwardRefVals.find(FunctionName);
2480 if (FRVI != ForwardRefVals.end()) {
2481 Fn = M->getFunction(FunctionName);
2482 ForwardRefVals.erase(FRVI);
2483 } else if ((Fn = M->getFunction(FunctionName))) {
2484 // If this function already exists in the symbol table, then it is
2485 // multiply defined. We accept a few cases for old backwards compat.
2486 // FIXME: Remove this stuff for LLVM 3.0.
2487 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2488 (!Fn->isDeclaration() && isDefine)) {
2489 // If the redefinition has different type or different attributes,
2490 // reject it. If both have bodies, reject it.
2491 return Error(NameLoc, "invalid redefinition of function '" +
2492 FunctionName + "'");
2493 } else if (Fn->isDeclaration()) {
2494 // Make sure to strip off any argument names so we can't get conflicts.
2495 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2496 AI != AE; ++AI)
2497 AI->setName("");
2498 }
2499 }
2500
2501 } else if (FunctionName.empty()) {
2502 // If this is a definition of a forward referenced function, make sure the
2503 // types agree.
2504 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2505 = ForwardRefValIDs.find(NumberedVals.size());
2506 if (I != ForwardRefValIDs.end()) {
2507 Fn = cast<Function>(I->second.first);
2508 if (Fn->getType() != PFT)
2509 return Error(NameLoc, "type of definition and forward reference of '@" +
2510 utostr(NumberedVals.size()) +"' disagree");
2511 ForwardRefValIDs.erase(I);
2512 }
2513 }
2514
2515 if (Fn == 0)
2516 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2517 else // Move the forward-reference to the correct spot in the module.
2518 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2519
2520 if (FunctionName.empty())
2521 NumberedVals.push_back(Fn);
2522
2523 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2524 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2525 Fn->setCallingConv(CC);
2526 Fn->setAttributes(PAL);
2527 Fn->setAlignment(Alignment);
2528 Fn->setSection(Section);
2529 if (!GC.empty()) Fn->setGC(GC.c_str());
2530
2531 // Add all of the arguments we parsed to the function.
2532 Function::arg_iterator ArgIt = Fn->arg_begin();
2533 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2534 // If the argument has a name, insert it into the argument symbol table.
2535 if (ArgList[i].Name.empty()) continue;
2536
2537 // Set the name, if it conflicted, it will be auto-renamed.
2538 ArgIt->setName(ArgList[i].Name);
2539
2540 if (ArgIt->getNameStr() != ArgList[i].Name)
2541 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2542 ArgList[i].Name + "'");
2543 }
2544
2545 return false;
2546}
2547
2548
2549/// ParseFunctionBody
2550/// ::= '{' BasicBlock+ '}'
2551/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2552///
2553bool LLParser::ParseFunctionBody(Function &Fn) {
2554 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2555 return TokError("expected '{' in function body");
2556 Lex.Lex(); // eat the {.
2557
2558 PerFunctionState PFS(*this, Fn);
2559
2560 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2561 if (ParseBasicBlock(PFS)) return true;
2562
2563 // Eat the }.
2564 Lex.Lex();
2565
2566 // Verify function is ok.
2567 return PFS.VerifyFunctionComplete();
2568}
2569
2570/// ParseBasicBlock
2571/// ::= LabelStr? Instruction*
2572bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2573 // If this basic block starts out with a name, remember it.
2574 std::string Name;
2575 LocTy NameLoc = Lex.getLoc();
2576 if (Lex.getKind() == lltok::LabelStr) {
2577 Name = Lex.getStrVal();
2578 Lex.Lex();
2579 }
2580
2581 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2582 if (BB == 0) return true;
2583
2584 std::string NameStr;
2585
2586 // Parse the instructions in this block until we get a terminator.
2587 Instruction *Inst;
2588 do {
2589 // This instruction may have three possibilities for a name: a) none
2590 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2591 LocTy NameLoc = Lex.getLoc();
2592 int NameID = -1;
2593 NameStr = "";
2594
2595 if (Lex.getKind() == lltok::LocalVarID) {
2596 NameID = Lex.getUIntVal();
2597 Lex.Lex();
2598 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2599 return true;
2600 } else if (Lex.getKind() == lltok::LocalVar ||
2601 // FIXME: REMOVE IN LLVM 3.0
2602 Lex.getKind() == lltok::StringConstant) {
2603 NameStr = Lex.getStrVal();
2604 Lex.Lex();
2605 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2606 return true;
2607 }
2608
2609 if (ParseInstruction(Inst, BB, PFS)) return true;
2610
2611 BB->getInstList().push_back(Inst);
2612
2613 // Set the name on the instruction.
2614 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2615 } while (!isa<TerminatorInst>(Inst));
2616
2617 return false;
2618}
2619
2620//===----------------------------------------------------------------------===//
2621// Instruction Parsing.
2622//===----------------------------------------------------------------------===//
2623
2624/// ParseInstruction - Parse one of the many different instructions.
2625///
2626bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2627 PerFunctionState &PFS) {
2628 lltok::Kind Token = Lex.getKind();
2629 if (Token == lltok::Eof)
2630 return TokError("found end of file when expecting more instructions");
2631 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002632 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 Lex.Lex(); // Eat the keyword.
2634
2635 switch (Token) {
2636 default: return Error(Loc, "expected instruction opcode");
2637 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002638 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2639 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2641 case lltok::kw_br: return ParseBr(Inst, PFS);
2642 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2643 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2644 // Binary Operators.
2645 case lltok::kw_add:
2646 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002647 case lltok::kw_mul: {
2648 bool NUW = false;
2649 bool NSW = false;
2650 LocTy ModifierLoc = Lex.getLoc();
2651 if (EatIfPresent(lltok::kw_nuw))
2652 NUW = true;
2653 if (EatIfPresent(lltok::kw_nsw)) {
2654 NSW = true;
2655 if (EatIfPresent(lltok::kw_nuw))
2656 NUW = true;
2657 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002658 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002659 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2660 if (!Result) {
2661 if (!Inst->getType()->isIntOrIntVector()) {
2662 if (NUW)
2663 return Error(ModifierLoc, "nuw only applies to integer operations");
2664 if (NSW)
2665 return Error(ModifierLoc, "nsw only applies to integer operations");
2666 }
2667 if (NUW)
2668 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2669 if (NSW)
2670 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2671 }
2672 return Result;
2673 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002674 case lltok::kw_fadd:
2675 case lltok::kw_fsub:
2676 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2677
Dan Gohman59858cf2009-07-27 16:11:46 +00002678 case lltok::kw_sdiv: {
2679 bool Exact = false;
2680 if (EatIfPresent(lltok::kw_exact))
2681 Exact = true;
2682 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2683 if (!Result)
2684 if (Exact)
2685 cast<SDivOperator>(Inst)->setIsExact(true);
2686 return Result;
2687 }
2688
Chris Lattnerdf986172009-01-02 07:01:27 +00002689 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002691 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002692 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002693 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 case lltok::kw_shl:
2695 case lltok::kw_lshr:
2696 case lltok::kw_ashr:
2697 case lltok::kw_and:
2698 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002699 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002701 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002702 // Casts.
2703 case lltok::kw_trunc:
2704 case lltok::kw_zext:
2705 case lltok::kw_sext:
2706 case lltok::kw_fptrunc:
2707 case lltok::kw_fpext:
2708 case lltok::kw_bitcast:
2709 case lltok::kw_uitofp:
2710 case lltok::kw_sitofp:
2711 case lltok::kw_fptoui:
2712 case lltok::kw_fptosi:
2713 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002714 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 // Other.
2716 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002717 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2719 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2720 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2721 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2722 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2723 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2724 // Memory.
2725 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002726 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 case lltok::kw_free: return ParseFree(Inst, PFS);
2728 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2729 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2730 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002731 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002732 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002733 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002735 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002736 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002737 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2738 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2739 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2740 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2741 }
2742}
2743
2744/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2745bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002746 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 switch (Lex.getKind()) {
2748 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2749 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2750 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2751 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2752 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2753 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2754 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2755 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2756 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2757 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2758 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2759 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2760 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2761 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2762 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2763 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2764 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2765 }
2766 } else {
2767 switch (Lex.getKind()) {
2768 default: TokError("expected icmp predicate (e.g. 'eq')");
2769 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2770 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2771 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2772 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2773 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2774 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2775 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2776 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2777 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2778 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2779 }
2780 }
2781 Lex.Lex();
2782 return false;
2783}
2784
2785//===----------------------------------------------------------------------===//
2786// Terminator Instructions.
2787//===----------------------------------------------------------------------===//
2788
2789/// ParseRet - Parse a return instruction.
2790/// ::= 'ret' void
2791/// ::= 'ret' TypeAndValue
2792/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2793bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2794 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002795 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002796 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002797
Owen Anderson1d0be152009-08-13 21:58:54 +00002798 if (Ty == Type::getVoidTy(Context)) {
2799 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002800 return false;
2801 }
2802
2803 Value *RV;
2804 if (ParseValue(Ty, RV, PFS)) return true;
2805
2806 // The normal case is one return value.
2807 if (Lex.getKind() == lltok::comma) {
2808 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2809 // of 'ret {i32,i32} {i32 1, i32 2}'
2810 SmallVector<Value*, 8> RVs;
2811 RVs.push_back(RV);
2812
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002813 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002814 if (ParseTypeAndValue(RV, PFS)) return true;
2815 RVs.push_back(RV);
2816 }
2817
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002818 RV = UndefValue::get(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2820 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2821 BB->getInstList().push_back(I);
2822 RV = I;
2823 }
2824 }
Owen Anderson1d0be152009-08-13 21:58:54 +00002825 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 return false;
2827}
2828
2829
2830/// ParseBr
2831/// ::= 'br' TypeAndValue
2832/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2833bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2834 LocTy Loc, Loc2;
2835 Value *Op0, *Op1, *Op2;
2836 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2837
2838 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2839 Inst = BranchInst::Create(BB);
2840 return false;
2841 }
2842
Owen Anderson1d0be152009-08-13 21:58:54 +00002843 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002844 return Error(Loc, "branch condition must have 'i1' type");
2845
2846 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2847 ParseTypeAndValue(Op1, Loc, PFS) ||
2848 ParseToken(lltok::comma, "expected ',' after true destination") ||
2849 ParseTypeAndValue(Op2, Loc2, PFS))
2850 return true;
2851
2852 if (!isa<BasicBlock>(Op1))
2853 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 if (!isa<BasicBlock>(Op2))
2855 return Error(Loc2, "true destination of branch must be a basic block");
2856
2857 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2858 return false;
2859}
2860
2861/// ParseSwitch
2862/// Instruction
2863/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2864/// JumpTable
2865/// ::= (TypeAndValue ',' TypeAndValue)*
2866bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2867 LocTy CondLoc, BBLoc;
2868 Value *Cond, *DefaultBB;
2869 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2870 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2871 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2872 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2873 return true;
2874
2875 if (!isa<IntegerType>(Cond->getType()))
2876 return Error(CondLoc, "switch condition must have integer type");
2877 if (!isa<BasicBlock>(DefaultBB))
2878 return Error(BBLoc, "default destination must be a basic block");
2879
2880 // Parse the jump table pairs.
2881 SmallPtrSet<Value*, 32> SeenCases;
2882 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2883 while (Lex.getKind() != lltok::rsquare) {
2884 Value *Constant, *DestBB;
2885
2886 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2887 ParseToken(lltok::comma, "expected ',' after case value") ||
2888 ParseTypeAndValue(DestBB, BBLoc, PFS))
2889 return true;
2890
2891 if (!SeenCases.insert(Constant))
2892 return Error(CondLoc, "duplicate case value in switch");
2893 if (!isa<ConstantInt>(Constant))
2894 return Error(CondLoc, "case value is not a constant integer");
2895 if (!isa<BasicBlock>(DestBB))
2896 return Error(BBLoc, "case destination is not a basic block");
2897
2898 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2899 cast<BasicBlock>(DestBB)));
2900 }
2901
2902 Lex.Lex(); // Eat the ']'.
2903
2904 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2905 Table.size());
2906 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2907 SI->addCase(Table[i].first, Table[i].second);
2908 Inst = SI;
2909 return false;
2910}
2911
2912/// ParseInvoke
2913/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2914/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2915bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2916 LocTy CallLoc = Lex.getLoc();
2917 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002918 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 LocTy RetTypeLoc;
2920 ValID CalleeID;
2921 SmallVector<ParamInfo, 16> ArgList;
2922
2923 Value *NormalBB, *UnwindBB;
2924 if (ParseOptionalCallingConv(CC) ||
2925 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002926 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 ParseValID(CalleeID) ||
2928 ParseParameterList(ArgList, PFS) ||
2929 ParseOptionalAttrs(FnAttrs, 2) ||
2930 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2931 ParseTypeAndValue(NormalBB, PFS) ||
2932 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2933 ParseTypeAndValue(UnwindBB, PFS))
2934 return true;
2935
2936 if (!isa<BasicBlock>(NormalBB))
2937 return Error(CallLoc, "normal destination is not a basic block");
2938 if (!isa<BasicBlock>(UnwindBB))
2939 return Error(CallLoc, "unwind destination is not a basic block");
2940
2941 // If RetType is a non-function pointer type, then this is the short syntax
2942 // for the call, which means that RetType is just the return type. Infer the
2943 // rest of the function argument types from the arguments that are present.
2944 const PointerType *PFTy = 0;
2945 const FunctionType *Ty = 0;
2946 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2947 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2948 // Pull out the types of all of the arguments...
2949 std::vector<const Type*> ParamTypes;
2950 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2951 ParamTypes.push_back(ArgList[i].V->getType());
2952
2953 if (!FunctionType::isValidReturnType(RetType))
2954 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2955
Owen Andersondebcb012009-07-29 22:17:13 +00002956 Ty = FunctionType::get(RetType, ParamTypes, false);
2957 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 }
2959
2960 // Look up the callee.
2961 Value *Callee;
2962 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2963
2964 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2965 // function attributes.
2966 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2967 if (FnAttrs & ObsoleteFuncAttrs) {
2968 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2969 FnAttrs &= ~ObsoleteFuncAttrs;
2970 }
2971
2972 // Set up the Attributes for the function.
2973 SmallVector<AttributeWithIndex, 8> Attrs;
2974 if (RetAttrs != Attribute::None)
2975 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2976
2977 SmallVector<Value*, 8> Args;
2978
2979 // Loop through FunctionType's arguments and ensure they are specified
2980 // correctly. Also, gather any parameter attributes.
2981 FunctionType::param_iterator I = Ty->param_begin();
2982 FunctionType::param_iterator E = Ty->param_end();
2983 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2984 const Type *ExpectedTy = 0;
2985 if (I != E) {
2986 ExpectedTy = *I++;
2987 } else if (!Ty->isVarArg()) {
2988 return Error(ArgList[i].Loc, "too many arguments specified");
2989 }
2990
2991 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2992 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2993 ExpectedTy->getDescription() + "'");
2994 Args.push_back(ArgList[i].V);
2995 if (ArgList[i].Attrs != Attribute::None)
2996 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2997 }
2998
2999 if (I != E)
3000 return Error(CallLoc, "not enough parameters specified for call");
3001
3002 if (FnAttrs != Attribute::None)
3003 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3004
3005 // Finish off the Attributes and check them
3006 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3007
3008 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3009 cast<BasicBlock>(UnwindBB),
3010 Args.begin(), Args.end());
3011 II->setCallingConv(CC);
3012 II->setAttributes(PAL);
3013 Inst = II;
3014 return false;
3015}
3016
3017
3018
3019//===----------------------------------------------------------------------===//
3020// Binary Operators.
3021//===----------------------------------------------------------------------===//
3022
3023/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003024/// ::= ArithmeticOps TypeAndValue ',' Value
3025///
3026/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3027/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003028bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003029 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 LocTy Loc; Value *LHS, *RHS;
3031 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3032 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3033 ParseValue(LHS->getType(), RHS, PFS))
3034 return true;
3035
Chris Lattnere914b592009-01-05 08:24:46 +00003036 bool Valid;
3037 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003038 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003039 case 0: // int or FP.
3040 Valid = LHS->getType()->isIntOrIntVector() ||
3041 LHS->getType()->isFPOrFPVector();
3042 break;
3043 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3044 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3045 }
3046
3047 if (!Valid)
3048 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00003049
3050 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3051 return false;
3052}
3053
3054/// ParseLogical
3055/// ::= ArithmeticOps TypeAndValue ',' Value {
3056bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3057 unsigned Opc) {
3058 LocTy Loc; Value *LHS, *RHS;
3059 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3060 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3061 ParseValue(LHS->getType(), RHS, PFS))
3062 return true;
3063
3064 if (!LHS->getType()->isIntOrIntVector())
3065 return Error(Loc,"instruction requires integer or integer vector operands");
3066
3067 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3068 return false;
3069}
3070
3071
3072/// ParseCompare
3073/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3074/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003075bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3076 unsigned Opc) {
3077 // Parse the integer/fp comparison predicate.
3078 LocTy Loc;
3079 unsigned Pred;
3080 Value *LHS, *RHS;
3081 if (ParseCmpPredicate(Pred, Opc) ||
3082 ParseTypeAndValue(LHS, Loc, PFS) ||
3083 ParseToken(lltok::comma, "expected ',' after compare value") ||
3084 ParseValue(LHS->getType(), RHS, PFS))
3085 return true;
3086
3087 if (Opc == Instruction::FCmp) {
3088 if (!LHS->getType()->isFPOrFPVector())
3089 return Error(Loc, "fcmp requires floating point operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003090 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003091 } else {
3092 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 if (!LHS->getType()->isIntOrIntVector() &&
3094 !isa<PointerType>(LHS->getType()))
3095 return Error(Loc, "icmp requires integer operands");
Owen Anderson333c4002009-07-09 23:48:35 +00003096 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 }
3098 return false;
3099}
3100
3101//===----------------------------------------------------------------------===//
3102// Other Instructions.
3103//===----------------------------------------------------------------------===//
3104
3105
3106/// ParseCast
3107/// ::= CastOpc TypeAndValue 'to' Type
3108bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3109 unsigned Opc) {
3110 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003111 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 if (ParseTypeAndValue(Op, Loc, PFS) ||
3113 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3114 ParseType(DestTy))
3115 return true;
3116
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003117 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3118 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003119 return Error(Loc, "invalid cast opcode for cast from '" +
3120 Op->getType()->getDescription() + "' to '" +
3121 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003122 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3124 return false;
3125}
3126
3127/// ParseSelect
3128/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3129bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3130 LocTy Loc;
3131 Value *Op0, *Op1, *Op2;
3132 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3133 ParseToken(lltok::comma, "expected ',' after select condition") ||
3134 ParseTypeAndValue(Op1, PFS) ||
3135 ParseToken(lltok::comma, "expected ',' after select value") ||
3136 ParseTypeAndValue(Op2, PFS))
3137 return true;
3138
3139 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3140 return Error(Loc, Reason);
3141
3142 Inst = SelectInst::Create(Op0, Op1, Op2);
3143 return false;
3144}
3145
Chris Lattner0088a5c2009-01-05 08:18:44 +00003146/// ParseVA_Arg
3147/// ::= 'va_arg' TypeAndValue ',' Type
3148bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003150 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003151 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003152 if (ParseTypeAndValue(Op, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003154 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003155 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003156
3157 if (!EltTy->isFirstClassType())
3158 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003159
3160 Inst = new VAArgInst(Op, EltTy);
3161 return false;
3162}
3163
3164/// ParseExtractElement
3165/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3166bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3167 LocTy Loc;
3168 Value *Op0, *Op1;
3169 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3170 ParseToken(lltok::comma, "expected ',' after extract value") ||
3171 ParseTypeAndValue(Op1, PFS))
3172 return true;
3173
3174 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3175 return Error(Loc, "invalid extractelement operands");
3176
Eric Christophera3500da2009-07-25 02:28:41 +00003177 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 return false;
3179}
3180
3181/// ParseInsertElement
3182/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3183bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3184 LocTy Loc;
3185 Value *Op0, *Op1, *Op2;
3186 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3187 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3188 ParseTypeAndValue(Op1, PFS) ||
3189 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3190 ParseTypeAndValue(Op2, PFS))
3191 return true;
3192
3193 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003194 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003195
3196 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3197 return false;
3198}
3199
3200/// ParseShuffleVector
3201/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3202bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3203 LocTy Loc;
3204 Value *Op0, *Op1, *Op2;
3205 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3206 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3207 ParseTypeAndValue(Op1, PFS) ||
3208 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3209 ParseTypeAndValue(Op2, PFS))
3210 return true;
3211
3212 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3213 return Error(Loc, "invalid extractelement operands");
3214
3215 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3216 return false;
3217}
3218
3219/// ParsePHI
3220/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3221bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003222 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 Value *Op0, *Op1;
3224 LocTy TypeLoc = Lex.getLoc();
3225
3226 if (ParseType(Ty) ||
3227 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3228 ParseValue(Ty, Op0, PFS) ||
3229 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003230 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3232 return true;
3233
3234 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3235 while (1) {
3236 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3237
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003238 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 break;
3240
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003241 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 ParseValue(Ty, Op0, PFS) ||
3243 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003244 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3246 return true;
3247 }
3248
3249 if (!Ty->isFirstClassType())
3250 return Error(TypeLoc, "phi node must have first class type");
3251
3252 PHINode *PN = PHINode::Create(Ty);
3253 PN->reserveOperandSpace(PHIVals.size());
3254 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3255 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3256 Inst = PN;
3257 return false;
3258}
3259
3260/// ParseCall
3261/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3262/// ParameterList OptionalAttrs
3263bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3264 bool isTail) {
3265 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00003266 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003267 LocTy RetTypeLoc;
3268 ValID CalleeID;
3269 SmallVector<ParamInfo, 16> ArgList;
3270 LocTy CallLoc = Lex.getLoc();
3271
3272 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3273 ParseOptionalCallingConv(CC) ||
3274 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003275 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 ParseValID(CalleeID) ||
3277 ParseParameterList(ArgList, PFS) ||
3278 ParseOptionalAttrs(FnAttrs, 2))
3279 return true;
3280
3281 // If RetType is a non-function pointer type, then this is the short syntax
3282 // for the call, which means that RetType is just the return type. Infer the
3283 // rest of the function argument types from the arguments that are present.
3284 const PointerType *PFTy = 0;
3285 const FunctionType *Ty = 0;
3286 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3287 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3288 // Pull out the types of all of the arguments...
3289 std::vector<const Type*> ParamTypes;
3290 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3291 ParamTypes.push_back(ArgList[i].V->getType());
3292
3293 if (!FunctionType::isValidReturnType(RetType))
3294 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3295
Owen Andersondebcb012009-07-29 22:17:13 +00003296 Ty = FunctionType::get(RetType, ParamTypes, false);
3297 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003298 }
3299
3300 // Look up the callee.
3301 Value *Callee;
3302 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3303
Chris Lattnerdf986172009-01-02 07:01:27 +00003304 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3305 // function attributes.
3306 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3307 if (FnAttrs & ObsoleteFuncAttrs) {
3308 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3309 FnAttrs &= ~ObsoleteFuncAttrs;
3310 }
3311
3312 // Set up the Attributes for the function.
3313 SmallVector<AttributeWithIndex, 8> Attrs;
3314 if (RetAttrs != Attribute::None)
3315 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3316
3317 SmallVector<Value*, 8> Args;
3318
3319 // Loop through FunctionType's arguments and ensure they are specified
3320 // correctly. Also, gather any parameter attributes.
3321 FunctionType::param_iterator I = Ty->param_begin();
3322 FunctionType::param_iterator E = Ty->param_end();
3323 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3324 const Type *ExpectedTy = 0;
3325 if (I != E) {
3326 ExpectedTy = *I++;
3327 } else if (!Ty->isVarArg()) {
3328 return Error(ArgList[i].Loc, "too many arguments specified");
3329 }
3330
3331 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3332 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3333 ExpectedTy->getDescription() + "'");
3334 Args.push_back(ArgList[i].V);
3335 if (ArgList[i].Attrs != Attribute::None)
3336 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3337 }
3338
3339 if (I != E)
3340 return Error(CallLoc, "not enough parameters specified for call");
3341
3342 if (FnAttrs != Attribute::None)
3343 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3344
3345 // Finish off the Attributes and check them
3346 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3347
3348 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3349 CI->setTailCall(isTail);
3350 CI->setCallingConv(CC);
3351 CI->setAttributes(PAL);
3352 Inst = CI;
3353 return false;
3354}
3355
3356//===----------------------------------------------------------------------===//
3357// Memory Instructions.
3358//===----------------------------------------------------------------------===//
3359
3360/// ParseAlloc
3361/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3362/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3363bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3364 unsigned Opc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003365 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003367 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003369 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003370
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003371 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003372 if (Lex.getKind() == lltok::kw_align) {
3373 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003374 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3375 ParseOptionalCommaAlignment(Alignment)) {
3376 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 }
3378 }
3379
Owen Anderson1d0be152009-08-13 21:58:54 +00003380 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 return Error(SizeLoc, "element count must be i32");
3382
3383 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003384 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003385 else
Owen Anderson50dead02009-07-15 23:53:25 +00003386 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 return false;
3388}
3389
3390/// ParseFree
3391/// ::= 'free' TypeAndValue
3392bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3393 Value *Val; LocTy Loc;
3394 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3395 if (!isa<PointerType>(Val->getType()))
3396 return Error(Loc, "operand to free must be a pointer");
3397 Inst = new FreeInst(Val);
3398 return false;
3399}
3400
3401/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003402/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003403bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3404 bool isVolatile) {
3405 Value *Val; LocTy Loc;
3406 unsigned Alignment;
3407 if (ParseTypeAndValue(Val, Loc, PFS) ||
3408 ParseOptionalCommaAlignment(Alignment))
3409 return true;
3410
3411 if (!isa<PointerType>(Val->getType()) ||
3412 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3413 return Error(Loc, "load operand must be a pointer to a first class type");
3414
3415 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3416 return false;
3417}
3418
3419/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003420/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003421bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3422 bool isVolatile) {
3423 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3424 unsigned Alignment;
3425 if (ParseTypeAndValue(Val, Loc, PFS) ||
3426 ParseToken(lltok::comma, "expected ',' after store operand") ||
3427 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3428 ParseOptionalCommaAlignment(Alignment))
3429 return true;
3430
3431 if (!isa<PointerType>(Ptr->getType()))
3432 return Error(PtrLoc, "store operand must be a pointer");
3433 if (!Val->getType()->isFirstClassType())
3434 return Error(Loc, "store operand must be a first class value");
3435 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3436 return Error(Loc, "stored value and pointer type do not match");
3437
3438 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3439 return false;
3440}
3441
3442/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003443/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003444/// FIXME: Remove support for getresult in LLVM 3.0
3445bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3446 Value *Val; LocTy ValLoc, EltLoc;
3447 unsigned Element;
3448 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3449 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003450 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 return true;
3452
3453 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3454 return Error(ValLoc, "getresult inst requires an aggregate operand");
3455 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3456 return Error(EltLoc, "invalid getresult index for value");
3457 Inst = ExtractValueInst::Create(Val, Element);
3458 return false;
3459}
3460
3461/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003462/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003463bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3464 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003465
Dan Gohmandcb40a32009-07-29 15:58:36 +00003466 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003467
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003468 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003469
3470 if (!isa<PointerType>(Ptr->getType()))
3471 return Error(Loc, "base of getelementptr must be a pointer");
3472
3473 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003474 while (EatIfPresent(lltok::comma)) {
3475 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003476 if (!isa<IntegerType>(Val->getType()))
3477 return Error(EltLoc, "getelementptr index must be an integer");
3478 Indices.push_back(Val);
3479 }
3480
3481 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3482 Indices.begin(), Indices.end()))
3483 return Error(Loc, "invalid getelementptr indices");
3484 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003485 if (InBounds)
3486 cast<GEPOperator>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003487 return false;
3488}
3489
3490/// ParseExtractValue
3491/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3492bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3493 Value *Val; LocTy Loc;
3494 SmallVector<unsigned, 4> Indices;
3495 if (ParseTypeAndValue(Val, Loc, PFS) ||
3496 ParseIndexList(Indices))
3497 return true;
3498
3499 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3500 return Error(Loc, "extractvalue operand must be array or struct");
3501
3502 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3503 Indices.end()))
3504 return Error(Loc, "invalid indices for extractvalue");
3505 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3506 return false;
3507}
3508
3509/// ParseInsertValue
3510/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3511bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3512 Value *Val0, *Val1; LocTy Loc0, Loc1;
3513 SmallVector<unsigned, 4> Indices;
3514 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3515 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3516 ParseTypeAndValue(Val1, Loc1, PFS) ||
3517 ParseIndexList(Indices))
3518 return true;
3519
3520 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3521 return Error(Loc0, "extractvalue operand must be array or struct");
3522
3523 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3524 Indices.end()))
3525 return Error(Loc0, "invalid indices for insertvalue");
3526 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3527 return false;
3528}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003529
3530//===----------------------------------------------------------------------===//
3531// Embedded metadata.
3532//===----------------------------------------------------------------------===//
3533
3534/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003535/// ::= Element (',' Element)*
3536/// Element
3537/// ::= 'null' | TypeAndValue
3538bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003539 assert(Lex.getKind() == lltok::lbrace);
3540 Lex.Lex();
3541 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003542 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003543 if (Lex.getKind() == lltok::kw_null) {
3544 Lex.Lex();
3545 V = 0;
3546 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003547 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003548 if (ParseType(Ty)) return true;
3549 if (Lex.getKind() == lltok::Metadata) {
3550 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003551 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003552 if (!ParseMDNode(Node))
3553 V = Node;
3554 else {
3555 MetadataBase *MDS = 0;
3556 if (ParseMDString(MDS)) return true;
3557 V = MDS;
3558 }
3559 } else {
3560 Constant *C;
3561 if (ParseGlobalValue(Ty, C)) return true;
3562 V = C;
3563 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003564 }
3565 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003566 } while (EatIfPresent(lltok::comma));
3567
3568 return false;
3569}