blob: ee084311e130550cc8ec72295c319e8a819ecb0b [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;
Dale Johannesende86d472009-08-26 01:08:21 +0000908 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000909 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
910 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
911 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
912 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
913 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
914 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000915 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000916
917 case lltok::kw_align: {
918 unsigned Alignment;
919 if (ParseOptionalAlignment(Alignment))
920 return true;
921 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
922 continue;
923 }
924 }
925 Lex.Lex();
926 }
927}
928
929/// ParseOptionalLinkage
930/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000931/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000932/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000933/// ::= 'internal'
934/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000935/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000936/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000937/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000938/// ::= 'appending'
939/// ::= 'dllexport'
940/// ::= 'common'
941/// ::= 'dllimport'
942/// ::= 'extern_weak'
943/// ::= 'external'
944bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
945 HasLinkage = false;
946 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000947 default: Res=GlobalValue::ExternalLinkage; return false;
948 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
949 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
950 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
951 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
952 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
953 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
954 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000955 case lltok::kw_available_externally:
956 Res = GlobalValue::AvailableExternallyLinkage;
957 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000958 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
959 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
960 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
961 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
962 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
963 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000964 }
965 Lex.Lex();
966 HasLinkage = true;
967 return false;
968}
969
970/// ParseOptionalVisibility
971/// ::= /*empty*/
972/// ::= 'default'
973/// ::= 'hidden'
974/// ::= 'protected'
975///
976bool LLParser::ParseOptionalVisibility(unsigned &Res) {
977 switch (Lex.getKind()) {
978 default: Res = GlobalValue::DefaultVisibility; return false;
979 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
980 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
981 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
982 }
983 Lex.Lex();
984 return false;
985}
986
987/// ParseOptionalCallingConv
988/// ::= /*empty*/
989/// ::= 'ccc'
990/// ::= 'fastcc'
991/// ::= 'coldcc'
992/// ::= 'x86_stdcallcc'
993/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000994/// ::= 'arm_apcscc'
995/// ::= 'arm_aapcscc'
996/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000997/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000998///
Chris Lattnerdf986172009-01-02 07:01:27 +0000999bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1000 switch (Lex.getKind()) {
1001 default: CC = CallingConv::C; return false;
1002 case lltok::kw_ccc: CC = CallingConv::C; break;
1003 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1004 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1005 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1006 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001007 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1008 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1009 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001010 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
Chris Lattnerdf986172009-01-02 07:01:27 +00001011 }
1012 Lex.Lex();
1013 return false;
1014}
1015
1016/// ParseOptionalAlignment
1017/// ::= /* empty */
1018/// ::= 'align' 4
1019bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1020 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001021 if (!EatIfPresent(lltok::kw_align))
1022 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001023 LocTy AlignLoc = Lex.getLoc();
1024 if (ParseUInt32(Alignment)) return true;
1025 if (!isPowerOf2_32(Alignment))
1026 return Error(AlignLoc, "alignment is not a power of two");
1027 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001028}
1029
1030/// ParseOptionalCommaAlignment
1031/// ::= /* empty */
1032/// ::= ',' 'align' 4
1033bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1034 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001035 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00001036 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001037 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001038 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001039}
1040
1041/// ParseIndexList
1042/// ::= (',' uint32)+
1043bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1044 if (Lex.getKind() != lltok::comma)
1045 return TokError("expected ',' as start of index list");
1046
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001047 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001048 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001049 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001050 Indices.push_back(Idx);
1051 }
1052
1053 return false;
1054}
1055
1056//===----------------------------------------------------------------------===//
1057// Type Parsing.
1058//===----------------------------------------------------------------------===//
1059
1060/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001061bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1062 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001063 if (ParseTypeRec(Result)) return true;
1064
1065 // Verify no unresolved uprefs.
1066 if (!UpRefs.empty())
1067 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +00001068
Owen Anderson1d0be152009-08-13 21:58:54 +00001069 if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001070 return Error(TypeLoc, "void type only allowed for function results");
1071
Chris Lattnerdf986172009-01-02 07:01:27 +00001072 return false;
1073}
1074
1075/// HandleUpRefs - Every time we finish a new layer of types, this function is
1076/// called. It loops through the UpRefs vector, which is a list of the
1077/// currently active types. For each type, if the up-reference is contained in
1078/// the newly completed type, we decrement the level count. When the level
1079/// count reaches zero, the up-referenced type is the type that is passed in:
1080/// thus we can complete the cycle.
1081///
1082PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1083 // If Ty isn't abstract, or if there are no up-references in it, then there is
1084 // nothing to resolve here.
1085 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1086
1087 PATypeHolder Ty(ty);
1088#if 0
1089 errs() << "Type '" << Ty->getDescription()
1090 << "' newly formed. Resolving upreferences.\n"
1091 << UpRefs.size() << " upreferences active!\n";
1092#endif
1093
1094 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1095 // to zero), we resolve them all together before we resolve them to Ty. At
1096 // the end of the loop, if there is anything to resolve to Ty, it will be in
1097 // this variable.
1098 OpaqueType *TypeToResolve = 0;
1099
1100 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1101 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1102 bool ContainsType =
1103 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1104 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1105
1106#if 0
1107 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1108 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1109 << (ContainsType ? "true" : "false")
1110 << " level=" << UpRefs[i].NestingLevel << "\n";
1111#endif
1112 if (!ContainsType)
1113 continue;
1114
1115 // Decrement level of upreference
1116 unsigned Level = --UpRefs[i].NestingLevel;
1117 UpRefs[i].LastContainedTy = Ty;
1118
1119 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1120 if (Level != 0)
1121 continue;
1122
1123#if 0
1124 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1125#endif
1126 if (!TypeToResolve)
1127 TypeToResolve = UpRefs[i].UpRefTy;
1128 else
1129 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1130 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1131 --i; // Do not skip the next element.
1132 }
1133
1134 if (TypeToResolve)
1135 TypeToResolve->refineAbstractTypeTo(Ty);
1136
1137 return Ty;
1138}
1139
1140
1141/// ParseTypeRec - The recursive function used to process the internal
1142/// implementation details of types.
1143bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1144 switch (Lex.getKind()) {
1145 default:
1146 return TokError("expected type");
1147 case lltok::Type:
1148 // TypeRec ::= 'float' | 'void' (etc)
1149 Result = Lex.getTyVal();
1150 Lex.Lex();
1151 break;
1152 case lltok::kw_opaque:
1153 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001154 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001155 Lex.Lex();
1156 break;
1157 case lltok::lbrace:
1158 // TypeRec ::= '{' ... '}'
1159 if (ParseStructType(Result, false))
1160 return true;
1161 break;
1162 case lltok::lsquare:
1163 // TypeRec ::= '[' ... ']'
1164 Lex.Lex(); // eat the lsquare.
1165 if (ParseArrayVectorType(Result, false))
1166 return true;
1167 break;
1168 case lltok::less: // Either vector or packed struct.
1169 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001170 Lex.Lex();
1171 if (Lex.getKind() == lltok::lbrace) {
1172 if (ParseStructType(Result, true) ||
1173 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001174 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 } else if (ParseArrayVectorType(Result, true))
1176 return true;
1177 break;
1178 case lltok::LocalVar:
1179 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1180 // TypeRec ::= %foo
1181 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1182 Result = T;
1183 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001184 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001185 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1186 std::make_pair(Result,
1187 Lex.getLoc())));
1188 M->addTypeName(Lex.getStrVal(), Result.get());
1189 }
1190 Lex.Lex();
1191 break;
1192
1193 case lltok::LocalVarID:
1194 // TypeRec ::= %4
1195 if (Lex.getUIntVal() < NumberedTypes.size())
1196 Result = NumberedTypes[Lex.getUIntVal()];
1197 else {
1198 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1199 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1200 if (I != ForwardRefTypeIDs.end())
1201 Result = I->second.first;
1202 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001203 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001204 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1205 std::make_pair(Result,
1206 Lex.getLoc())));
1207 }
1208 }
1209 Lex.Lex();
1210 break;
1211 case lltok::backslash: {
1212 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001213 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001214 unsigned Val;
1215 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001216 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001217 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1218 Result = OT;
1219 break;
1220 }
1221 }
1222
1223 // Parse the type suffixes.
1224 while (1) {
1225 switch (Lex.getKind()) {
1226 // End of type.
1227 default: return false;
1228
1229 // TypeRec ::= TypeRec '*'
1230 case lltok::star:
Owen Anderson1d0be152009-08-13 21:58:54 +00001231 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001233 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001234 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001235 if (!PointerType::isValidElementType(Result.get()))
1236 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001237 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 Lex.Lex();
1239 break;
1240
1241 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1242 case lltok::kw_addrspace: {
Owen Anderson1d0be152009-08-13 21:58:54 +00001243 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001245 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001246 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001247 if (!PointerType::isValidElementType(Result.get()))
1248 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001249 unsigned AddrSpace;
1250 if (ParseOptionalAddrSpace(AddrSpace) ||
1251 ParseToken(lltok::star, "expected '*' in address space"))
1252 return true;
1253
Owen Andersondebcb012009-07-29 22:17:13 +00001254 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 break;
1256 }
1257
1258 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1259 case lltok::lparen:
1260 if (ParseFunctionType(Result))
1261 return true;
1262 break;
1263 }
1264 }
1265}
1266
1267/// ParseParameterList
1268/// ::= '(' ')'
1269/// ::= '(' Arg (',' Arg)* ')'
1270/// Arg
1271/// ::= Type OptionalAttributes Value OptionalAttributes
1272bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1273 PerFunctionState &PFS) {
1274 if (ParseToken(lltok::lparen, "expected '(' in call"))
1275 return true;
1276
1277 while (Lex.getKind() != lltok::rparen) {
1278 // If this isn't the first argument, we need a comma.
1279 if (!ArgList.empty() &&
1280 ParseToken(lltok::comma, "expected ',' in argument list"))
1281 return true;
1282
1283 // Parse the argument.
1284 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001285 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 unsigned ArgAttrs1, ArgAttrs2;
1287 Value *V;
1288 if (ParseType(ArgTy, ArgLoc) ||
1289 ParseOptionalAttrs(ArgAttrs1, 0) ||
1290 ParseValue(ArgTy, V, PFS) ||
1291 // FIXME: Should not allow attributes after the argument, remove this in
1292 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001293 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 return true;
1295 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1296 }
1297
1298 Lex.Lex(); // Lex the ')'.
1299 return false;
1300}
1301
1302
1303
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001304/// ParseArgumentList - Parse the argument list for a function type or function
1305/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001306/// ::= '(' ArgTypeListI ')'
1307/// ArgTypeListI
1308/// ::= /*empty*/
1309/// ::= '...'
1310/// ::= ArgTypeList ',' '...'
1311/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001312///
Chris Lattnerdf986172009-01-02 07:01:27 +00001313bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001314 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 isVarArg = false;
1316 assert(Lex.getKind() == lltok::lparen);
1317 Lex.Lex(); // eat the (.
1318
1319 if (Lex.getKind() == lltok::rparen) {
1320 // empty
1321 } else if (Lex.getKind() == lltok::dotdotdot) {
1322 isVarArg = true;
1323 Lex.Lex();
1324 } else {
1325 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001326 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001329
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001330 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1331 // types (such as a function returning a pointer to itself). If parsing a
1332 // function prototype, we require fully resolved types.
1333 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001334 ParseOptionalAttrs(Attrs, 0)) return true;
1335
Owen Anderson1d0be152009-08-13 21:58:54 +00001336 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001337 return Error(TypeLoc, "argument can not have void type");
1338
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 if (Lex.getKind() == lltok::LocalVar ||
1340 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1341 Name = Lex.getStrVal();
1342 Lex.Lex();
1343 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001344
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001345 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001346 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001347
1348 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1349
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001350 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001352 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 break;
1355 }
1356
1357 // Otherwise must be an argument type.
1358 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001359 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001360 ParseOptionalAttrs(Attrs, 0)) return true;
1361
Owen Anderson1d0be152009-08-13 21:58:54 +00001362 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001363 return Error(TypeLoc, "argument can not have void type");
1364
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 if (Lex.getKind() == lltok::LocalVar ||
1366 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1367 Name = Lex.getStrVal();
1368 Lex.Lex();
1369 } else {
1370 Name = "";
1371 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001372
1373 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1374 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001375
1376 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1377 }
1378 }
1379
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001380 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001381}
1382
1383/// ParseFunctionType
1384/// ::= Type ArgumentList OptionalAttrs
1385bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1386 assert(Lex.getKind() == lltok::lparen);
1387
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001388 if (!FunctionType::isValidReturnType(Result))
1389 return TokError("invalid function return type");
1390
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 std::vector<ArgInfo> ArgList;
1392 bool isVarArg;
1393 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001394 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001395 // FIXME: Allow, but ignore attributes on function types!
1396 // FIXME: Remove in LLVM 3.0
1397 ParseOptionalAttrs(Attrs, 2))
1398 return true;
1399
1400 // Reject names on the arguments lists.
1401 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1402 if (!ArgList[i].Name.empty())
1403 return Error(ArgList[i].Loc, "argument name invalid in function type");
1404 if (!ArgList[i].Attrs != 0) {
1405 // Allow but ignore attributes on function types; this permits
1406 // auto-upgrade.
1407 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1408 }
1409 }
1410
1411 std::vector<const Type*> ArgListTy;
1412 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1413 ArgListTy.push_back(ArgList[i].Type);
1414
Owen Andersondebcb012009-07-29 22:17:13 +00001415 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001416 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001417 return false;
1418}
1419
1420/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1421/// TypeRec
1422/// ::= '{' '}'
1423/// ::= '{' TypeRec (',' TypeRec)* '}'
1424/// ::= '<' '{' '}' '>'
1425/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1426bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1427 assert(Lex.getKind() == lltok::lbrace);
1428 Lex.Lex(); // Consume the '{'
1429
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001430 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001431 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 return false;
1433 }
1434
1435 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001436 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001437 if (ParseTypeRec(Result)) return true;
1438 ParamsList.push_back(Result);
1439
Owen Anderson1d0be152009-08-13 21:58:54 +00001440 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001441 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001442 if (!StructType::isValidElementType(Result))
1443 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001444
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001445 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001446 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001448
Owen Anderson1d0be152009-08-13 21:58:54 +00001449 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001450 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001451 if (!StructType::isValidElementType(Result))
1452 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 ParamsList.push_back(Result);
1455 }
1456
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001457 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1458 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001459
1460 std::vector<const Type*> ParamsListTy;
1461 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1462 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001463 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001464 return false;
1465}
1466
1467/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1468/// token has already been consumed.
1469/// TypeRec
1470/// ::= '[' APSINTVAL 'x' Types ']'
1471/// ::= '<' APSINTVAL 'x' Types '>'
1472bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1473 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1474 Lex.getAPSIntVal().getBitWidth() > 64)
1475 return TokError("expected number in address space");
1476
1477 LocTy SizeLoc = Lex.getLoc();
1478 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001479 Lex.Lex();
1480
1481 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1482 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001483
1484 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001485 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001486 if (ParseTypeRec(EltTy)) return true;
1487
Owen Anderson1d0be152009-08-13 21:58:54 +00001488 if (EltTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001489 return Error(TypeLoc, "array and vector element type cannot be void");
1490
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001491 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1492 "expected end of sequential type"))
1493 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001494
1495 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001496 if (Size == 0)
1497 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001498 if ((unsigned)Size != Size)
1499 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001500 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001502 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001504 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001505 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001506 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 }
1508 return false;
1509}
1510
1511//===----------------------------------------------------------------------===//
1512// Function Semantic Analysis.
1513//===----------------------------------------------------------------------===//
1514
1515LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1516 : P(p), F(f) {
1517
1518 // Insert unnamed arguments into the NumberedVals list.
1519 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1520 AI != E; ++AI)
1521 if (!AI->hasName())
1522 NumberedVals.push_back(AI);
1523}
1524
1525LLParser::PerFunctionState::~PerFunctionState() {
1526 // If there were any forward referenced non-basicblock values, delete them.
1527 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1528 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1529 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001530 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001531 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001532 delete I->second.first;
1533 I->second.first = 0;
1534 }
1535
1536 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1537 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1538 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001539 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001540 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001541 delete I->second.first;
1542 I->second.first = 0;
1543 }
1544}
1545
1546bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1547 if (!ForwardRefVals.empty())
1548 return P.Error(ForwardRefVals.begin()->second.second,
1549 "use of undefined value '%" + ForwardRefVals.begin()->first +
1550 "'");
1551 if (!ForwardRefValIDs.empty())
1552 return P.Error(ForwardRefValIDs.begin()->second.second,
1553 "use of undefined value '%" +
1554 utostr(ForwardRefValIDs.begin()->first) + "'");
1555 return false;
1556}
1557
1558
1559/// GetVal - Get a value with the specified name or ID, creating a
1560/// forward reference record if needed. This can return null if the value
1561/// exists but does not have the right type.
1562Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1563 const Type *Ty, LocTy Loc) {
1564 // Look this name up in the normal function symbol table.
1565 Value *Val = F.getValueSymbolTable().lookup(Name);
1566
1567 // If this is a forward reference for the value, see if we already created a
1568 // forward ref record.
1569 if (Val == 0) {
1570 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1571 I = ForwardRefVals.find(Name);
1572 if (I != ForwardRefVals.end())
1573 Val = I->second.first;
1574 }
1575
1576 // If we have the value in the symbol table or fwd-ref table, return it.
1577 if (Val) {
1578 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001579 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 P.Error(Loc, "'%" + Name + "' is not a basic block");
1581 else
1582 P.Error(Loc, "'%" + Name + "' defined with type '" +
1583 Val->getType()->getDescription() + "'");
1584 return 0;
1585 }
1586
1587 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001588 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1589 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 P.Error(Loc, "invalid use of a non-first-class type");
1591 return 0;
1592 }
1593
1594 // Otherwise, create a new forward reference for this value and remember it.
1595 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001596 if (Ty == Type::getLabelTy(F.getContext()))
1597 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 else
1599 FwdVal = new Argument(Ty, Name);
1600
1601 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1602 return FwdVal;
1603}
1604
1605Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1606 LocTy Loc) {
1607 // Look this name up in the normal function symbol table.
1608 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1609
1610 // If this is a forward reference for the value, see if we already created a
1611 // forward ref record.
1612 if (Val == 0) {
1613 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1614 I = ForwardRefValIDs.find(ID);
1615 if (I != ForwardRefValIDs.end())
1616 Val = I->second.first;
1617 }
1618
1619 // If we have the value in the symbol table or fwd-ref table, return it.
1620 if (Val) {
1621 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001622 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1624 else
1625 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1626 Val->getType()->getDescription() + "'");
1627 return 0;
1628 }
1629
Owen Anderson1d0be152009-08-13 21:58:54 +00001630 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1631 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001632 P.Error(Loc, "invalid use of a non-first-class type");
1633 return 0;
1634 }
1635
1636 // Otherwise, create a new forward reference for this value and remember it.
1637 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001638 if (Ty == Type::getLabelTy(F.getContext()))
1639 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001640 else
1641 FwdVal = new Argument(Ty);
1642
1643 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1644 return FwdVal;
1645}
1646
1647/// SetInstName - After an instruction is parsed and inserted into its
1648/// basic block, this installs its name.
1649bool LLParser::PerFunctionState::SetInstName(int NameID,
1650 const std::string &NameStr,
1651 LocTy NameLoc, Instruction *Inst) {
1652 // If this instruction has void type, it cannot have a name or ID specified.
Owen Anderson1d0be152009-08-13 21:58:54 +00001653 if (Inst->getType() == Type::getVoidTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 if (NameID != -1 || !NameStr.empty())
1655 return P.Error(NameLoc, "instructions returning void cannot have a name");
1656 return false;
1657 }
1658
1659 // If this was a numbered instruction, verify that the instruction is the
1660 // expected value and resolve any forward references.
1661 if (NameStr.empty()) {
1662 // If neither a name nor an ID was specified, just use the next ID.
1663 if (NameID == -1)
1664 NameID = NumberedVals.size();
1665
1666 if (unsigned(NameID) != NumberedVals.size())
1667 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1668 utostr(NumberedVals.size()) + "'");
1669
1670 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1671 ForwardRefValIDs.find(NameID);
1672 if (FI != ForwardRefValIDs.end()) {
1673 if (FI->second.first->getType() != Inst->getType())
1674 return P.Error(NameLoc, "instruction forward referenced with type '" +
1675 FI->second.first->getType()->getDescription() + "'");
1676 FI->second.first->replaceAllUsesWith(Inst);
1677 ForwardRefValIDs.erase(FI);
1678 }
1679
1680 NumberedVals.push_back(Inst);
1681 return false;
1682 }
1683
1684 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1685 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1686 FI = ForwardRefVals.find(NameStr);
1687 if (FI != ForwardRefVals.end()) {
1688 if (FI->second.first->getType() != Inst->getType())
1689 return P.Error(NameLoc, "instruction forward referenced with type '" +
1690 FI->second.first->getType()->getDescription() + "'");
1691 FI->second.first->replaceAllUsesWith(Inst);
1692 ForwardRefVals.erase(FI);
1693 }
1694
1695 // Set the name on the instruction.
1696 Inst->setName(NameStr);
1697
1698 if (Inst->getNameStr() != NameStr)
1699 return P.Error(NameLoc, "multiple definition of local value named '" +
1700 NameStr + "'");
1701 return false;
1702}
1703
1704/// GetBB - Get a basic block with the specified name or ID, creating a
1705/// forward reference record if needed.
1706BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1707 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001708 return cast_or_null<BasicBlock>(GetVal(Name,
1709 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001710}
1711
1712BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001713 return cast_or_null<BasicBlock>(GetVal(ID,
1714 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001715}
1716
1717/// DefineBB - Define the specified basic block, which is either named or
1718/// unnamed. If there is an error, this returns null otherwise it returns
1719/// the block being defined.
1720BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1721 LocTy Loc) {
1722 BasicBlock *BB;
1723 if (Name.empty())
1724 BB = GetBB(NumberedVals.size(), Loc);
1725 else
1726 BB = GetBB(Name, Loc);
1727 if (BB == 0) return 0; // Already diagnosed error.
1728
1729 // Move the block to the end of the function. Forward ref'd blocks are
1730 // inserted wherever they happen to be referenced.
1731 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1732
1733 // Remove the block from forward ref sets.
1734 if (Name.empty()) {
1735 ForwardRefValIDs.erase(NumberedVals.size());
1736 NumberedVals.push_back(BB);
1737 } else {
1738 // BB forward references are already in the function symbol table.
1739 ForwardRefVals.erase(Name);
1740 }
1741
1742 return BB;
1743}
1744
1745//===----------------------------------------------------------------------===//
1746// Constants.
1747//===----------------------------------------------------------------------===//
1748
1749/// ParseValID - Parse an abstract value that doesn't necessarily have a
1750/// type implied. For example, if we parse "4" we don't know what integer type
1751/// it has. The value will later be combined with its type and checked for
1752/// sanity.
1753bool LLParser::ParseValID(ValID &ID) {
1754 ID.Loc = Lex.getLoc();
1755 switch (Lex.getKind()) {
1756 default: return TokError("expected value token");
1757 case lltok::GlobalID: // @42
1758 ID.UIntVal = Lex.getUIntVal();
1759 ID.Kind = ValID::t_GlobalID;
1760 break;
1761 case lltok::GlobalVar: // @foo
1762 ID.StrVal = Lex.getStrVal();
1763 ID.Kind = ValID::t_GlobalName;
1764 break;
1765 case lltok::LocalVarID: // %42
1766 ID.UIntVal = Lex.getUIntVal();
1767 ID.Kind = ValID::t_LocalID;
1768 break;
1769 case lltok::LocalVar: // %foo
1770 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1771 ID.StrVal = Lex.getStrVal();
1772 ID.Kind = ValID::t_LocalName;
1773 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001774 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001775 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001776 Lex.Lex();
1777 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001778 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001779 if (ParseMDNodeVector(Elts) ||
1780 ParseToken(lltok::rbrace, "expected end of metadata node"))
1781 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001782
Owen Anderson647e3012009-07-31 21:35:40 +00001783 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001784 return false;
1785 }
1786
Devang Patel923078c2009-07-01 19:21:12 +00001787 // Standalone metadata reference
1788 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001789 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001790 return false;
Devang Patel256be962009-07-20 19:00:08 +00001791
Nick Lewycky21cc4462009-04-04 07:22:01 +00001792 // MDString:
1793 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001794 if (ParseMDString(ID.MetadataVal)) return true;
1795 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001796 return false;
1797 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 case lltok::APSInt:
1799 ID.APSIntVal = Lex.getAPSIntVal();
1800 ID.Kind = ValID::t_APSInt;
1801 break;
1802 case lltok::APFloat:
1803 ID.APFloatVal = Lex.getAPFloatVal();
1804 ID.Kind = ValID::t_APFloat;
1805 break;
1806 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001807 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 ID.Kind = ValID::t_Constant;
1809 break;
1810 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001811 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001812 ID.Kind = ValID::t_Constant;
1813 break;
1814 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1815 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1816 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1817
1818 case lltok::lbrace: {
1819 // ValID ::= '{' ConstVector '}'
1820 Lex.Lex();
1821 SmallVector<Constant*, 16> Elts;
1822 if (ParseGlobalValueVector(Elts) ||
1823 ParseToken(lltok::rbrace, "expected end of struct constant"))
1824 return true;
1825
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001826 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1827 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001828 ID.Kind = ValID::t_Constant;
1829 return false;
1830 }
1831 case lltok::less: {
1832 // ValID ::= '<' ConstVector '>' --> Vector.
1833 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1834 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001835 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001836
1837 SmallVector<Constant*, 16> Elts;
1838 LocTy FirstEltLoc = Lex.getLoc();
1839 if (ParseGlobalValueVector(Elts) ||
1840 (isPackedStruct &&
1841 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1842 ParseToken(lltok::greater, "expected end of constant"))
1843 return true;
1844
1845 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001846 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001847 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 ID.Kind = ValID::t_Constant;
1849 return false;
1850 }
1851
1852 if (Elts.empty())
1853 return Error(ID.Loc, "constant vector must not be empty");
1854
1855 if (!Elts[0]->getType()->isInteger() &&
1856 !Elts[0]->getType()->isFloatingPoint())
1857 return Error(FirstEltLoc,
1858 "vector elements must have integer or floating point type");
1859
1860 // Verify that all the vector elements have the same type.
1861 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1862 if (Elts[i]->getType() != Elts[0]->getType())
1863 return Error(FirstEltLoc,
1864 "vector element #" + utostr(i) +
1865 " is not of type '" + Elts[0]->getType()->getDescription());
1866
Owen Andersonaf7ec972009-07-28 21:19:26 +00001867 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 ID.Kind = ValID::t_Constant;
1869 return false;
1870 }
1871 case lltok::lsquare: { // Array Constant
1872 Lex.Lex();
1873 SmallVector<Constant*, 16> Elts;
1874 LocTy FirstEltLoc = Lex.getLoc();
1875 if (ParseGlobalValueVector(Elts) ||
1876 ParseToken(lltok::rsquare, "expected end of array constant"))
1877 return true;
1878
1879 // Handle empty element.
1880 if (Elts.empty()) {
1881 // Use undef instead of an array because it's inconvenient to determine
1882 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001883 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001884 return false;
1885 }
1886
1887 if (!Elts[0]->getType()->isFirstClassType())
1888 return Error(FirstEltLoc, "invalid array element type: " +
1889 Elts[0]->getType()->getDescription());
1890
Owen Andersondebcb012009-07-29 22:17:13 +00001891 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001892
1893 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001894 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 if (Elts[i]->getType() != Elts[0]->getType())
1896 return Error(FirstEltLoc,
1897 "array element #" + utostr(i) +
1898 " is not of type '" +Elts[0]->getType()->getDescription());
1899 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001900
Owen Anderson1fd70962009-07-28 18:32:17 +00001901 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 ID.Kind = ValID::t_Constant;
1903 return false;
1904 }
1905 case lltok::kw_c: // c "foo"
1906 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001907 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001908 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1909 ID.Kind = ValID::t_Constant;
1910 return false;
1911
1912 case lltok::kw_asm: {
1913 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1914 bool HasSideEffect;
1915 Lex.Lex();
1916 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001917 ParseStringConstant(ID.StrVal) ||
1918 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 ParseToken(lltok::StringConstant, "expected constraint string"))
1920 return true;
1921 ID.StrVal2 = Lex.getStrVal();
1922 ID.UIntVal = HasSideEffect;
1923 ID.Kind = ValID::t_InlineAsm;
1924 return false;
1925 }
1926
1927 case lltok::kw_trunc:
1928 case lltok::kw_zext:
1929 case lltok::kw_sext:
1930 case lltok::kw_fptrunc:
1931 case lltok::kw_fpext:
1932 case lltok::kw_bitcast:
1933 case lltok::kw_uitofp:
1934 case lltok::kw_sitofp:
1935 case lltok::kw_fptoui:
1936 case lltok::kw_fptosi:
1937 case lltok::kw_inttoptr:
1938 case lltok::kw_ptrtoint: {
1939 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00001940 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001941 Constant *SrcVal;
1942 Lex.Lex();
1943 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1944 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001945 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001946 ParseType(DestTy) ||
1947 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1948 return true;
1949 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1950 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1951 SrcVal->getType()->getDescription() + "' to '" +
1952 DestTy->getDescription() + "'");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001953 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00001954 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001955 ID.Kind = ValID::t_Constant;
1956 return false;
1957 }
1958 case lltok::kw_extractvalue: {
1959 Lex.Lex();
1960 Constant *Val;
1961 SmallVector<unsigned, 4> Indices;
1962 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1963 ParseGlobalTypeAndValue(Val) ||
1964 ParseIndexList(Indices) ||
1965 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1966 return true;
1967 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1968 return Error(ID.Loc, "extractvalue operand must be array or struct");
1969 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1970 Indices.end()))
1971 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001972 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001973 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001974 ID.Kind = ValID::t_Constant;
1975 return false;
1976 }
1977 case lltok::kw_insertvalue: {
1978 Lex.Lex();
1979 Constant *Val0, *Val1;
1980 SmallVector<unsigned, 4> Indices;
1981 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1982 ParseGlobalTypeAndValue(Val0) ||
1983 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1984 ParseGlobalTypeAndValue(Val1) ||
1985 ParseIndexList(Indices) ||
1986 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1987 return true;
1988 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1989 return Error(ID.Loc, "extractvalue operand must be array or struct");
1990 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1991 Indices.end()))
1992 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001993 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00001994 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 ID.Kind = ValID::t_Constant;
1996 return false;
1997 }
1998 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001999 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002000 unsigned PredVal, Opc = Lex.getUIntVal();
2001 Constant *Val0, *Val1;
2002 Lex.Lex();
2003 if (ParseCmpPredicate(PredVal, Opc) ||
2004 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2005 ParseGlobalTypeAndValue(Val0) ||
2006 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2007 ParseGlobalTypeAndValue(Val1) ||
2008 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2009 return true;
2010
2011 if (Val0->getType() != Val1->getType())
2012 return Error(ID.Loc, "compare operands must have the same type");
2013
2014 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2015
2016 if (Opc == Instruction::FCmp) {
2017 if (!Val0->getType()->isFPOrFPVector())
2018 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002019 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002020 } else {
2021 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002022 if (!Val0->getType()->isIntOrIntVector() &&
2023 !isa<PointerType>(Val0->getType()))
2024 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002025 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 }
2027 ID.Kind = ValID::t_Constant;
2028 return false;
2029 }
2030
2031 // Binary Operators.
2032 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002033 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002034 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002035 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002037 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002038 case lltok::kw_udiv:
2039 case lltok::kw_sdiv:
2040 case lltok::kw_fdiv:
2041 case lltok::kw_urem:
2042 case lltok::kw_srem:
2043 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002044 bool NUW = false;
2045 bool NSW = false;
2046 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002047 unsigned Opc = Lex.getUIntVal();
2048 Constant *Val0, *Val1;
2049 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002050 LocTy ModifierLoc = Lex.getLoc();
2051 if (Opc == Instruction::Add ||
2052 Opc == Instruction::Sub ||
2053 Opc == Instruction::Mul) {
2054 if (EatIfPresent(lltok::kw_nuw))
2055 NUW = true;
2056 if (EatIfPresent(lltok::kw_nsw)) {
2057 NSW = true;
2058 if (EatIfPresent(lltok::kw_nuw))
2059 NUW = true;
2060 }
2061 } else if (Opc == Instruction::SDiv) {
2062 if (EatIfPresent(lltok::kw_exact))
2063 Exact = true;
2064 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2066 ParseGlobalTypeAndValue(Val0) ||
2067 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2068 ParseGlobalTypeAndValue(Val1) ||
2069 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2070 return true;
2071 if (Val0->getType() != Val1->getType())
2072 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002073 if (!Val0->getType()->isIntOrIntVector()) {
2074 if (NUW)
2075 return Error(ModifierLoc, "nuw only applies to integer operations");
2076 if (NSW)
2077 return Error(ModifierLoc, "nsw only applies to integer operations");
2078 }
2079 // API compatibility: Accept either integer or floating-point types with
2080 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 if (!Val0->getType()->isIntOrIntVector() &&
2082 !Val0->getType()->isFPOrFPVector())
2083 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002084 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
Dan Gohman59858cf2009-07-27 16:11:46 +00002085 if (NUW)
Dan Gohman5078f842009-08-20 17:11:38 +00002086 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002087 if (NSW)
Dan Gohman5078f842009-08-20 17:11:38 +00002088 cast<OverflowingBinaryOperator>(C)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002089 if (Exact)
2090 cast<SDivOperator>(C)->setIsExact(true);
2091 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 ID.Kind = ValID::t_Constant;
2093 return false;
2094 }
2095
2096 // Logical Operations
2097 case lltok::kw_shl:
2098 case lltok::kw_lshr:
2099 case lltok::kw_ashr:
2100 case lltok::kw_and:
2101 case lltok::kw_or:
2102 case lltok::kw_xor: {
2103 unsigned Opc = Lex.getUIntVal();
2104 Constant *Val0, *Val1;
2105 Lex.Lex();
2106 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2107 ParseGlobalTypeAndValue(Val0) ||
2108 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2109 ParseGlobalTypeAndValue(Val1) ||
2110 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2111 return true;
2112 if (Val0->getType() != Val1->getType())
2113 return Error(ID.Loc, "operands of constexpr must have same type");
2114 if (!Val0->getType()->isIntOrIntVector())
2115 return Error(ID.Loc,
2116 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002117 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002118 ID.Kind = ValID::t_Constant;
2119 return false;
2120 }
2121
2122 case lltok::kw_getelementptr:
2123 case lltok::kw_shufflevector:
2124 case lltok::kw_insertelement:
2125 case lltok::kw_extractelement:
2126 case lltok::kw_select: {
2127 unsigned Opc = Lex.getUIntVal();
2128 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002129 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002131 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002132 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2134 ParseGlobalValueVector(Elts) ||
2135 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2136 return true;
2137
2138 if (Opc == Instruction::GetElementPtr) {
2139 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2140 return Error(ID.Loc, "getelementptr requires pointer operand");
2141
2142 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002143 (Value**)(Elts.data() + 1),
2144 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002145 return Error(ID.Loc, "invalid indices for getelementptr");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002146 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
Eli Friedman4e9bac32009-07-24 21:56:17 +00002147 Elts.data() + 1, Elts.size() - 1);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002148 if (InBounds)
2149 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002150 } else if (Opc == Instruction::Select) {
2151 if (Elts.size() != 3)
2152 return Error(ID.Loc, "expected three operands to select");
2153 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2154 Elts[2]))
2155 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002156 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002157 } else if (Opc == Instruction::ShuffleVector) {
2158 if (Elts.size() != 3)
2159 return Error(ID.Loc, "expected three operands to shufflevector");
2160 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2161 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002162 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002163 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 } else if (Opc == Instruction::ExtractElement) {
2165 if (Elts.size() != 2)
2166 return Error(ID.Loc, "expected two operands to extractelement");
2167 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2168 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002169 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 } else {
2171 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2172 if (Elts.size() != 3)
2173 return Error(ID.Loc, "expected three operands to insertelement");
2174 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2175 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002176 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002177 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 }
2179
2180 ID.Kind = ValID::t_Constant;
2181 return false;
2182 }
2183 }
2184
2185 Lex.Lex();
2186 return false;
2187}
2188
2189/// ParseGlobalValue - Parse a global value with the specified type.
2190bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2191 V = 0;
2192 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002193 return ParseValID(ID) ||
2194 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002195}
2196
2197/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2198/// constant.
2199bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2200 Constant *&V) {
2201 if (isa<FunctionType>(Ty))
2202 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2203
2204 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002205 default: llvm_unreachable("Unknown ValID!");
2206 case ValID::t_Metadata:
2207 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 case ValID::t_LocalID:
2209 case ValID::t_LocalName:
2210 return Error(ID.Loc, "invalid use of function-local name");
2211 case ValID::t_InlineAsm:
2212 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2213 case ValID::t_GlobalName:
2214 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2215 return V == 0;
2216 case ValID::t_GlobalID:
2217 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2218 return V == 0;
2219 case ValID::t_APSInt:
2220 if (!isa<IntegerType>(Ty))
2221 return Error(ID.Loc, "integer constant must have integer type");
2222 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002223 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002224 return false;
2225 case ValID::t_APFloat:
2226 if (!Ty->isFloatingPoint() ||
2227 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2228 return Error(ID.Loc, "floating point constant invalid for type");
2229
2230 // The lexer has no type info, so builds all float and double FP constants
2231 // as double. Fix this here. Long double does not need this.
2232 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002233 Ty == Type::getFloatTy(Context)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 bool Ignored;
2235 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2236 &Ignored);
2237 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002238 V = ConstantFP::get(Context, ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002239
2240 if (V->getType() != Ty)
2241 return Error(ID.Loc, "floating point constant does not have type '" +
2242 Ty->getDescription() + "'");
2243
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 return false;
2245 case ValID::t_Null:
2246 if (!isa<PointerType>(Ty))
2247 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002248 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 return false;
2250 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002251 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002252 if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002253 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002254 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002255 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002257 case ValID::t_EmptyArray:
2258 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2259 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002260 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002261 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002262 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002263 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002264 if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002266 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 return false;
2268 case ValID::t_Constant:
2269 if (ID.ConstantVal->getType() != Ty)
2270 return Error(ID.Loc, "constant expression type mismatch");
2271 V = ID.ConstantVal;
2272 return false;
2273 }
2274}
2275
2276bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002277 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 return ParseType(Type) ||
2279 ParseGlobalValue(Type, V);
2280}
2281
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002282/// ParseGlobalValueVector
2283/// ::= /*empty*/
2284/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002285bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2286 // Empty list.
2287 if (Lex.getKind() == lltok::rbrace ||
2288 Lex.getKind() == lltok::rsquare ||
2289 Lex.getKind() == lltok::greater ||
2290 Lex.getKind() == lltok::rparen)
2291 return false;
2292
2293 Constant *C;
2294 if (ParseGlobalTypeAndValue(C)) return true;
2295 Elts.push_back(C);
2296
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002297 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002298 if (ParseGlobalTypeAndValue(C)) return true;
2299 Elts.push_back(C);
2300 }
2301
2302 return false;
2303}
2304
2305
2306//===----------------------------------------------------------------------===//
2307// Function Parsing.
2308//===----------------------------------------------------------------------===//
2309
2310bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2311 PerFunctionState &PFS) {
2312 if (ID.Kind == ValID::t_LocalID)
2313 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2314 else if (ID.Kind == ValID::t_LocalName)
2315 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002316 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002317 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2318 const FunctionType *FTy =
2319 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2320 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2321 return Error(ID.Loc, "invalid type for inline asm constraint string");
2322 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2323 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002324 } else if (ID.Kind == ValID::t_Metadata) {
2325 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002326 } else {
2327 Constant *C;
2328 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2329 V = C;
2330 return false;
2331 }
2332
2333 return V == 0;
2334}
2335
2336bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2337 V = 0;
2338 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002339 return ParseValID(ID) ||
2340 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002341}
2342
2343bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002344 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002345 return ParseType(T) ||
2346 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002347}
2348
2349/// FunctionHeader
2350/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2351/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2352/// OptionalAlign OptGC
2353bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2354 // Parse the linkage.
2355 LocTy LinkageLoc = Lex.getLoc();
2356 unsigned Linkage;
2357
2358 unsigned Visibility, CC, RetAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002359 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 LocTy RetTypeLoc = Lex.getLoc();
2361 if (ParseOptionalLinkage(Linkage) ||
2362 ParseOptionalVisibility(Visibility) ||
2363 ParseOptionalCallingConv(CC) ||
2364 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002365 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002366 return true;
2367
2368 // Verify that the linkage is ok.
2369 switch ((GlobalValue::LinkageTypes)Linkage) {
2370 case GlobalValue::ExternalLinkage:
2371 break; // always ok.
2372 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002373 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 if (isDefine)
2375 return Error(LinkageLoc, "invalid linkage for function definition");
2376 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002377 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002378 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002380 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002381 case GlobalValue::LinkOnceAnyLinkage:
2382 case GlobalValue::LinkOnceODRLinkage:
2383 case GlobalValue::WeakAnyLinkage:
2384 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 case GlobalValue::DLLExportLinkage:
2386 if (!isDefine)
2387 return Error(LinkageLoc, "invalid linkage for function declaration");
2388 break;
2389 case GlobalValue::AppendingLinkage:
2390 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002391 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 return Error(LinkageLoc, "invalid function linkage type");
2393 }
2394
Chris Lattner99bb3152009-01-05 08:00:30 +00002395 if (!FunctionType::isValidReturnType(RetType) ||
2396 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 return Error(RetTypeLoc, "invalid function return type");
2398
Chris Lattnerdf986172009-01-02 07:01:27 +00002399 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002400
2401 std::string FunctionName;
2402 if (Lex.getKind() == lltok::GlobalVar) {
2403 FunctionName = Lex.getStrVal();
2404 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2405 unsigned NameID = Lex.getUIntVal();
2406
2407 if (NameID != NumberedVals.size())
2408 return TokError("function expected to be numbered '%" +
2409 utostr(NumberedVals.size()) + "'");
2410 } else {
2411 return TokError("expected function name");
2412 }
2413
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002414 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002415
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002416 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002417 return TokError("expected '(' in function argument list");
2418
2419 std::vector<ArgInfo> ArgList;
2420 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002421 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002424 std::string GC;
2425
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002426 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002427 ParseOptionalAttrs(FuncAttrs, 2) ||
2428 (EatIfPresent(lltok::kw_section) &&
2429 ParseStringConstant(Section)) ||
2430 ParseOptionalAlignment(Alignment) ||
2431 (EatIfPresent(lltok::kw_gc) &&
2432 ParseStringConstant(GC)))
2433 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002434
2435 // If the alignment was parsed as an attribute, move to the alignment field.
2436 if (FuncAttrs & Attribute::Alignment) {
2437 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2438 FuncAttrs &= ~Attribute::Alignment;
2439 }
2440
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 // Okay, if we got here, the function is syntactically valid. Convert types
2442 // and do semantic checks.
2443 std::vector<const Type*> ParamTypeList;
2444 SmallVector<AttributeWithIndex, 8> Attrs;
2445 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2446 // attributes.
2447 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2448 if (FuncAttrs & ObsoleteFuncAttrs) {
2449 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2450 FuncAttrs &= ~ObsoleteFuncAttrs;
2451 }
2452
2453 if (RetAttrs != Attribute::None)
2454 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2455
2456 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2457 ParamTypeList.push_back(ArgList[i].Type);
2458 if (ArgList[i].Attrs != Attribute::None)
2459 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2460 }
2461
2462 if (FuncAttrs != Attribute::None)
2463 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2464
2465 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2466
Chris Lattnera9a9e072009-03-09 04:49:14 +00002467 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002468 RetType != Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00002469 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2470
Owen Andersonfba933c2009-07-01 23:57:11 +00002471 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002472 FunctionType::get(RetType, ParamTypeList, isVarArg);
2473 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002474
2475 Fn = 0;
2476 if (!FunctionName.empty()) {
2477 // If this was a definition of a forward reference, remove the definition
2478 // from the forward reference table and fill in the forward ref.
2479 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2480 ForwardRefVals.find(FunctionName);
2481 if (FRVI != ForwardRefVals.end()) {
2482 Fn = M->getFunction(FunctionName);
2483 ForwardRefVals.erase(FRVI);
2484 } else if ((Fn = M->getFunction(FunctionName))) {
2485 // If this function already exists in the symbol table, then it is
2486 // multiply defined. We accept a few cases for old backwards compat.
2487 // FIXME: Remove this stuff for LLVM 3.0.
2488 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2489 (!Fn->isDeclaration() && isDefine)) {
2490 // If the redefinition has different type or different attributes,
2491 // reject it. If both have bodies, reject it.
2492 return Error(NameLoc, "invalid redefinition of function '" +
2493 FunctionName + "'");
2494 } else if (Fn->isDeclaration()) {
2495 // Make sure to strip off any argument names so we can't get conflicts.
2496 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2497 AI != AE; ++AI)
2498 AI->setName("");
2499 }
2500 }
2501
2502 } else if (FunctionName.empty()) {
2503 // If this is a definition of a forward referenced function, make sure the
2504 // types agree.
2505 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2506 = ForwardRefValIDs.find(NumberedVals.size());
2507 if (I != ForwardRefValIDs.end()) {
2508 Fn = cast<Function>(I->second.first);
2509 if (Fn->getType() != PFT)
2510 return Error(NameLoc, "type of definition and forward reference of '@" +
2511 utostr(NumberedVals.size()) +"' disagree");
2512 ForwardRefValIDs.erase(I);
2513 }
2514 }
2515
2516 if (Fn == 0)
2517 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2518 else // Move the forward-reference to the correct spot in the module.
2519 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2520
2521 if (FunctionName.empty())
2522 NumberedVals.push_back(Fn);
2523
2524 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2525 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2526 Fn->setCallingConv(CC);
2527 Fn->setAttributes(PAL);
2528 Fn->setAlignment(Alignment);
2529 Fn->setSection(Section);
2530 if (!GC.empty()) Fn->setGC(GC.c_str());
2531
2532 // Add all of the arguments we parsed to the function.
2533 Function::arg_iterator ArgIt = Fn->arg_begin();
2534 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2535 // If the argument has a name, insert it into the argument symbol table.
2536 if (ArgList[i].Name.empty()) continue;
2537
2538 // Set the name, if it conflicted, it will be auto-renamed.
2539 ArgIt->setName(ArgList[i].Name);
2540
2541 if (ArgIt->getNameStr() != ArgList[i].Name)
2542 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2543 ArgList[i].Name + "'");
2544 }
2545
2546 return false;
2547}
2548
2549
2550/// ParseFunctionBody
2551/// ::= '{' BasicBlock+ '}'
2552/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2553///
2554bool LLParser::ParseFunctionBody(Function &Fn) {
2555 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2556 return TokError("expected '{' in function body");
2557 Lex.Lex(); // eat the {.
2558
2559 PerFunctionState PFS(*this, Fn);
2560
2561 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2562 if (ParseBasicBlock(PFS)) return true;
2563
2564 // Eat the }.
2565 Lex.Lex();
2566
2567 // Verify function is ok.
2568 return PFS.VerifyFunctionComplete();
2569}
2570
2571/// ParseBasicBlock
2572/// ::= LabelStr? Instruction*
2573bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2574 // If this basic block starts out with a name, remember it.
2575 std::string Name;
2576 LocTy NameLoc = Lex.getLoc();
2577 if (Lex.getKind() == lltok::LabelStr) {
2578 Name = Lex.getStrVal();
2579 Lex.Lex();
2580 }
2581
2582 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2583 if (BB == 0) return true;
2584
2585 std::string NameStr;
2586
2587 // Parse the instructions in this block until we get a terminator.
2588 Instruction *Inst;
2589 do {
2590 // This instruction may have three possibilities for a name: a) none
2591 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2592 LocTy NameLoc = Lex.getLoc();
2593 int NameID = -1;
2594 NameStr = "";
2595
2596 if (Lex.getKind() == lltok::LocalVarID) {
2597 NameID = Lex.getUIntVal();
2598 Lex.Lex();
2599 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2600 return true;
2601 } else if (Lex.getKind() == lltok::LocalVar ||
2602 // FIXME: REMOVE IN LLVM 3.0
2603 Lex.getKind() == lltok::StringConstant) {
2604 NameStr = Lex.getStrVal();
2605 Lex.Lex();
2606 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2607 return true;
2608 }
2609
2610 if (ParseInstruction(Inst, BB, PFS)) return true;
2611
2612 BB->getInstList().push_back(Inst);
2613
2614 // Set the name on the instruction.
2615 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2616 } while (!isa<TerminatorInst>(Inst));
2617
2618 return false;
2619}
2620
2621//===----------------------------------------------------------------------===//
2622// Instruction Parsing.
2623//===----------------------------------------------------------------------===//
2624
2625/// ParseInstruction - Parse one of the many different instructions.
2626///
2627bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2628 PerFunctionState &PFS) {
2629 lltok::Kind Token = Lex.getKind();
2630 if (Token == lltok::Eof)
2631 return TokError("found end of file when expecting more instructions");
2632 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002633 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 Lex.Lex(); // Eat the keyword.
2635
2636 switch (Token) {
2637 default: return Error(Loc, "expected instruction opcode");
2638 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002639 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2640 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002641 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2642 case lltok::kw_br: return ParseBr(Inst, PFS);
2643 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2644 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2645 // Binary Operators.
2646 case lltok::kw_add:
2647 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002648 case lltok::kw_mul: {
2649 bool NUW = false;
2650 bool NSW = false;
2651 LocTy ModifierLoc = Lex.getLoc();
2652 if (EatIfPresent(lltok::kw_nuw))
2653 NUW = true;
2654 if (EatIfPresent(lltok::kw_nsw)) {
2655 NSW = true;
2656 if (EatIfPresent(lltok::kw_nuw))
2657 NUW = true;
2658 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002659 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002660 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2661 if (!Result) {
2662 if (!Inst->getType()->isIntOrIntVector()) {
2663 if (NUW)
2664 return Error(ModifierLoc, "nuw only applies to integer operations");
2665 if (NSW)
2666 return Error(ModifierLoc, "nsw only applies to integer operations");
2667 }
2668 if (NUW)
Dan Gohman5078f842009-08-20 17:11:38 +00002669 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002670 if (NSW)
Dan Gohman5078f842009-08-20 17:11:38 +00002671 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002672 }
2673 return Result;
2674 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002675 case lltok::kw_fadd:
2676 case lltok::kw_fsub:
2677 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2678
Dan Gohman59858cf2009-07-27 16:11:46 +00002679 case lltok::kw_sdiv: {
2680 bool Exact = false;
2681 if (EatIfPresent(lltok::kw_exact))
2682 Exact = true;
2683 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2684 if (!Result)
2685 if (Exact)
2686 cast<SDivOperator>(Inst)->setIsExact(true);
2687 return Result;
2688 }
2689
Chris Lattnerdf986172009-01-02 07:01:27 +00002690 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002691 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002692 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002693 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002694 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002695 case lltok::kw_shl:
2696 case lltok::kw_lshr:
2697 case lltok::kw_ashr:
2698 case lltok::kw_and:
2699 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002700 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002702 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002703 // Casts.
2704 case lltok::kw_trunc:
2705 case lltok::kw_zext:
2706 case lltok::kw_sext:
2707 case lltok::kw_fptrunc:
2708 case lltok::kw_fpext:
2709 case lltok::kw_bitcast:
2710 case lltok::kw_uitofp:
2711 case lltok::kw_sitofp:
2712 case lltok::kw_fptoui:
2713 case lltok::kw_fptosi:
2714 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002715 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002716 // Other.
2717 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002718 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002719 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2720 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2721 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2722 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2723 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2724 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2725 // Memory.
2726 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002727 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 case lltok::kw_free: return ParseFree(Inst, PFS);
2729 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2730 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2731 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002732 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002734 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002736 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002737 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002738 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2739 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2740 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2741 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2742 }
2743}
2744
2745/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2746bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002747 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 switch (Lex.getKind()) {
2749 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2750 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2751 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2752 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2753 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2754 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2755 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2756 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2757 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2758 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2759 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2760 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2761 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2762 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2763 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2764 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2765 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2766 }
2767 } else {
2768 switch (Lex.getKind()) {
2769 default: TokError("expected icmp predicate (e.g. 'eq')");
2770 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2771 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2772 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2773 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2774 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2775 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2776 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2777 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2778 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2779 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2780 }
2781 }
2782 Lex.Lex();
2783 return false;
2784}
2785
2786//===----------------------------------------------------------------------===//
2787// Terminator Instructions.
2788//===----------------------------------------------------------------------===//
2789
2790/// ParseRet - Parse a return instruction.
2791/// ::= 'ret' void
2792/// ::= 'ret' TypeAndValue
2793/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2794bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2795 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002796 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002797 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002798
Owen Anderson1d0be152009-08-13 21:58:54 +00002799 if (Ty == Type::getVoidTy(Context)) {
2800 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002801 return false;
2802 }
2803
2804 Value *RV;
2805 if (ParseValue(Ty, RV, PFS)) return true;
2806
2807 // The normal case is one return value.
2808 if (Lex.getKind() == lltok::comma) {
2809 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2810 // of 'ret {i32,i32} {i32 1, i32 2}'
2811 SmallVector<Value*, 8> RVs;
2812 RVs.push_back(RV);
2813
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002814 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 if (ParseTypeAndValue(RV, PFS)) return true;
2816 RVs.push_back(RV);
2817 }
2818
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002819 RV = UndefValue::get(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002820 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2821 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2822 BB->getInstList().push_back(I);
2823 RV = I;
2824 }
2825 }
Owen Anderson1d0be152009-08-13 21:58:54 +00002826 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002827 return false;
2828}
2829
2830
2831/// ParseBr
2832/// ::= 'br' TypeAndValue
2833/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2834bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2835 LocTy Loc, Loc2;
2836 Value *Op0, *Op1, *Op2;
2837 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2838
2839 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2840 Inst = BranchInst::Create(BB);
2841 return false;
2842 }
2843
Owen Anderson1d0be152009-08-13 21:58:54 +00002844 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002845 return Error(Loc, "branch condition must have 'i1' type");
2846
2847 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2848 ParseTypeAndValue(Op1, Loc, PFS) ||
2849 ParseToken(lltok::comma, "expected ',' after true destination") ||
2850 ParseTypeAndValue(Op2, Loc2, PFS))
2851 return true;
2852
2853 if (!isa<BasicBlock>(Op1))
2854 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 if (!isa<BasicBlock>(Op2))
2856 return Error(Loc2, "true destination of branch must be a basic block");
2857
2858 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2859 return false;
2860}
2861
2862/// ParseSwitch
2863/// Instruction
2864/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2865/// JumpTable
2866/// ::= (TypeAndValue ',' TypeAndValue)*
2867bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2868 LocTy CondLoc, BBLoc;
2869 Value *Cond, *DefaultBB;
2870 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2871 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2872 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2873 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2874 return true;
2875
2876 if (!isa<IntegerType>(Cond->getType()))
2877 return Error(CondLoc, "switch condition must have integer type");
2878 if (!isa<BasicBlock>(DefaultBB))
2879 return Error(BBLoc, "default destination must be a basic block");
2880
2881 // Parse the jump table pairs.
2882 SmallPtrSet<Value*, 32> SeenCases;
2883 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2884 while (Lex.getKind() != lltok::rsquare) {
2885 Value *Constant, *DestBB;
2886
2887 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2888 ParseToken(lltok::comma, "expected ',' after case value") ||
2889 ParseTypeAndValue(DestBB, BBLoc, PFS))
2890 return true;
2891
2892 if (!SeenCases.insert(Constant))
2893 return Error(CondLoc, "duplicate case value in switch");
2894 if (!isa<ConstantInt>(Constant))
2895 return Error(CondLoc, "case value is not a constant integer");
2896 if (!isa<BasicBlock>(DestBB))
2897 return Error(BBLoc, "case destination is not a basic block");
2898
2899 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2900 cast<BasicBlock>(DestBB)));
2901 }
2902
2903 Lex.Lex(); // Eat the ']'.
2904
2905 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2906 Table.size());
2907 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2908 SI->addCase(Table[i].first, Table[i].second);
2909 Inst = SI;
2910 return false;
2911}
2912
2913/// ParseInvoke
2914/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2915/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2916bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2917 LocTy CallLoc = Lex.getLoc();
2918 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00002919 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 LocTy RetTypeLoc;
2921 ValID CalleeID;
2922 SmallVector<ParamInfo, 16> ArgList;
2923
2924 Value *NormalBB, *UnwindBB;
2925 if (ParseOptionalCallingConv(CC) ||
2926 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002927 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 ParseValID(CalleeID) ||
2929 ParseParameterList(ArgList, PFS) ||
2930 ParseOptionalAttrs(FnAttrs, 2) ||
2931 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2932 ParseTypeAndValue(NormalBB, PFS) ||
2933 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2934 ParseTypeAndValue(UnwindBB, PFS))
2935 return true;
2936
2937 if (!isa<BasicBlock>(NormalBB))
2938 return Error(CallLoc, "normal destination is not a basic block");
2939 if (!isa<BasicBlock>(UnwindBB))
2940 return Error(CallLoc, "unwind destination is not a basic block");
2941
2942 // If RetType is a non-function pointer type, then this is the short syntax
2943 // for the call, which means that RetType is just the return type. Infer the
2944 // rest of the function argument types from the arguments that are present.
2945 const PointerType *PFTy = 0;
2946 const FunctionType *Ty = 0;
2947 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2948 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2949 // Pull out the types of all of the arguments...
2950 std::vector<const Type*> ParamTypes;
2951 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2952 ParamTypes.push_back(ArgList[i].V->getType());
2953
2954 if (!FunctionType::isValidReturnType(RetType))
2955 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2956
Owen Andersondebcb012009-07-29 22:17:13 +00002957 Ty = FunctionType::get(RetType, ParamTypes, false);
2958 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002959 }
2960
2961 // Look up the callee.
2962 Value *Callee;
2963 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2964
2965 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2966 // function attributes.
2967 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2968 if (FnAttrs & ObsoleteFuncAttrs) {
2969 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2970 FnAttrs &= ~ObsoleteFuncAttrs;
2971 }
2972
2973 // Set up the Attributes for the function.
2974 SmallVector<AttributeWithIndex, 8> Attrs;
2975 if (RetAttrs != Attribute::None)
2976 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2977
2978 SmallVector<Value*, 8> Args;
2979
2980 // Loop through FunctionType's arguments and ensure they are specified
2981 // correctly. Also, gather any parameter attributes.
2982 FunctionType::param_iterator I = Ty->param_begin();
2983 FunctionType::param_iterator E = Ty->param_end();
2984 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2985 const Type *ExpectedTy = 0;
2986 if (I != E) {
2987 ExpectedTy = *I++;
2988 } else if (!Ty->isVarArg()) {
2989 return Error(ArgList[i].Loc, "too many arguments specified");
2990 }
2991
2992 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2993 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2994 ExpectedTy->getDescription() + "'");
2995 Args.push_back(ArgList[i].V);
2996 if (ArgList[i].Attrs != Attribute::None)
2997 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2998 }
2999
3000 if (I != E)
3001 return Error(CallLoc, "not enough parameters specified for call");
3002
3003 if (FnAttrs != Attribute::None)
3004 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3005
3006 // Finish off the Attributes and check them
3007 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3008
3009 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3010 cast<BasicBlock>(UnwindBB),
3011 Args.begin(), Args.end());
3012 II->setCallingConv(CC);
3013 II->setAttributes(PAL);
3014 Inst = II;
3015 return false;
3016}
3017
3018
3019
3020//===----------------------------------------------------------------------===//
3021// Binary Operators.
3022//===----------------------------------------------------------------------===//
3023
3024/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003025/// ::= ArithmeticOps TypeAndValue ',' Value
3026///
3027/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3028/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003029bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003030 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003031 LocTy Loc; Value *LHS, *RHS;
3032 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3033 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3034 ParseValue(LHS->getType(), RHS, PFS))
3035 return true;
3036
Chris Lattnere914b592009-01-05 08:24:46 +00003037 bool Valid;
3038 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003039 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003040 case 0: // int or FP.
3041 Valid = LHS->getType()->isIntOrIntVector() ||
3042 LHS->getType()->isFPOrFPVector();
3043 break;
3044 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3045 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3046 }
3047
3048 if (!Valid)
3049 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00003050
3051 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3052 return false;
3053}
3054
3055/// ParseLogical
3056/// ::= ArithmeticOps TypeAndValue ',' Value {
3057bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3058 unsigned Opc) {
3059 LocTy Loc; Value *LHS, *RHS;
3060 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3061 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3062 ParseValue(LHS->getType(), RHS, PFS))
3063 return true;
3064
3065 if (!LHS->getType()->isIntOrIntVector())
3066 return Error(Loc,"instruction requires integer or integer vector operands");
3067
3068 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3069 return false;
3070}
3071
3072
3073/// ParseCompare
3074/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3075/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003076bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3077 unsigned Opc) {
3078 // Parse the integer/fp comparison predicate.
3079 LocTy Loc;
3080 unsigned Pred;
3081 Value *LHS, *RHS;
3082 if (ParseCmpPredicate(Pred, Opc) ||
3083 ParseTypeAndValue(LHS, Loc, PFS) ||
3084 ParseToken(lltok::comma, "expected ',' after compare value") ||
3085 ParseValue(LHS->getType(), RHS, PFS))
3086 return true;
3087
3088 if (Opc == Instruction::FCmp) {
3089 if (!LHS->getType()->isFPOrFPVector())
3090 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003091 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003092 } else {
3093 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 if (!LHS->getType()->isIntOrIntVector() &&
3095 !isa<PointerType>(LHS->getType()))
3096 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003097 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 }
3099 return false;
3100}
3101
3102//===----------------------------------------------------------------------===//
3103// Other Instructions.
3104//===----------------------------------------------------------------------===//
3105
3106
3107/// ParseCast
3108/// ::= CastOpc TypeAndValue 'to' Type
3109bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3110 unsigned Opc) {
3111 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003112 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003113 if (ParseTypeAndValue(Op, Loc, PFS) ||
3114 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3115 ParseType(DestTy))
3116 return true;
3117
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003118 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3119 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003120 return Error(Loc, "invalid cast opcode for cast from '" +
3121 Op->getType()->getDescription() + "' to '" +
3122 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003123 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3125 return false;
3126}
3127
3128/// ParseSelect
3129/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3130bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3131 LocTy Loc;
3132 Value *Op0, *Op1, *Op2;
3133 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3134 ParseToken(lltok::comma, "expected ',' after select condition") ||
3135 ParseTypeAndValue(Op1, PFS) ||
3136 ParseToken(lltok::comma, "expected ',' after select value") ||
3137 ParseTypeAndValue(Op2, PFS))
3138 return true;
3139
3140 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3141 return Error(Loc, Reason);
3142
3143 Inst = SelectInst::Create(Op0, Op1, Op2);
3144 return false;
3145}
3146
Chris Lattner0088a5c2009-01-05 08:18:44 +00003147/// ParseVA_Arg
3148/// ::= 'va_arg' TypeAndValue ',' Type
3149bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003151 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003152 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003153 if (ParseTypeAndValue(Op, PFS) ||
3154 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003155 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003156 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003157
3158 if (!EltTy->isFirstClassType())
3159 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003160
3161 Inst = new VAArgInst(Op, EltTy);
3162 return false;
3163}
3164
3165/// ParseExtractElement
3166/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3167bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3168 LocTy Loc;
3169 Value *Op0, *Op1;
3170 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3171 ParseToken(lltok::comma, "expected ',' after extract value") ||
3172 ParseTypeAndValue(Op1, PFS))
3173 return true;
3174
3175 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3176 return Error(Loc, "invalid extractelement operands");
3177
Eric Christophera3500da2009-07-25 02:28:41 +00003178 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 return false;
3180}
3181
3182/// ParseInsertElement
3183/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3184bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3185 LocTy Loc;
3186 Value *Op0, *Op1, *Op2;
3187 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3188 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3189 ParseTypeAndValue(Op1, PFS) ||
3190 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3191 ParseTypeAndValue(Op2, PFS))
3192 return true;
3193
3194 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003195 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003196
3197 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3198 return false;
3199}
3200
3201/// ParseShuffleVector
3202/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3203bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3204 LocTy Loc;
3205 Value *Op0, *Op1, *Op2;
3206 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3207 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3208 ParseTypeAndValue(Op1, PFS) ||
3209 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3210 ParseTypeAndValue(Op2, PFS))
3211 return true;
3212
3213 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3214 return Error(Loc, "invalid extractelement operands");
3215
3216 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3217 return false;
3218}
3219
3220/// ParsePHI
3221/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3222bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003223 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 Value *Op0, *Op1;
3225 LocTy TypeLoc = Lex.getLoc();
3226
3227 if (ParseType(Ty) ||
3228 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3229 ParseValue(Ty, Op0, PFS) ||
3230 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003231 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3233 return true;
3234
3235 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3236 while (1) {
3237 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3238
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003239 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 break;
3241
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003242 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 ParseValue(Ty, Op0, PFS) ||
3244 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003245 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003246 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3247 return true;
3248 }
3249
3250 if (!Ty->isFirstClassType())
3251 return Error(TypeLoc, "phi node must have first class type");
3252
3253 PHINode *PN = PHINode::Create(Ty);
3254 PN->reserveOperandSpace(PHIVals.size());
3255 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3256 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3257 Inst = PN;
3258 return false;
3259}
3260
3261/// ParseCall
3262/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3263/// ParameterList OptionalAttrs
3264bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3265 bool isTail) {
3266 unsigned CC, RetAttrs, FnAttrs;
Owen Anderson1d0be152009-08-13 21:58:54 +00003267 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 LocTy RetTypeLoc;
3269 ValID CalleeID;
3270 SmallVector<ParamInfo, 16> ArgList;
3271 LocTy CallLoc = Lex.getLoc();
3272
3273 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3274 ParseOptionalCallingConv(CC) ||
3275 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003276 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 ParseValID(CalleeID) ||
3278 ParseParameterList(ArgList, PFS) ||
3279 ParseOptionalAttrs(FnAttrs, 2))
3280 return true;
3281
3282 // If RetType is a non-function pointer type, then this is the short syntax
3283 // for the call, which means that RetType is just the return type. Infer the
3284 // rest of the function argument types from the arguments that are present.
3285 const PointerType *PFTy = 0;
3286 const FunctionType *Ty = 0;
3287 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3288 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3289 // Pull out the types of all of the arguments...
3290 std::vector<const Type*> ParamTypes;
3291 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3292 ParamTypes.push_back(ArgList[i].V->getType());
3293
3294 if (!FunctionType::isValidReturnType(RetType))
3295 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3296
Owen Andersondebcb012009-07-29 22:17:13 +00003297 Ty = FunctionType::get(RetType, ParamTypes, false);
3298 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003299 }
3300
3301 // Look up the callee.
3302 Value *Callee;
3303 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3304
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3306 // function attributes.
3307 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3308 if (FnAttrs & ObsoleteFuncAttrs) {
3309 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3310 FnAttrs &= ~ObsoleteFuncAttrs;
3311 }
3312
3313 // Set up the Attributes for the function.
3314 SmallVector<AttributeWithIndex, 8> Attrs;
3315 if (RetAttrs != Attribute::None)
3316 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3317
3318 SmallVector<Value*, 8> Args;
3319
3320 // Loop through FunctionType's arguments and ensure they are specified
3321 // correctly. Also, gather any parameter attributes.
3322 FunctionType::param_iterator I = Ty->param_begin();
3323 FunctionType::param_iterator E = Ty->param_end();
3324 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3325 const Type *ExpectedTy = 0;
3326 if (I != E) {
3327 ExpectedTy = *I++;
3328 } else if (!Ty->isVarArg()) {
3329 return Error(ArgList[i].Loc, "too many arguments specified");
3330 }
3331
3332 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3333 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3334 ExpectedTy->getDescription() + "'");
3335 Args.push_back(ArgList[i].V);
3336 if (ArgList[i].Attrs != Attribute::None)
3337 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3338 }
3339
3340 if (I != E)
3341 return Error(CallLoc, "not enough parameters specified for call");
3342
3343 if (FnAttrs != Attribute::None)
3344 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3345
3346 // Finish off the Attributes and check them
3347 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3348
3349 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3350 CI->setTailCall(isTail);
3351 CI->setCallingConv(CC);
3352 CI->setAttributes(PAL);
3353 Inst = CI;
3354 return false;
3355}
3356
3357//===----------------------------------------------------------------------===//
3358// Memory Instructions.
3359//===----------------------------------------------------------------------===//
3360
3361/// ParseAlloc
3362/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3363/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3364bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3365 unsigned Opc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003366 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003368 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003369 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003370 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003371
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003372 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 if (Lex.getKind() == lltok::kw_align) {
3374 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003375 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3376 ParseOptionalCommaAlignment(Alignment)) {
3377 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 }
3379 }
3380
Owen Anderson1d0be152009-08-13 21:58:54 +00003381 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 return Error(SizeLoc, "element count must be i32");
3383
3384 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003385 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 else
Owen Anderson50dead02009-07-15 23:53:25 +00003387 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 return false;
3389}
3390
3391/// ParseFree
3392/// ::= 'free' TypeAndValue
3393bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3394 Value *Val; LocTy Loc;
3395 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3396 if (!isa<PointerType>(Val->getType()))
3397 return Error(Loc, "operand to free must be a pointer");
3398 Inst = new FreeInst(Val);
3399 return false;
3400}
3401
3402/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003403/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003404bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3405 bool isVolatile) {
3406 Value *Val; LocTy Loc;
3407 unsigned Alignment;
3408 if (ParseTypeAndValue(Val, Loc, PFS) ||
3409 ParseOptionalCommaAlignment(Alignment))
3410 return true;
3411
3412 if (!isa<PointerType>(Val->getType()) ||
3413 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3414 return Error(Loc, "load operand must be a pointer to a first class type");
3415
3416 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3417 return false;
3418}
3419
3420/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003421/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003422bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3423 bool isVolatile) {
3424 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3425 unsigned Alignment;
3426 if (ParseTypeAndValue(Val, Loc, PFS) ||
3427 ParseToken(lltok::comma, "expected ',' after store operand") ||
3428 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3429 ParseOptionalCommaAlignment(Alignment))
3430 return true;
3431
3432 if (!isa<PointerType>(Ptr->getType()))
3433 return Error(PtrLoc, "store operand must be a pointer");
3434 if (!Val->getType()->isFirstClassType())
3435 return Error(Loc, "store operand must be a first class value");
3436 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3437 return Error(Loc, "stored value and pointer type do not match");
3438
3439 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3440 return false;
3441}
3442
3443/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003444/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003445/// FIXME: Remove support for getresult in LLVM 3.0
3446bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3447 Value *Val; LocTy ValLoc, EltLoc;
3448 unsigned Element;
3449 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3450 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003451 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 return true;
3453
3454 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3455 return Error(ValLoc, "getresult inst requires an aggregate operand");
3456 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3457 return Error(EltLoc, "invalid getresult index for value");
3458 Inst = ExtractValueInst::Create(Val, Element);
3459 return false;
3460}
3461
3462/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003463/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003464bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3465 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003466
Dan Gohmandcb40a32009-07-29 15:58:36 +00003467 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003468
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003469 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003470
3471 if (!isa<PointerType>(Ptr->getType()))
3472 return Error(Loc, "base of getelementptr must be a pointer");
3473
3474 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003475 while (EatIfPresent(lltok::comma)) {
3476 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 if (!isa<IntegerType>(Val->getType()))
3478 return Error(EltLoc, "getelementptr index must be an integer");
3479 Indices.push_back(Val);
3480 }
3481
3482 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3483 Indices.begin(), Indices.end()))
3484 return Error(Loc, "invalid getelementptr indices");
3485 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003486 if (InBounds)
3487 cast<GEPOperator>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003488 return false;
3489}
3490
3491/// ParseExtractValue
3492/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3493bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3494 Value *Val; LocTy Loc;
3495 SmallVector<unsigned, 4> Indices;
3496 if (ParseTypeAndValue(Val, Loc, PFS) ||
3497 ParseIndexList(Indices))
3498 return true;
3499
3500 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3501 return Error(Loc, "extractvalue operand must be array or struct");
3502
3503 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3504 Indices.end()))
3505 return Error(Loc, "invalid indices for extractvalue");
3506 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3507 return false;
3508}
3509
3510/// ParseInsertValue
3511/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3512bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3513 Value *Val0, *Val1; LocTy Loc0, Loc1;
3514 SmallVector<unsigned, 4> Indices;
3515 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3516 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3517 ParseTypeAndValue(Val1, Loc1, PFS) ||
3518 ParseIndexList(Indices))
3519 return true;
3520
3521 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3522 return Error(Loc0, "extractvalue operand must be array or struct");
3523
3524 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3525 Indices.end()))
3526 return Error(Loc0, "invalid indices for insertvalue");
3527 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3528 return false;
3529}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003530
3531//===----------------------------------------------------------------------===//
3532// Embedded metadata.
3533//===----------------------------------------------------------------------===//
3534
3535/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003536/// ::= Element (',' Element)*
3537/// Element
3538/// ::= 'null' | TypeAndValue
3539bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003540 assert(Lex.getKind() == lltok::lbrace);
3541 Lex.Lex();
3542 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003543 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003544 if (Lex.getKind() == lltok::kw_null) {
3545 Lex.Lex();
3546 V = 0;
3547 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003548 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003549 if (ParseType(Ty)) return true;
3550 if (Lex.getKind() == lltok::Metadata) {
3551 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003552 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003553 if (!ParseMDNode(Node))
3554 V = Node;
3555 else {
3556 MetadataBase *MDS = 0;
3557 if (ParseMDString(MDS)) return true;
3558 V = MDS;
3559 }
3560 } else {
3561 Constant *C;
3562 if (ParseGlobalValue(Ty, C)) return true;
3563 V = C;
3564 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003565 }
3566 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003567 } while (EatIfPresent(lltok::comma));
3568
3569 return false;
3570}