blob: 3c125a01b19d6bf028a5630d281e021088dbdfcf [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
Devang Patele4b27562009-08-28 23:24:31 +0000101 // Check debug info intrinsics.
102 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 return false;
104}
105
106//===----------------------------------------------------------------------===//
107// Top-Level Entities
108//===----------------------------------------------------------------------===//
109
110bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000111 while (1) {
112 switch (Lex.getKind()) {
113 default: return TokError("expected top-level entity");
114 case lltok::Eof: return false;
115 //case lltok::kw_define:
116 case lltok::kw_declare: if (ParseDeclare()) return true; break;
117 case lltok::kw_define: if (ParseDefine()) return true; break;
118 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
119 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
120 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
121 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000122 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
124 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000125 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000126 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000127 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Pateleff2ab62009-07-29 00:34:02 +0000128 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000129
130 // The Global variable production with no name can have many different
131 // optional leading prefixes, the production is:
132 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
133 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000134 case lltok::kw_private : // OptionalLinkage
135 case lltok::kw_linker_private: // OptionalLinkage
136 case lltok::kw_internal: // OptionalLinkage
137 case lltok::kw_weak: // OptionalLinkage
138 case lltok::kw_weak_odr: // OptionalLinkage
139 case lltok::kw_linkonce: // OptionalLinkage
140 case lltok::kw_linkonce_odr: // OptionalLinkage
141 case lltok::kw_appending: // OptionalLinkage
142 case lltok::kw_dllexport: // OptionalLinkage
143 case lltok::kw_common: // OptionalLinkage
144 case lltok::kw_dllimport: // OptionalLinkage
145 case lltok::kw_extern_weak: // OptionalLinkage
146 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000147 unsigned Linkage, Visibility;
148 if (ParseOptionalLinkage(Linkage) ||
149 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000150 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000151 return true;
152 break;
153 }
154 case lltok::kw_default: // OptionalVisibility
155 case lltok::kw_hidden: // OptionalVisibility
156 case lltok::kw_protected: { // OptionalVisibility
157 unsigned Visibility;
158 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000159 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000160 return true;
161 break;
162 }
163
164 case lltok::kw_thread_local: // OptionalThreadLocal
165 case lltok::kw_addrspace: // OptionalAddrSpace
166 case lltok::kw_constant: // GlobalType
167 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000168 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 break;
170 }
171 }
172}
173
174
175/// toplevelentity
176/// ::= 'module' 'asm' STRINGCONSTANT
177bool LLParser::ParseModuleAsm() {
178 assert(Lex.getKind() == lltok::kw_module);
179 Lex.Lex();
180
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000181 std::string AsmStr;
182 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
183 ParseStringConstant(AsmStr)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000184
185 const std::string &AsmSoFar = M->getModuleInlineAsm();
186 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000187 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000188 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000189 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 return false;
191}
192
193/// toplevelentity
194/// ::= 'target' 'triple' '=' STRINGCONSTANT
195/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
196bool LLParser::ParseTargetDefinition() {
197 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000198 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 switch (Lex.Lex()) {
200 default: return TokError("unknown target property");
201 case lltok::kw_triple:
202 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000203 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
204 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return false;
208 case lltok::kw_datalayout:
209 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000210 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
211 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000213 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 return false;
215 }
216}
217
218/// toplevelentity
219/// ::= 'deplibs' '=' '[' ']'
220/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
221bool LLParser::ParseDepLibs() {
222 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000223 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000224 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
225 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
226 return true;
227
228 if (EatIfPresent(lltok::rsquare))
229 return false;
230
231 std::string Str;
232 if (ParseStringConstant(Str)) return true;
233 M->addLibrary(Str);
234
235 while (EatIfPresent(lltok::comma)) {
236 if (ParseStringConstant(Str)) return true;
237 M->addLibrary(Str);
238 }
239
240 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000241}
242
Dan Gohman3845e502009-08-12 23:32:33 +0000243/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000244/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000245/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000246bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000247 unsigned TypeID = NumberedTypes.size();
248
249 // Handle the LocalVarID form.
250 if (Lex.getKind() == lltok::LocalVarID) {
251 if (Lex.getUIntVal() != TypeID)
252 return Error(Lex.getLoc(), "type expected to be numbered '%" +
253 utostr(TypeID) + "'");
254 Lex.Lex(); // eat LocalVarID;
255
256 if (ParseToken(lltok::equal, "expected '=' after name"))
257 return true;
258 }
259
Chris Lattnerdf986172009-01-02 07:01:27 +0000260 assert(Lex.getKind() == lltok::kw_type);
261 LocTy TypeLoc = Lex.getLoc();
262 Lex.Lex(); // eat kw_type
263
Owen Anderson1d0be152009-08-13 21:58:54 +0000264 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000265 if (ParseType(Ty)) return true;
266
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 // See if this type was previously referenced.
268 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
269 FI = ForwardRefTypeIDs.find(TypeID);
270 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000271 if (FI->second.first.get() == Ty)
272 return Error(TypeLoc, "self referential type is invalid");
273
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
275 Ty = FI->second.first.get();
276 ForwardRefTypeIDs.erase(FI);
277 }
278
279 NumberedTypes.push_back(Ty);
280
281 return false;
282}
283
284/// toplevelentity
285/// ::= LocalVar '=' 'type' type
286bool LLParser::ParseNamedType() {
287 std::string Name = Lex.getStrVal();
288 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000289 Lex.Lex(); // eat LocalVar.
Chris Lattnerdf986172009-01-02 07:01:27 +0000290
Owen Anderson1d0be152009-08-13 21:58:54 +0000291 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000292
293 if (ParseToken(lltok::equal, "expected '=' after name") ||
294 ParseToken(lltok::kw_type, "expected 'type' after name") ||
295 ParseType(Ty))
296 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000297
Chris Lattnerdf986172009-01-02 07:01:27 +0000298 // Set the type name, checking for conflicts as we do so.
299 bool AlreadyExists = M->addTypeName(Name, Ty);
300 if (!AlreadyExists) return false;
301
302 // See if this type is a forward reference. We need to eagerly resolve
303 // types to allow recursive type redefinitions below.
304 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
305 FI = ForwardRefTypes.find(Name);
306 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000307 if (FI->second.first.get() == Ty)
308 return Error(NameLoc, "self referential type is invalid");
309
Chris Lattnerdf986172009-01-02 07:01:27 +0000310 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
311 Ty = FI->second.first.get();
312 ForwardRefTypes.erase(FI);
313 }
314
315 // Inserting a name that is already defined, get the existing name.
316 const Type *Existing = M->getTypeByName(Name);
317 assert(Existing && "Conflict but no matching type?!");
318
319 // Otherwise, this is an attempt to redefine a type. That's okay if
320 // the redefinition is identical to the original.
321 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
322 if (Existing == Ty) return false;
323
324 // Any other kind of (non-equivalent) redefinition is an error.
325 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
326 Ty->getDescription() + "'");
327}
328
329
330/// toplevelentity
331/// ::= 'declare' FunctionHeader
332bool LLParser::ParseDeclare() {
333 assert(Lex.getKind() == lltok::kw_declare);
334 Lex.Lex();
335
336 Function *F;
337 return ParseFunctionHeader(F, false);
338}
339
340/// toplevelentity
341/// ::= 'define' FunctionHeader '{' ...
342bool LLParser::ParseDefine() {
343 assert(Lex.getKind() == lltok::kw_define);
344 Lex.Lex();
345
346 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000347 return ParseFunctionHeader(F, true) ||
348 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000349}
350
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000351/// ParseGlobalType
352/// ::= 'constant'
353/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000354bool LLParser::ParseGlobalType(bool &IsConstant) {
355 if (Lex.getKind() == lltok::kw_constant)
356 IsConstant = true;
357 else if (Lex.getKind() == lltok::kw_global)
358 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000359 else {
360 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000361 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000362 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 Lex.Lex();
364 return false;
365}
366
Dan Gohman3845e502009-08-12 23:32:33 +0000367/// ParseUnnamedGlobal:
368/// OptionalVisibility ALIAS ...
369/// OptionalLinkage OptionalVisibility ... -> global variable
370/// GlobalID '=' OptionalVisibility ALIAS ...
371/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
372bool LLParser::ParseUnnamedGlobal() {
373 unsigned VarID = NumberedVals.size();
374 std::string Name;
375 LocTy NameLoc = Lex.getLoc();
376
377 // Handle the GlobalID form.
378 if (Lex.getKind() == lltok::GlobalID) {
379 if (Lex.getUIntVal() != VarID)
380 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
381 utostr(VarID) + "'");
382 Lex.Lex(); // eat GlobalID;
383
384 if (ParseToken(lltok::equal, "expected '=' after name"))
385 return true;
386 }
387
388 bool HasLinkage;
389 unsigned Linkage, Visibility;
390 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
391 ParseOptionalVisibility(Visibility))
392 return true;
393
394 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
395 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
396 return ParseAlias(Name, NameLoc, Visibility);
397}
398
Chris Lattnerdf986172009-01-02 07:01:27 +0000399/// ParseNamedGlobal:
400/// GlobalVar '=' OptionalVisibility ALIAS ...
401/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
402bool LLParser::ParseNamedGlobal() {
403 assert(Lex.getKind() == lltok::GlobalVar);
404 LocTy NameLoc = Lex.getLoc();
405 std::string Name = Lex.getStrVal();
406 Lex.Lex();
407
408 bool HasLinkage;
409 unsigned Linkage, Visibility;
410 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
411 ParseOptionalLinkage(Linkage, HasLinkage) ||
412 ParseOptionalVisibility(Visibility))
413 return true;
414
415 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
416 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
417 return ParseAlias(Name, NameLoc, Visibility);
418}
419
Devang Patel256be962009-07-20 19:00:08 +0000420// MDString:
421// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000422bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000423 std::string Str;
424 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000425 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000426 return false;
427}
428
429// MDNode:
430// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000431bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000432 // !{ ..., !42, ... }
433 unsigned MID = 0;
434 if (ParseUInt32(MID)) return true;
435
436 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000437 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000438 if (I != MetadataCache.end()) {
439 Node = I->second;
440 return false;
441 }
442
443 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000444 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000445 FI = ForwardRefMDNodes.find(MID);
446 if (FI != ForwardRefMDNodes.end()) {
447 Node = FI->second.first;
448 return false;
449 }
450
451 // Create MDNode forward reference
452 SmallVector<Value *, 1> Elts;
453 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000454 Elts.push_back(MDString::get(Context, FwdRefName));
455 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000456 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
457 Node = FwdNode;
458 return false;
459}
460
Devang Pateleff2ab62009-07-29 00:34:02 +0000461///ParseNamedMetadata:
462/// !foo = !{ !1, !2 }
463bool LLParser::ParseNamedMetadata() {
464 assert(Lex.getKind() == lltok::NamedMD);
465 Lex.Lex();
466 std::string Name = Lex.getStrVal();
467
468 if (ParseToken(lltok::equal, "expected '=' here"))
469 return true;
470
471 if (Lex.getKind() != lltok::Metadata)
472 return TokError("Expected '!' here");
473 Lex.Lex();
474
475 if (Lex.getKind() != lltok::lbrace)
476 return TokError("Expected '{' here");
477 Lex.Lex();
478 SmallVector<MetadataBase *, 8> Elts;
479 do {
480 if (Lex.getKind() != lltok::Metadata)
481 return TokError("Expected '!' here");
482 Lex.Lex();
483 MetadataBase *N = 0;
484 if (ParseMDNode(N)) return true;
485 Elts.push_back(N);
486 } while (EatIfPresent(lltok::comma));
487
488 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
489 return true;
490
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000492 return false;
493}
494
Devang Patel923078c2009-07-01 19:21:12 +0000495/// ParseStandaloneMetadata:
496/// !42 = !{...}
497bool LLParser::ParseStandaloneMetadata() {
498 assert(Lex.getKind() == lltok::Metadata);
499 Lex.Lex();
500 unsigned MetadataID = 0;
501 if (ParseUInt32(MetadataID))
502 return true;
503 if (MetadataCache.find(MetadataID) != MetadataCache.end())
504 return TokError("Metadata id is already used");
505 if (ParseToken(lltok::equal, "expected '=' here"))
506 return true;
507
508 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000509 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000510 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000511 return true;
512
Devang Patel104cf9e2009-07-23 01:07:34 +0000513 if (Lex.getKind() != lltok::Metadata)
514 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000515
Devang Patel104cf9e2009-07-23 01:07:34 +0000516 Lex.Lex();
517 if (Lex.getKind() != lltok::lbrace)
518 return TokError("Expected '{' here");
519
520 SmallVector<Value *, 16> Elts;
521 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000522 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000523 return true;
524
Owen Anderson647e3012009-07-31 21:35:40 +0000525 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000526 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000527 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000528 FI = ForwardRefMDNodes.find(MetadataID);
529 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000530 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000531 FwdNode->replaceAllUsesWith(Init);
532 ForwardRefMDNodes.erase(FI);
533 }
534
Devang Patel923078c2009-07-01 19:21:12 +0000535 return false;
536}
537
Chris Lattnerdf986172009-01-02 07:01:27 +0000538/// ParseAlias:
539/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
540/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000541/// ::= TypeAndValue
542/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000543/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000544///
545/// Everything through visibility has already been parsed.
546///
547bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
548 unsigned Visibility) {
549 assert(Lex.getKind() == lltok::kw_alias);
550 Lex.Lex();
551 unsigned Linkage;
552 LocTy LinkageLoc = Lex.getLoc();
553 if (ParseOptionalLinkage(Linkage))
554 return true;
555
556 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000557 Linkage != GlobalValue::WeakAnyLinkage &&
558 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000559 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000560 Linkage != GlobalValue::PrivateLinkage &&
561 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000562 return Error(LinkageLoc, "invalid linkage type for alias");
563
564 Constant *Aliasee;
565 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000566 if (Lex.getKind() != lltok::kw_bitcast &&
567 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000568 if (ParseGlobalTypeAndValue(Aliasee)) return true;
569 } else {
570 // The bitcast dest type is not present, it is implied by the dest type.
571 ValID ID;
572 if (ParseValID(ID)) return true;
573 if (ID.Kind != ValID::t_Constant)
574 return Error(AliaseeLoc, "invalid aliasee");
575 Aliasee = ID.ConstantVal;
576 }
577
578 if (!isa<PointerType>(Aliasee->getType()))
579 return Error(AliaseeLoc, "alias must have pointer type");
580
581 // Okay, create the alias but do not insert it into the module yet.
582 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
583 (GlobalValue::LinkageTypes)Linkage, Name,
584 Aliasee);
585 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
586
587 // See if this value already exists in the symbol table. If so, it is either
588 // a redefinition or a definition of a forward reference.
589 if (GlobalValue *Val =
590 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
591 // See if this was a redefinition. If so, there is no entry in
592 // ForwardRefVals.
593 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
594 I = ForwardRefVals.find(Name);
595 if (I == ForwardRefVals.end())
596 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
597
598 // Otherwise, this was a definition of forward ref. Verify that types
599 // agree.
600 if (Val->getType() != GA->getType())
601 return Error(NameLoc,
602 "forward reference and definition of alias have different types");
603
604 // If they agree, just RAUW the old value with the alias and remove the
605 // forward ref info.
606 Val->replaceAllUsesWith(GA);
607 Val->eraseFromParent();
608 ForwardRefVals.erase(I);
609 }
610
611 // Insert into the module, we know its name won't collide now.
612 M->getAliasList().push_back(GA);
613 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
614
615 return false;
616}
617
618/// ParseGlobal
619/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
620/// OptionalAddrSpace GlobalType Type Const
621/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
622/// OptionalAddrSpace GlobalType Type Const
623///
624/// Everything through visibility has been parsed already.
625///
626bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
627 unsigned Linkage, bool HasLinkage,
628 unsigned Visibility) {
629 unsigned AddrSpace;
630 bool ThreadLocal, IsConstant;
631 LocTy TyLoc;
632
Owen Anderson1d0be152009-08-13 21:58:54 +0000633 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000634 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
635 ParseOptionalAddrSpace(AddrSpace) ||
636 ParseGlobalType(IsConstant) ||
637 ParseType(Ty, TyLoc))
638 return true;
639
640 // If the linkage is specified and is external, then no initializer is
641 // present.
642 Constant *Init = 0;
643 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000644 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000645 Linkage != GlobalValue::ExternalLinkage)) {
646 if (ParseGlobalValue(Ty, Init))
647 return true;
648 }
649
Owen Anderson1d0be152009-08-13 21:58:54 +0000650 if (isa<FunctionType>(Ty) || Ty == Type::getLabelTy(Context))
Chris Lattner4a2f1122009-02-08 20:00:15 +0000651 return Error(TyLoc, "invalid type for global variable");
Chris Lattnerdf986172009-01-02 07:01:27 +0000652
653 GlobalVariable *GV = 0;
654
655 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000656 if (!Name.empty()) {
657 if ((GV = M->getGlobalVariable(Name, true)) &&
658 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 return Error(NameLoc, "redefinition of global '@" + Name + "'");
660 } else {
661 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
662 I = ForwardRefValIDs.find(NumberedVals.size());
663 if (I != ForwardRefValIDs.end()) {
664 GV = cast<GlobalVariable>(I->second.first);
665 ForwardRefValIDs.erase(I);
666 }
667 }
668
669 if (GV == 0) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000670 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
671 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 } else {
673 if (GV->getType()->getElementType() != Ty)
674 return Error(TyLoc,
675 "forward reference and definition of global have different types");
676
677 // Move the forward-reference to the correct spot in the module.
678 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
679 }
680
681 if (Name.empty())
682 NumberedVals.push_back(GV);
683
684 // Set the parsed properties on the global.
685 if (Init)
686 GV->setInitializer(Init);
687 GV->setConstant(IsConstant);
688 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
689 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
690 GV->setThreadLocal(ThreadLocal);
691
692 // Parse attributes on the global.
693 while (Lex.getKind() == lltok::comma) {
694 Lex.Lex();
695
696 if (Lex.getKind() == lltok::kw_section) {
697 Lex.Lex();
698 GV->setSection(Lex.getStrVal());
699 if (ParseToken(lltok::StringConstant, "expected global section string"))
700 return true;
701 } else if (Lex.getKind() == lltok::kw_align) {
702 unsigned Alignment;
703 if (ParseOptionalAlignment(Alignment)) return true;
704 GV->setAlignment(Alignment);
705 } else {
706 TokError("unknown global variable property!");
707 }
708 }
709
710 return false;
711}
712
713
714//===----------------------------------------------------------------------===//
715// GlobalValue Reference/Resolution Routines.
716//===----------------------------------------------------------------------===//
717
718/// GetGlobalVal - Get a value with the specified name or ID, creating a
719/// forward reference record if needed. This can return null if the value
720/// exists but does not have the right type.
721GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
722 LocTy Loc) {
723 const PointerType *PTy = dyn_cast<PointerType>(Ty);
724 if (PTy == 0) {
725 Error(Loc, "global variable reference must have pointer type");
726 return 0;
727 }
728
729 // Look this name up in the normal function symbol table.
730 GlobalValue *Val =
731 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
732
733 // If this is a forward reference for the value, see if we already created a
734 // forward ref record.
735 if (Val == 0) {
736 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
737 I = ForwardRefVals.find(Name);
738 if (I != ForwardRefVals.end())
739 Val = I->second.first;
740 }
741
742 // If we have the value in the symbol table or fwd-ref table, return it.
743 if (Val) {
744 if (Val->getType() == Ty) return Val;
745 Error(Loc, "'@" + Name + "' defined with type '" +
746 Val->getType()->getDescription() + "'");
747 return 0;
748 }
749
750 // Otherwise, create a new forward reference for this value and remember it.
751 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000752 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
753 // Function types can return opaque but functions can't.
754 if (isa<OpaqueType>(FT->getReturnType())) {
755 Error(Loc, "function may not return opaque type");
756 return 0;
757 }
758
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000759 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000760 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000761 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
762 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000763 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000764
765 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
766 return FwdVal;
767}
768
769GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
770 const PointerType *PTy = dyn_cast<PointerType>(Ty);
771 if (PTy == 0) {
772 Error(Loc, "global variable reference must have pointer type");
773 return 0;
774 }
775
776 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
777
778 // If this is a forward reference for the value, see if we already created a
779 // forward ref record.
780 if (Val == 0) {
781 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
782 I = ForwardRefValIDs.find(ID);
783 if (I != ForwardRefValIDs.end())
784 Val = I->second.first;
785 }
786
787 // If we have the value in the symbol table or fwd-ref table, return it.
788 if (Val) {
789 if (Val->getType() == Ty) return Val;
790 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
791 Val->getType()->getDescription() + "'");
792 return 0;
793 }
794
795 // Otherwise, create a new forward reference for this value and remember it.
796 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000797 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
798 // Function types can return opaque but functions can't.
799 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000800 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000801 return 0;
802 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000803 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000804 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000805 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
806 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000807 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000808
809 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
810 return FwdVal;
811}
812
813
814//===----------------------------------------------------------------------===//
815// Helper Routines.
816//===----------------------------------------------------------------------===//
817
818/// ParseToken - If the current token has the specified kind, eat it and return
819/// success. Otherwise, emit the specified error and return failure.
820bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
821 if (Lex.getKind() != T)
822 return TokError(ErrMsg);
823 Lex.Lex();
824 return false;
825}
826
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000827/// ParseStringConstant
828/// ::= StringConstant
829bool LLParser::ParseStringConstant(std::string &Result) {
830 if (Lex.getKind() != lltok::StringConstant)
831 return TokError("expected string constant");
832 Result = Lex.getStrVal();
833 Lex.Lex();
834 return false;
835}
836
837/// ParseUInt32
838/// ::= uint32
839bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000840 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
841 return TokError("expected integer");
842 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
843 if (Val64 != unsigned(Val64))
844 return TokError("expected 32-bit integer (too large)");
845 Val = Val64;
846 Lex.Lex();
847 return false;
848}
849
850
851/// ParseOptionalAddrSpace
852/// := /*empty*/
853/// := 'addrspace' '(' uint32 ')'
854bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
855 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000856 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000859 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000860 ParseToken(lltok::rparen, "expected ')' in address space");
861}
862
863/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
864/// indicates what kind of attribute list this is: 0: function arg, 1: result,
865/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000866/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000867bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
868 Attrs = Attribute::None;
869 LocTy AttrLoc = Lex.getLoc();
870
871 while (1) {
872 switch (Lex.getKind()) {
873 case lltok::kw_sext:
874 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000875 // Treat these as signext/zeroext if they occur in the argument list after
876 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
877 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
878 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000880 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000881 if (Lex.getKind() == lltok::kw_sext)
882 Attrs |= Attribute::SExt;
883 else
884 Attrs |= Attribute::ZExt;
885 break;
886 }
887 // FALL THROUGH.
888 default: // End of attributes.
889 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
890 return Error(AttrLoc, "invalid use of function-only attribute");
891
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000892 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000893 return Error(AttrLoc, "invalid use of parameter-only attribute");
894
895 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000896 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
897 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
898 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
899 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
900 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
901 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
902 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
903 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000904
Devang Patel578efa92009-06-05 21:57:13 +0000905 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
906 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
907 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
908 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
909 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000910 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000911 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
912 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
913 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
914 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
915 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
916 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000917 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000918
919 case lltok::kw_align: {
920 unsigned Alignment;
921 if (ParseOptionalAlignment(Alignment))
922 return true;
923 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
924 continue;
925 }
926 }
927 Lex.Lex();
928 }
929}
930
931/// ParseOptionalLinkage
932/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000933/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000934/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000935/// ::= 'internal'
936/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000937/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000938/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000939/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000940/// ::= 'appending'
941/// ::= 'dllexport'
942/// ::= 'common'
943/// ::= 'dllimport'
944/// ::= 'extern_weak'
945/// ::= 'external'
946bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
947 HasLinkage = false;
948 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000949 default: Res=GlobalValue::ExternalLinkage; return false;
950 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
951 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
952 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
953 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
954 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
955 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
956 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000957 case lltok::kw_available_externally:
958 Res = GlobalValue::AvailableExternallyLinkage;
959 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000960 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
961 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
962 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
963 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
964 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
965 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000966 }
967 Lex.Lex();
968 HasLinkage = true;
969 return false;
970}
971
972/// ParseOptionalVisibility
973/// ::= /*empty*/
974/// ::= 'default'
975/// ::= 'hidden'
976/// ::= 'protected'
977///
978bool LLParser::ParseOptionalVisibility(unsigned &Res) {
979 switch (Lex.getKind()) {
980 default: Res = GlobalValue::DefaultVisibility; return false;
981 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
982 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
983 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
984 }
985 Lex.Lex();
986 return false;
987}
988
989/// ParseOptionalCallingConv
990/// ::= /*empty*/
991/// ::= 'ccc'
992/// ::= 'fastcc'
993/// ::= 'coldcc'
994/// ::= 'x86_stdcallcc'
995/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +0000996/// ::= 'arm_apcscc'
997/// ::= 'arm_aapcscc'
998/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +0000999/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001000///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001001bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001002 switch (Lex.getKind()) {
1003 default: CC = CallingConv::C; return false;
1004 case lltok::kw_ccc: CC = CallingConv::C; break;
1005 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1006 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1007 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1008 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001009 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1010 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1011 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001012 case lltok::kw_cc: {
1013 unsigned ArbitraryCC;
1014 Lex.Lex();
1015 if (ParseUInt32(ArbitraryCC)) {
1016 return true;
1017 } else
1018 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1019 return false;
1020 }
1021 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001022 }
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001023
Chris Lattnerdf986172009-01-02 07:01:27 +00001024 Lex.Lex();
1025 return false;
1026}
1027
1028/// ParseOptionalAlignment
1029/// ::= /* empty */
1030/// ::= 'align' 4
1031bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1032 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001033 if (!EatIfPresent(lltok::kw_align))
1034 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001035 LocTy AlignLoc = Lex.getLoc();
1036 if (ParseUInt32(Alignment)) return true;
1037 if (!isPowerOf2_32(Alignment))
1038 return Error(AlignLoc, "alignment is not a power of two");
1039 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001040}
1041
1042/// ParseOptionalCommaAlignment
1043/// ::= /* empty */
1044/// ::= ',' 'align' 4
1045bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
1046 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001047 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00001048 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001049 return ParseToken(lltok::kw_align, "expected 'align'") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001050 ParseUInt32(Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00001051}
1052
1053/// ParseIndexList
1054/// ::= (',' uint32)+
1055bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1056 if (Lex.getKind() != lltok::comma)
1057 return TokError("expected ',' as start of index list");
1058
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001059 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001061 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001062 Indices.push_back(Idx);
1063 }
1064
1065 return false;
1066}
1067
1068//===----------------------------------------------------------------------===//
1069// Type Parsing.
1070//===----------------------------------------------------------------------===//
1071
1072/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001073bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1074 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001075 if (ParseTypeRec(Result)) return true;
1076
1077 // Verify no unresolved uprefs.
1078 if (!UpRefs.empty())
1079 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Chris Lattnerdf986172009-01-02 07:01:27 +00001080
Owen Anderson1d0be152009-08-13 21:58:54 +00001081 if (!AllowVoid && Result.get() == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001082 return Error(TypeLoc, "void type only allowed for function results");
1083
Chris Lattnerdf986172009-01-02 07:01:27 +00001084 return false;
1085}
1086
1087/// HandleUpRefs - Every time we finish a new layer of types, this function is
1088/// called. It loops through the UpRefs vector, which is a list of the
1089/// currently active types. For each type, if the up-reference is contained in
1090/// the newly completed type, we decrement the level count. When the level
1091/// count reaches zero, the up-referenced type is the type that is passed in:
1092/// thus we can complete the cycle.
1093///
1094PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1095 // If Ty isn't abstract, or if there are no up-references in it, then there is
1096 // nothing to resolve here.
1097 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1098
1099 PATypeHolder Ty(ty);
1100#if 0
1101 errs() << "Type '" << Ty->getDescription()
1102 << "' newly formed. Resolving upreferences.\n"
1103 << UpRefs.size() << " upreferences active!\n";
1104#endif
1105
1106 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1107 // to zero), we resolve them all together before we resolve them to Ty. At
1108 // the end of the loop, if there is anything to resolve to Ty, it will be in
1109 // this variable.
1110 OpaqueType *TypeToResolve = 0;
1111
1112 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1113 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1114 bool ContainsType =
1115 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1116 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1117
1118#if 0
1119 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1120 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1121 << (ContainsType ? "true" : "false")
1122 << " level=" << UpRefs[i].NestingLevel << "\n";
1123#endif
1124 if (!ContainsType)
1125 continue;
1126
1127 // Decrement level of upreference
1128 unsigned Level = --UpRefs[i].NestingLevel;
1129 UpRefs[i].LastContainedTy = Ty;
1130
1131 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1132 if (Level != 0)
1133 continue;
1134
1135#if 0
1136 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1137#endif
1138 if (!TypeToResolve)
1139 TypeToResolve = UpRefs[i].UpRefTy;
1140 else
1141 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1142 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1143 --i; // Do not skip the next element.
1144 }
1145
1146 if (TypeToResolve)
1147 TypeToResolve->refineAbstractTypeTo(Ty);
1148
1149 return Ty;
1150}
1151
1152
1153/// ParseTypeRec - The recursive function used to process the internal
1154/// implementation details of types.
1155bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1156 switch (Lex.getKind()) {
1157 default:
1158 return TokError("expected type");
1159 case lltok::Type:
1160 // TypeRec ::= 'float' | 'void' (etc)
1161 Result = Lex.getTyVal();
1162 Lex.Lex();
1163 break;
1164 case lltok::kw_opaque:
1165 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001166 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001167 Lex.Lex();
1168 break;
1169 case lltok::lbrace:
1170 // TypeRec ::= '{' ... '}'
1171 if (ParseStructType(Result, false))
1172 return true;
1173 break;
1174 case lltok::lsquare:
1175 // TypeRec ::= '[' ... ']'
1176 Lex.Lex(); // eat the lsquare.
1177 if (ParseArrayVectorType(Result, false))
1178 return true;
1179 break;
1180 case lltok::less: // Either vector or packed struct.
1181 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001182 Lex.Lex();
1183 if (Lex.getKind() == lltok::lbrace) {
1184 if (ParseStructType(Result, true) ||
1185 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001186 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001187 } else if (ParseArrayVectorType(Result, true))
1188 return true;
1189 break;
1190 case lltok::LocalVar:
1191 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1192 // TypeRec ::= %foo
1193 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1194 Result = T;
1195 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001196 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001197 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1198 std::make_pair(Result,
1199 Lex.getLoc())));
1200 M->addTypeName(Lex.getStrVal(), Result.get());
1201 }
1202 Lex.Lex();
1203 break;
1204
1205 case lltok::LocalVarID:
1206 // TypeRec ::= %4
1207 if (Lex.getUIntVal() < NumberedTypes.size())
1208 Result = NumberedTypes[Lex.getUIntVal()];
1209 else {
1210 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1211 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1212 if (I != ForwardRefTypeIDs.end())
1213 Result = I->second.first;
1214 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001215 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1217 std::make_pair(Result,
1218 Lex.getLoc())));
1219 }
1220 }
1221 Lex.Lex();
1222 break;
1223 case lltok::backslash: {
1224 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001226 unsigned Val;
1227 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001228 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1230 Result = OT;
1231 break;
1232 }
1233 }
1234
1235 // Parse the type suffixes.
1236 while (1) {
1237 switch (Lex.getKind()) {
1238 // End of type.
1239 default: return false;
1240
1241 // TypeRec ::= TypeRec '*'
1242 case lltok::star:
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");
Owen Andersondebcb012009-07-29 22:17:13 +00001249 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 Lex.Lex();
1251 break;
1252
1253 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1254 case lltok::kw_addrspace: {
Owen Anderson1d0be152009-08-13 21:58:54 +00001255 if (Result.get() == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 return TokError("basic block pointers are invalid");
Owen Anderson1d0be152009-08-13 21:58:54 +00001257 if (Result.get() == Type::getVoidTy(Context))
Dan Gohmanb9070d32009-02-09 17:41:21 +00001258 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001259 if (!PointerType::isValidElementType(Result.get()))
1260 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001261 unsigned AddrSpace;
1262 if (ParseOptionalAddrSpace(AddrSpace) ||
1263 ParseToken(lltok::star, "expected '*' in address space"))
1264 return true;
1265
Owen Andersondebcb012009-07-29 22:17:13 +00001266 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 break;
1268 }
1269
1270 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1271 case lltok::lparen:
1272 if (ParseFunctionType(Result))
1273 return true;
1274 break;
1275 }
1276 }
1277}
1278
1279/// ParseParameterList
1280/// ::= '(' ')'
1281/// ::= '(' Arg (',' Arg)* ')'
1282/// Arg
1283/// ::= Type OptionalAttributes Value OptionalAttributes
1284bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1285 PerFunctionState &PFS) {
1286 if (ParseToken(lltok::lparen, "expected '(' in call"))
1287 return true;
1288
1289 while (Lex.getKind() != lltok::rparen) {
1290 // If this isn't the first argument, we need a comma.
1291 if (!ArgList.empty() &&
1292 ParseToken(lltok::comma, "expected ',' in argument list"))
1293 return true;
1294
1295 // Parse the argument.
1296 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001297 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 unsigned ArgAttrs1, ArgAttrs2;
1299 Value *V;
1300 if (ParseType(ArgTy, ArgLoc) ||
1301 ParseOptionalAttrs(ArgAttrs1, 0) ||
1302 ParseValue(ArgTy, V, PFS) ||
1303 // FIXME: Should not allow attributes after the argument, remove this in
1304 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001305 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001306 return true;
1307 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1308 }
1309
1310 Lex.Lex(); // Lex the ')'.
1311 return false;
1312}
1313
1314
1315
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001316/// ParseArgumentList - Parse the argument list for a function type or function
1317/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001318/// ::= '(' ArgTypeListI ')'
1319/// ArgTypeListI
1320/// ::= /*empty*/
1321/// ::= '...'
1322/// ::= ArgTypeList ',' '...'
1323/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001324///
Chris Lattnerdf986172009-01-02 07:01:27 +00001325bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001326 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 isVarArg = false;
1328 assert(Lex.getKind() == lltok::lparen);
1329 Lex.Lex(); // eat the (.
1330
1331 if (Lex.getKind() == lltok::rparen) {
1332 // empty
1333 } else if (Lex.getKind() == lltok::dotdotdot) {
1334 isVarArg = true;
1335 Lex.Lex();
1336 } else {
1337 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001338 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001340 std::string Name;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001341
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001342 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1343 // types (such as a function returning a pointer to itself). If parsing a
1344 // function prototype, we require fully resolved types.
1345 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001346 ParseOptionalAttrs(Attrs, 0)) return true;
1347
Owen Anderson1d0be152009-08-13 21:58:54 +00001348 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001349 return Error(TypeLoc, "argument can not have void type");
1350
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 if (Lex.getKind() == lltok::LocalVar ||
1352 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1353 Name = Lex.getStrVal();
1354 Lex.Lex();
1355 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001356
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001357 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001358 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001359
1360 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1361
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001362 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001364 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 break;
1367 }
1368
1369 // Otherwise must be an argument type.
1370 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001371 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001372 ParseOptionalAttrs(Attrs, 0)) return true;
1373
Owen Anderson1d0be152009-08-13 21:58:54 +00001374 if (ArgTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001375 return Error(TypeLoc, "argument can not have void type");
1376
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 if (Lex.getKind() == lltok::LocalVar ||
1378 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1379 Name = Lex.getStrVal();
1380 Lex.Lex();
1381 } else {
1382 Name = "";
1383 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001384
1385 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1386 return Error(TypeLoc, "invalid type for function argument");
Chris Lattnerdf986172009-01-02 07:01:27 +00001387
1388 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1389 }
1390 }
1391
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001392 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001393}
1394
1395/// ParseFunctionType
1396/// ::= Type ArgumentList OptionalAttrs
1397bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1398 assert(Lex.getKind() == lltok::lparen);
1399
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001400 if (!FunctionType::isValidReturnType(Result))
1401 return TokError("invalid function return type");
1402
Chris Lattnerdf986172009-01-02 07:01:27 +00001403 std::vector<ArgInfo> ArgList;
1404 bool isVarArg;
1405 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001406 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 // FIXME: Allow, but ignore attributes on function types!
1408 // FIXME: Remove in LLVM 3.0
1409 ParseOptionalAttrs(Attrs, 2))
1410 return true;
1411
1412 // Reject names on the arguments lists.
1413 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1414 if (!ArgList[i].Name.empty())
1415 return Error(ArgList[i].Loc, "argument name invalid in function type");
1416 if (!ArgList[i].Attrs != 0) {
1417 // Allow but ignore attributes on function types; this permits
1418 // auto-upgrade.
1419 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1420 }
1421 }
1422
1423 std::vector<const Type*> ArgListTy;
1424 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1425 ArgListTy.push_back(ArgList[i].Type);
1426
Owen Andersondebcb012009-07-29 22:17:13 +00001427 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001428 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001429 return false;
1430}
1431
1432/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1433/// TypeRec
1434/// ::= '{' '}'
1435/// ::= '{' TypeRec (',' TypeRec)* '}'
1436/// ::= '<' '{' '}' '>'
1437/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1438bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1439 assert(Lex.getKind() == lltok::lbrace);
1440 Lex.Lex(); // Consume the '{'
1441
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001442 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001443 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001444 return false;
1445 }
1446
1447 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001448 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 if (ParseTypeRec(Result)) return true;
1450 ParamsList.push_back(Result);
1451
Owen Anderson1d0be152009-08-13 21:58:54 +00001452 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001453 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001454 if (!StructType::isValidElementType(Result))
1455 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001456
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001457 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001458 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 if (ParseTypeRec(Result)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001460
Owen Anderson1d0be152009-08-13 21:58:54 +00001461 if (Result == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001462 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001463 if (!StructType::isValidElementType(Result))
1464 return Error(EltTyLoc, "invalid element type for struct");
Chris Lattnera9a9e072009-03-09 04:49:14 +00001465
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 ParamsList.push_back(Result);
1467 }
1468
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001469 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1470 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001471
1472 std::vector<const Type*> ParamsListTy;
1473 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1474 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001475 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001476 return false;
1477}
1478
1479/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1480/// token has already been consumed.
1481/// TypeRec
1482/// ::= '[' APSINTVAL 'x' Types ']'
1483/// ::= '<' APSINTVAL 'x' Types '>'
1484bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1485 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1486 Lex.getAPSIntVal().getBitWidth() > 64)
1487 return TokError("expected number in address space");
1488
1489 LocTy SizeLoc = Lex.getLoc();
1490 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001491 Lex.Lex();
1492
1493 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1494 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001495
1496 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001497 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001498 if (ParseTypeRec(EltTy)) return true;
1499
Owen Anderson1d0be152009-08-13 21:58:54 +00001500 if (EltTy == Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00001501 return Error(TypeLoc, "array and vector element type cannot be void");
1502
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001503 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1504 "expected end of sequential type"))
1505 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001506
1507 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001508 if (Size == 0)
1509 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001510 if ((unsigned)Size != Size)
1511 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001512 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001513 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001514 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001515 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001516 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001517 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001518 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001519 }
1520 return false;
1521}
1522
1523//===----------------------------------------------------------------------===//
1524// Function Semantic Analysis.
1525//===----------------------------------------------------------------------===//
1526
1527LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1528 : P(p), F(f) {
1529
1530 // Insert unnamed arguments into the NumberedVals list.
1531 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1532 AI != E; ++AI)
1533 if (!AI->hasName())
1534 NumberedVals.push_back(AI);
1535}
1536
1537LLParser::PerFunctionState::~PerFunctionState() {
1538 // If there were any forward referenced non-basicblock values, delete them.
1539 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1540 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1541 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001542 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001543 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 delete I->second.first;
1545 I->second.first = 0;
1546 }
1547
1548 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1549 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1550 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001551 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001552 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 delete I->second.first;
1554 I->second.first = 0;
1555 }
1556}
1557
1558bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1559 if (!ForwardRefVals.empty())
1560 return P.Error(ForwardRefVals.begin()->second.second,
1561 "use of undefined value '%" + ForwardRefVals.begin()->first +
1562 "'");
1563 if (!ForwardRefValIDs.empty())
1564 return P.Error(ForwardRefValIDs.begin()->second.second,
1565 "use of undefined value '%" +
1566 utostr(ForwardRefValIDs.begin()->first) + "'");
1567 return false;
1568}
1569
1570
1571/// GetVal - Get a value with the specified name or ID, creating a
1572/// forward reference record if needed. This can return null if the value
1573/// exists but does not have the right type.
1574Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1575 const Type *Ty, LocTy Loc) {
1576 // Look this name up in the normal function symbol table.
1577 Value *Val = F.getValueSymbolTable().lookup(Name);
1578
1579 // If this is a forward reference for the value, see if we already created a
1580 // forward ref record.
1581 if (Val == 0) {
1582 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1583 I = ForwardRefVals.find(Name);
1584 if (I != ForwardRefVals.end())
1585 Val = I->second.first;
1586 }
1587
1588 // If we have the value in the symbol table or fwd-ref table, return it.
1589 if (Val) {
1590 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001591 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 P.Error(Loc, "'%" + Name + "' is not a basic block");
1593 else
1594 P.Error(Loc, "'%" + Name + "' defined with type '" +
1595 Val->getType()->getDescription() + "'");
1596 return 0;
1597 }
1598
1599 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001600 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1601 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001602 P.Error(Loc, "invalid use of a non-first-class type");
1603 return 0;
1604 }
1605
1606 // Otherwise, create a new forward reference for this value and remember it.
1607 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001608 if (Ty == Type::getLabelTy(F.getContext()))
1609 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 else
1611 FwdVal = new Argument(Ty, Name);
1612
1613 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1614 return FwdVal;
1615}
1616
1617Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1618 LocTy Loc) {
1619 // Look this name up in the normal function symbol table.
1620 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1621
1622 // If this is a forward reference for the value, see if we already created a
1623 // forward ref record.
1624 if (Val == 0) {
1625 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1626 I = ForwardRefValIDs.find(ID);
1627 if (I != ForwardRefValIDs.end())
1628 Val = I->second.first;
1629 }
1630
1631 // If we have the value in the symbol table or fwd-ref table, return it.
1632 if (Val) {
1633 if (Val->getType() == Ty) return Val;
Owen Anderson1d0be152009-08-13 21:58:54 +00001634 if (Ty == Type::getLabelTy(F.getContext()))
Chris Lattnerdf986172009-01-02 07:01:27 +00001635 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1636 else
1637 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1638 Val->getType()->getDescription() + "'");
1639 return 0;
1640 }
1641
Owen Anderson1d0be152009-08-13 21:58:54 +00001642 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1643 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 P.Error(Loc, "invalid use of a non-first-class type");
1645 return 0;
1646 }
1647
1648 // Otherwise, create a new forward reference for this value and remember it.
1649 Value *FwdVal;
Owen Anderson1d0be152009-08-13 21:58:54 +00001650 if (Ty == Type::getLabelTy(F.getContext()))
1651 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 else
1653 FwdVal = new Argument(Ty);
1654
1655 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1656 return FwdVal;
1657}
1658
1659/// SetInstName - After an instruction is parsed and inserted into its
1660/// basic block, this installs its name.
1661bool LLParser::PerFunctionState::SetInstName(int NameID,
1662 const std::string &NameStr,
1663 LocTy NameLoc, Instruction *Inst) {
1664 // If this instruction has void type, it cannot have a name or ID specified.
Owen Anderson1d0be152009-08-13 21:58:54 +00001665 if (Inst->getType() == Type::getVoidTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 if (NameID != -1 || !NameStr.empty())
1667 return P.Error(NameLoc, "instructions returning void cannot have a name");
1668 return false;
1669 }
1670
1671 // If this was a numbered instruction, verify that the instruction is the
1672 // expected value and resolve any forward references.
1673 if (NameStr.empty()) {
1674 // If neither a name nor an ID was specified, just use the next ID.
1675 if (NameID == -1)
1676 NameID = NumberedVals.size();
1677
1678 if (unsigned(NameID) != NumberedVals.size())
1679 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1680 utostr(NumberedVals.size()) + "'");
1681
1682 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1683 ForwardRefValIDs.find(NameID);
1684 if (FI != ForwardRefValIDs.end()) {
1685 if (FI->second.first->getType() != Inst->getType())
1686 return P.Error(NameLoc, "instruction forward referenced with type '" +
1687 FI->second.first->getType()->getDescription() + "'");
1688 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001689 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 ForwardRefValIDs.erase(FI);
1691 }
1692
1693 NumberedVals.push_back(Inst);
1694 return false;
1695 }
1696
1697 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1698 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1699 FI = ForwardRefVals.find(NameStr);
1700 if (FI != ForwardRefVals.end()) {
1701 if (FI->second.first->getType() != Inst->getType())
1702 return P.Error(NameLoc, "instruction forward referenced with type '" +
1703 FI->second.first->getType()->getDescription() + "'");
1704 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001705 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 ForwardRefVals.erase(FI);
1707 }
1708
1709 // Set the name on the instruction.
1710 Inst->setName(NameStr);
1711
1712 if (Inst->getNameStr() != NameStr)
1713 return P.Error(NameLoc, "multiple definition of local value named '" +
1714 NameStr + "'");
1715 return false;
1716}
1717
1718/// GetBB - Get a basic block with the specified name or ID, creating a
1719/// forward reference record if needed.
1720BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1721 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001722 return cast_or_null<BasicBlock>(GetVal(Name,
1723 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001724}
1725
1726BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001727 return cast_or_null<BasicBlock>(GetVal(ID,
1728 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001729}
1730
1731/// DefineBB - Define the specified basic block, which is either named or
1732/// unnamed. If there is an error, this returns null otherwise it returns
1733/// the block being defined.
1734BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1735 LocTy Loc) {
1736 BasicBlock *BB;
1737 if (Name.empty())
1738 BB = GetBB(NumberedVals.size(), Loc);
1739 else
1740 BB = GetBB(Name, Loc);
1741 if (BB == 0) return 0; // Already diagnosed error.
1742
1743 // Move the block to the end of the function. Forward ref'd blocks are
1744 // inserted wherever they happen to be referenced.
1745 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1746
1747 // Remove the block from forward ref sets.
1748 if (Name.empty()) {
1749 ForwardRefValIDs.erase(NumberedVals.size());
1750 NumberedVals.push_back(BB);
1751 } else {
1752 // BB forward references are already in the function symbol table.
1753 ForwardRefVals.erase(Name);
1754 }
1755
1756 return BB;
1757}
1758
1759//===----------------------------------------------------------------------===//
1760// Constants.
1761//===----------------------------------------------------------------------===//
1762
1763/// ParseValID - Parse an abstract value that doesn't necessarily have a
1764/// type implied. For example, if we parse "4" we don't know what integer type
1765/// it has. The value will later be combined with its type and checked for
1766/// sanity.
1767bool LLParser::ParseValID(ValID &ID) {
1768 ID.Loc = Lex.getLoc();
1769 switch (Lex.getKind()) {
1770 default: return TokError("expected value token");
1771 case lltok::GlobalID: // @42
1772 ID.UIntVal = Lex.getUIntVal();
1773 ID.Kind = ValID::t_GlobalID;
1774 break;
1775 case lltok::GlobalVar: // @foo
1776 ID.StrVal = Lex.getStrVal();
1777 ID.Kind = ValID::t_GlobalName;
1778 break;
1779 case lltok::LocalVarID: // %42
1780 ID.UIntVal = Lex.getUIntVal();
1781 ID.Kind = ValID::t_LocalID;
1782 break;
1783 case lltok::LocalVar: // %foo
1784 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1785 ID.StrVal = Lex.getStrVal();
1786 ID.Kind = ValID::t_LocalName;
1787 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001788 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001789 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001790 Lex.Lex();
1791 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001792 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001793 if (ParseMDNodeVector(Elts) ||
1794 ParseToken(lltok::rbrace, "expected end of metadata node"))
1795 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001796
Owen Anderson647e3012009-07-31 21:35:40 +00001797 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001798 return false;
1799 }
1800
Devang Patel923078c2009-07-01 19:21:12 +00001801 // Standalone metadata reference
1802 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001803 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001804 return false;
Devang Patel256be962009-07-20 19:00:08 +00001805
Nick Lewycky21cc4462009-04-04 07:22:01 +00001806 // MDString:
1807 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001808 if (ParseMDString(ID.MetadataVal)) return true;
1809 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001810 return false;
1811 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001812 case lltok::APSInt:
1813 ID.APSIntVal = Lex.getAPSIntVal();
1814 ID.Kind = ValID::t_APSInt;
1815 break;
1816 case lltok::APFloat:
1817 ID.APFloatVal = Lex.getAPFloatVal();
1818 ID.Kind = ValID::t_APFloat;
1819 break;
1820 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001821 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001822 ID.Kind = ValID::t_Constant;
1823 break;
1824 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001825 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 ID.Kind = ValID::t_Constant;
1827 break;
1828 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1829 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1830 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1831
1832 case lltok::lbrace: {
1833 // ValID ::= '{' ConstVector '}'
1834 Lex.Lex();
1835 SmallVector<Constant*, 16> Elts;
1836 if (ParseGlobalValueVector(Elts) ||
1837 ParseToken(lltok::rbrace, "expected end of struct constant"))
1838 return true;
1839
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001840 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1841 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 ID.Kind = ValID::t_Constant;
1843 return false;
1844 }
1845 case lltok::less: {
1846 // ValID ::= '<' ConstVector '>' --> Vector.
1847 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1848 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001849 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001850
1851 SmallVector<Constant*, 16> Elts;
1852 LocTy FirstEltLoc = Lex.getLoc();
1853 if (ParseGlobalValueVector(Elts) ||
1854 (isPackedStruct &&
1855 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1856 ParseToken(lltok::greater, "expected end of constant"))
1857 return true;
1858
1859 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001860 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001861 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 ID.Kind = ValID::t_Constant;
1863 return false;
1864 }
1865
1866 if (Elts.empty())
1867 return Error(ID.Loc, "constant vector must not be empty");
1868
1869 if (!Elts[0]->getType()->isInteger() &&
1870 !Elts[0]->getType()->isFloatingPoint())
1871 return Error(FirstEltLoc,
1872 "vector elements must have integer or floating point type");
1873
1874 // Verify that all the vector elements have the same type.
1875 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1876 if (Elts[i]->getType() != Elts[0]->getType())
1877 return Error(FirstEltLoc,
1878 "vector element #" + utostr(i) +
1879 " is not of type '" + Elts[0]->getType()->getDescription());
1880
Owen Andersonaf7ec972009-07-28 21:19:26 +00001881 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 ID.Kind = ValID::t_Constant;
1883 return false;
1884 }
1885 case lltok::lsquare: { // Array Constant
1886 Lex.Lex();
1887 SmallVector<Constant*, 16> Elts;
1888 LocTy FirstEltLoc = Lex.getLoc();
1889 if (ParseGlobalValueVector(Elts) ||
1890 ParseToken(lltok::rsquare, "expected end of array constant"))
1891 return true;
1892
1893 // Handle empty element.
1894 if (Elts.empty()) {
1895 // Use undef instead of an array because it's inconvenient to determine
1896 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001897 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001898 return false;
1899 }
1900
1901 if (!Elts[0]->getType()->isFirstClassType())
1902 return Error(FirstEltLoc, "invalid array element type: " +
1903 Elts[0]->getType()->getDescription());
1904
Owen Andersondebcb012009-07-29 22:17:13 +00001905 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001906
1907 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001908 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 if (Elts[i]->getType() != Elts[0]->getType())
1910 return Error(FirstEltLoc,
1911 "array element #" + utostr(i) +
1912 " is not of type '" +Elts[0]->getType()->getDescription());
1913 }
Nick Lewycky21cc4462009-04-04 07:22:01 +00001914
Owen Anderson1fd70962009-07-28 18:32:17 +00001915 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 ID.Kind = ValID::t_Constant;
1917 return false;
1918 }
1919 case lltok::kw_c: // c "foo"
1920 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001921 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001922 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1923 ID.Kind = ValID::t_Constant;
1924 return false;
1925
1926 case lltok::kw_asm: {
1927 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1928 bool HasSideEffect;
1929 Lex.Lex();
1930 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001931 ParseStringConstant(ID.StrVal) ||
1932 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 ParseToken(lltok::StringConstant, "expected constraint string"))
1934 return true;
1935 ID.StrVal2 = Lex.getStrVal();
1936 ID.UIntVal = HasSideEffect;
1937 ID.Kind = ValID::t_InlineAsm;
1938 return false;
1939 }
1940
1941 case lltok::kw_trunc:
1942 case lltok::kw_zext:
1943 case lltok::kw_sext:
1944 case lltok::kw_fptrunc:
1945 case lltok::kw_fpext:
1946 case lltok::kw_bitcast:
1947 case lltok::kw_uitofp:
1948 case lltok::kw_sitofp:
1949 case lltok::kw_fptoui:
1950 case lltok::kw_fptosi:
1951 case lltok::kw_inttoptr:
1952 case lltok::kw_ptrtoint: {
1953 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00001954 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001955 Constant *SrcVal;
1956 Lex.Lex();
1957 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1958 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001959 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 ParseType(DestTy) ||
1961 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1962 return true;
1963 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1964 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1965 SrcVal->getType()->getDescription() + "' to '" +
1966 DestTy->getDescription() + "'");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001967 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00001968 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 ID.Kind = ValID::t_Constant;
1970 return false;
1971 }
1972 case lltok::kw_extractvalue: {
1973 Lex.Lex();
1974 Constant *Val;
1975 SmallVector<unsigned, 4> Indices;
1976 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1977 ParseGlobalTypeAndValue(Val) ||
1978 ParseIndexList(Indices) ||
1979 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1980 return true;
1981 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1982 return Error(ID.Loc, "extractvalue operand must be array or struct");
1983 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1984 Indices.end()))
1985 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00001986 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001987 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001988 ID.Kind = ValID::t_Constant;
1989 return false;
1990 }
1991 case lltok::kw_insertvalue: {
1992 Lex.Lex();
1993 Constant *Val0, *Val1;
1994 SmallVector<unsigned, 4> Indices;
1995 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1996 ParseGlobalTypeAndValue(Val0) ||
1997 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1998 ParseGlobalTypeAndValue(Val1) ||
1999 ParseIndexList(Indices) ||
2000 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2001 return true;
2002 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2003 return Error(ID.Loc, "extractvalue operand must be array or struct");
2004 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2005 Indices.end()))
2006 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002007 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002008 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 ID.Kind = ValID::t_Constant;
2010 return false;
2011 }
2012 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002013 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002014 unsigned PredVal, Opc = Lex.getUIntVal();
2015 Constant *Val0, *Val1;
2016 Lex.Lex();
2017 if (ParseCmpPredicate(PredVal, Opc) ||
2018 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2019 ParseGlobalTypeAndValue(Val0) ||
2020 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2021 ParseGlobalTypeAndValue(Val1) ||
2022 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2023 return true;
2024
2025 if (Val0->getType() != Val1->getType())
2026 return Error(ID.Loc, "compare operands must have the same type");
2027
2028 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2029
2030 if (Opc == Instruction::FCmp) {
2031 if (!Val0->getType()->isFPOrFPVector())
2032 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002033 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002034 } else {
2035 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 if (!Val0->getType()->isIntOrIntVector() &&
2037 !isa<PointerType>(Val0->getType()))
2038 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002039 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 }
2041 ID.Kind = ValID::t_Constant;
2042 return false;
2043 }
2044
2045 // Binary Operators.
2046 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002047 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002049 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002050 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002051 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002052 case lltok::kw_udiv:
2053 case lltok::kw_sdiv:
2054 case lltok::kw_fdiv:
2055 case lltok::kw_urem:
2056 case lltok::kw_srem:
2057 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002058 bool NUW = false;
2059 bool NSW = false;
2060 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 unsigned Opc = Lex.getUIntVal();
2062 Constant *Val0, *Val1;
2063 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002064 LocTy ModifierLoc = Lex.getLoc();
2065 if (Opc == Instruction::Add ||
2066 Opc == Instruction::Sub ||
2067 Opc == Instruction::Mul) {
2068 if (EatIfPresent(lltok::kw_nuw))
2069 NUW = true;
2070 if (EatIfPresent(lltok::kw_nsw)) {
2071 NSW = true;
2072 if (EatIfPresent(lltok::kw_nuw))
2073 NUW = true;
2074 }
2075 } else if (Opc == Instruction::SDiv) {
2076 if (EatIfPresent(lltok::kw_exact))
2077 Exact = true;
2078 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2080 ParseGlobalTypeAndValue(Val0) ||
2081 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2082 ParseGlobalTypeAndValue(Val1) ||
2083 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2084 return true;
2085 if (Val0->getType() != Val1->getType())
2086 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002087 if (!Val0->getType()->isIntOrIntVector()) {
2088 if (NUW)
2089 return Error(ModifierLoc, "nuw only applies to integer operations");
2090 if (NSW)
2091 return Error(ModifierLoc, "nsw only applies to integer operations");
2092 }
2093 // API compatibility: Accept either integer or floating-point types with
2094 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 if (!Val0->getType()->isIntOrIntVector() &&
2096 !Val0->getType()->isFPOrFPVector())
2097 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002098 unsigned Flags = 0;
2099 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2100 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2101 if (Exact) Flags |= SDivOperator::IsExact;
2102 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002103 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 ID.Kind = ValID::t_Constant;
2105 return false;
2106 }
2107
2108 // Logical Operations
2109 case lltok::kw_shl:
2110 case lltok::kw_lshr:
2111 case lltok::kw_ashr:
2112 case lltok::kw_and:
2113 case lltok::kw_or:
2114 case lltok::kw_xor: {
2115 unsigned Opc = Lex.getUIntVal();
2116 Constant *Val0, *Val1;
2117 Lex.Lex();
2118 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2119 ParseGlobalTypeAndValue(Val0) ||
2120 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2121 ParseGlobalTypeAndValue(Val1) ||
2122 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2123 return true;
2124 if (Val0->getType() != Val1->getType())
2125 return Error(ID.Loc, "operands of constexpr must have same type");
2126 if (!Val0->getType()->isIntOrIntVector())
2127 return Error(ID.Loc,
2128 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002129 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 ID.Kind = ValID::t_Constant;
2131 return false;
2132 }
2133
2134 case lltok::kw_getelementptr:
2135 case lltok::kw_shufflevector:
2136 case lltok::kw_insertelement:
2137 case lltok::kw_extractelement:
2138 case lltok::kw_select: {
2139 unsigned Opc = Lex.getUIntVal();
2140 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002141 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002143 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002144 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002145 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2146 ParseGlobalValueVector(Elts) ||
2147 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2148 return true;
2149
2150 if (Opc == Instruction::GetElementPtr) {
2151 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2152 return Error(ID.Loc, "getelementptr requires pointer operand");
2153
2154 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002155 (Value**)(Elts.data() + 1),
2156 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002157 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002158 ID.ConstantVal = InBounds ?
2159 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2160 Elts.data() + 1,
2161 Elts.size() - 1) :
2162 ConstantExpr::getGetElementPtr(Elts[0],
2163 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 } else if (Opc == Instruction::Select) {
2165 if (Elts.size() != 3)
2166 return Error(ID.Loc, "expected three operands to select");
2167 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2168 Elts[2]))
2169 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002170 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 } else if (Opc == Instruction::ShuffleVector) {
2172 if (Elts.size() != 3)
2173 return Error(ID.Loc, "expected three operands to shufflevector");
2174 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2175 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002176 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002177 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 } else if (Opc == Instruction::ExtractElement) {
2179 if (Elts.size() != 2)
2180 return Error(ID.Loc, "expected two operands to extractelement");
2181 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2182 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002183 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 } else {
2185 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2186 if (Elts.size() != 3)
2187 return Error(ID.Loc, "expected three operands to insertelement");
2188 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2189 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002190 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002191 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 }
2193
2194 ID.Kind = ValID::t_Constant;
2195 return false;
2196 }
2197 }
2198
2199 Lex.Lex();
2200 return false;
2201}
2202
2203/// ParseGlobalValue - Parse a global value with the specified type.
2204bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2205 V = 0;
2206 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002207 return ParseValID(ID) ||
2208 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002209}
2210
2211/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2212/// constant.
2213bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2214 Constant *&V) {
2215 if (isa<FunctionType>(Ty))
2216 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2217
2218 switch (ID.Kind) {
Devang Patele54abc92009-07-22 17:43:22 +00002219 default: llvm_unreachable("Unknown ValID!");
2220 case ValID::t_Metadata:
2221 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 case ValID::t_LocalID:
2223 case ValID::t_LocalName:
2224 return Error(ID.Loc, "invalid use of function-local name");
2225 case ValID::t_InlineAsm:
2226 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2227 case ValID::t_GlobalName:
2228 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2229 return V == 0;
2230 case ValID::t_GlobalID:
2231 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2232 return V == 0;
2233 case ValID::t_APSInt:
2234 if (!isa<IntegerType>(Ty))
2235 return Error(ID.Loc, "integer constant must have integer type");
2236 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002237 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002238 return false;
2239 case ValID::t_APFloat:
2240 if (!Ty->isFloatingPoint() ||
2241 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2242 return Error(ID.Loc, "floating point constant invalid for type");
2243
2244 // The lexer has no type info, so builds all float and double FP constants
2245 // as double. Fix this here. Long double does not need this.
2246 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002247 Ty == Type::getFloatTy(Context)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 bool Ignored;
2249 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2250 &Ignored);
2251 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002252 V = ConstantFP::get(Context, ID.APFloatVal);
Chris Lattner959873d2009-01-05 18:24:23 +00002253
2254 if (V->getType() != Ty)
2255 return Error(ID.Loc, "floating point constant does not have type '" +
2256 Ty->getDescription() + "'");
2257
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 return false;
2259 case ValID::t_Null:
2260 if (!isa<PointerType>(Ty))
2261 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002262 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 return false;
2264 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002265 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002266 if ((!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context)) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002267 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002268 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002269 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002270 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002271 case ValID::t_EmptyArray:
2272 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2273 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002274 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002275 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002277 // FIXME: LabelTy should not be a first-class type.
Owen Anderson1d0be152009-08-13 21:58:54 +00002278 if (!Ty->isFirstClassType() || Ty == Type::getLabelTy(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002280 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002281 return false;
2282 case ValID::t_Constant:
2283 if (ID.ConstantVal->getType() != Ty)
2284 return Error(ID.Loc, "constant expression type mismatch");
2285 V = ID.ConstantVal;
2286 return false;
2287 }
2288}
2289
2290bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002291 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002292 return ParseType(Type) ||
2293 ParseGlobalValue(Type, V);
2294}
2295
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002296/// ParseGlobalValueVector
2297/// ::= /*empty*/
2298/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002299bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2300 // Empty list.
2301 if (Lex.getKind() == lltok::rbrace ||
2302 Lex.getKind() == lltok::rsquare ||
2303 Lex.getKind() == lltok::greater ||
2304 Lex.getKind() == lltok::rparen)
2305 return false;
2306
2307 Constant *C;
2308 if (ParseGlobalTypeAndValue(C)) return true;
2309 Elts.push_back(C);
2310
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002311 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 if (ParseGlobalTypeAndValue(C)) return true;
2313 Elts.push_back(C);
2314 }
2315
2316 return false;
2317}
2318
2319
2320//===----------------------------------------------------------------------===//
2321// Function Parsing.
2322//===----------------------------------------------------------------------===//
2323
2324bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2325 PerFunctionState &PFS) {
2326 if (ID.Kind == ValID::t_LocalID)
2327 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2328 else if (ID.Kind == ValID::t_LocalName)
2329 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002330 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002331 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2332 const FunctionType *FTy =
2333 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2334 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2335 return Error(ID.Loc, "invalid type for inline asm constraint string");
2336 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2337 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002338 } else if (ID.Kind == ValID::t_Metadata) {
2339 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 } else {
2341 Constant *C;
2342 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2343 V = C;
2344 return false;
2345 }
2346
2347 return V == 0;
2348}
2349
2350bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2351 V = 0;
2352 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002353 return ParseValID(ID) ||
2354 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002355}
2356
2357bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002358 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002359 return ParseType(T) ||
2360 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002361}
2362
2363/// FunctionHeader
2364/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2365/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2366/// OptionalAlign OptGC
2367bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2368 // Parse the linkage.
2369 LocTy LinkageLoc = Lex.getLoc();
2370 unsigned Linkage;
2371
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002372 unsigned Visibility, RetAttrs;
2373 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002374 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002375 LocTy RetTypeLoc = Lex.getLoc();
2376 if (ParseOptionalLinkage(Linkage) ||
2377 ParseOptionalVisibility(Visibility) ||
2378 ParseOptionalCallingConv(CC) ||
2379 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002380 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002381 return true;
2382
2383 // Verify that the linkage is ok.
2384 switch ((GlobalValue::LinkageTypes)Linkage) {
2385 case GlobalValue::ExternalLinkage:
2386 break; // always ok.
2387 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002388 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 if (isDefine)
2390 return Error(LinkageLoc, "invalid linkage for function definition");
2391 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002392 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002393 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002395 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002396 case GlobalValue::LinkOnceAnyLinkage:
2397 case GlobalValue::LinkOnceODRLinkage:
2398 case GlobalValue::WeakAnyLinkage:
2399 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002400 case GlobalValue::DLLExportLinkage:
2401 if (!isDefine)
2402 return Error(LinkageLoc, "invalid linkage for function declaration");
2403 break;
2404 case GlobalValue::AppendingLinkage:
2405 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002406 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002407 return Error(LinkageLoc, "invalid function linkage type");
2408 }
2409
Chris Lattner99bb3152009-01-05 08:00:30 +00002410 if (!FunctionType::isValidReturnType(RetType) ||
2411 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002412 return Error(RetTypeLoc, "invalid function return type");
2413
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002415
2416 std::string FunctionName;
2417 if (Lex.getKind() == lltok::GlobalVar) {
2418 FunctionName = Lex.getStrVal();
2419 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2420 unsigned NameID = Lex.getUIntVal();
2421
2422 if (NameID != NumberedVals.size())
2423 return TokError("function expected to be numbered '%" +
2424 utostr(NumberedVals.size()) + "'");
2425 } else {
2426 return TokError("expected function name");
2427 }
2428
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002429 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00002430
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002431 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 return TokError("expected '(' in function argument list");
2433
2434 std::vector<ArgInfo> ArgList;
2435 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002438 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002439 std::string GC;
2440
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002441 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002442 ParseOptionalAttrs(FuncAttrs, 2) ||
2443 (EatIfPresent(lltok::kw_section) &&
2444 ParseStringConstant(Section)) ||
2445 ParseOptionalAlignment(Alignment) ||
2446 (EatIfPresent(lltok::kw_gc) &&
2447 ParseStringConstant(GC)))
2448 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002449
2450 // If the alignment was parsed as an attribute, move to the alignment field.
2451 if (FuncAttrs & Attribute::Alignment) {
2452 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2453 FuncAttrs &= ~Attribute::Alignment;
2454 }
2455
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 // Okay, if we got here, the function is syntactically valid. Convert types
2457 // and do semantic checks.
2458 std::vector<const Type*> ParamTypeList;
2459 SmallVector<AttributeWithIndex, 8> Attrs;
2460 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2461 // attributes.
2462 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2463 if (FuncAttrs & ObsoleteFuncAttrs) {
2464 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2465 FuncAttrs &= ~ObsoleteFuncAttrs;
2466 }
2467
2468 if (RetAttrs != Attribute::None)
2469 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2470
2471 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2472 ParamTypeList.push_back(ArgList[i].Type);
2473 if (ArgList[i].Attrs != Attribute::None)
2474 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2475 }
2476
2477 if (FuncAttrs != Attribute::None)
2478 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2479
2480 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2481
Chris Lattnera9a9e072009-03-09 04:49:14 +00002482 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002483 RetType != Type::getVoidTy(Context))
Chris Lattnera9a9e072009-03-09 04:49:14 +00002484 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2485
Owen Andersonfba933c2009-07-01 23:57:11 +00002486 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002487 FunctionType::get(RetType, ParamTypeList, isVarArg);
2488 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002489
2490 Fn = 0;
2491 if (!FunctionName.empty()) {
2492 // If this was a definition of a forward reference, remove the definition
2493 // from the forward reference table and fill in the forward ref.
2494 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2495 ForwardRefVals.find(FunctionName);
2496 if (FRVI != ForwardRefVals.end()) {
2497 Fn = M->getFunction(FunctionName);
2498 ForwardRefVals.erase(FRVI);
2499 } else if ((Fn = M->getFunction(FunctionName))) {
2500 // If this function already exists in the symbol table, then it is
2501 // multiply defined. We accept a few cases for old backwards compat.
2502 // FIXME: Remove this stuff for LLVM 3.0.
2503 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2504 (!Fn->isDeclaration() && isDefine)) {
2505 // If the redefinition has different type or different attributes,
2506 // reject it. If both have bodies, reject it.
2507 return Error(NameLoc, "invalid redefinition of function '" +
2508 FunctionName + "'");
2509 } else if (Fn->isDeclaration()) {
2510 // Make sure to strip off any argument names so we can't get conflicts.
2511 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2512 AI != AE; ++AI)
2513 AI->setName("");
2514 }
2515 }
2516
Dan Gohman41905542009-08-29 23:37:49 +00002517 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002518 // If this is a definition of a forward referenced function, make sure the
2519 // types agree.
2520 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2521 = ForwardRefValIDs.find(NumberedVals.size());
2522 if (I != ForwardRefValIDs.end()) {
2523 Fn = cast<Function>(I->second.first);
2524 if (Fn->getType() != PFT)
2525 return Error(NameLoc, "type of definition and forward reference of '@" +
2526 utostr(NumberedVals.size()) +"' disagree");
2527 ForwardRefValIDs.erase(I);
2528 }
2529 }
2530
2531 if (Fn == 0)
2532 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2533 else // Move the forward-reference to the correct spot in the module.
2534 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2535
2536 if (FunctionName.empty())
2537 NumberedVals.push_back(Fn);
2538
2539 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2540 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2541 Fn->setCallingConv(CC);
2542 Fn->setAttributes(PAL);
2543 Fn->setAlignment(Alignment);
2544 Fn->setSection(Section);
2545 if (!GC.empty()) Fn->setGC(GC.c_str());
2546
2547 // Add all of the arguments we parsed to the function.
2548 Function::arg_iterator ArgIt = Fn->arg_begin();
2549 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2550 // If the argument has a name, insert it into the argument symbol table.
2551 if (ArgList[i].Name.empty()) continue;
2552
2553 // Set the name, if it conflicted, it will be auto-renamed.
2554 ArgIt->setName(ArgList[i].Name);
2555
2556 if (ArgIt->getNameStr() != ArgList[i].Name)
2557 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2558 ArgList[i].Name + "'");
2559 }
2560
2561 return false;
2562}
2563
2564
2565/// ParseFunctionBody
2566/// ::= '{' BasicBlock+ '}'
2567/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2568///
2569bool LLParser::ParseFunctionBody(Function &Fn) {
2570 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2571 return TokError("expected '{' in function body");
2572 Lex.Lex(); // eat the {.
2573
2574 PerFunctionState PFS(*this, Fn);
2575
2576 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2577 if (ParseBasicBlock(PFS)) return true;
2578
2579 // Eat the }.
2580 Lex.Lex();
2581
2582 // Verify function is ok.
2583 return PFS.VerifyFunctionComplete();
2584}
2585
2586/// ParseBasicBlock
2587/// ::= LabelStr? Instruction*
2588bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2589 // If this basic block starts out with a name, remember it.
2590 std::string Name;
2591 LocTy NameLoc = Lex.getLoc();
2592 if (Lex.getKind() == lltok::LabelStr) {
2593 Name = Lex.getStrVal();
2594 Lex.Lex();
2595 }
2596
2597 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2598 if (BB == 0) return true;
2599
2600 std::string NameStr;
2601
2602 // Parse the instructions in this block until we get a terminator.
2603 Instruction *Inst;
2604 do {
2605 // This instruction may have three possibilities for a name: a) none
2606 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2607 LocTy NameLoc = Lex.getLoc();
2608 int NameID = -1;
2609 NameStr = "";
2610
2611 if (Lex.getKind() == lltok::LocalVarID) {
2612 NameID = Lex.getUIntVal();
2613 Lex.Lex();
2614 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2615 return true;
2616 } else if (Lex.getKind() == lltok::LocalVar ||
2617 // FIXME: REMOVE IN LLVM 3.0
2618 Lex.getKind() == lltok::StringConstant) {
2619 NameStr = Lex.getStrVal();
2620 Lex.Lex();
2621 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2622 return true;
2623 }
2624
2625 if (ParseInstruction(Inst, BB, PFS)) return true;
2626
Devang Patelcea188a2009-09-16 18:18:06 +00002627 // Parse optional debug info
2628 if (Lex.getKind() == lltok::comma) {
2629 Lex.Lex();
2630 if (Lex.getKind() == lltok::kw_dbg) {
2631 Lex.Lex();
2632 if (Lex.getKind() != lltok::Metadata)
2633 return TokError("Expected '!' here");
2634 Lex.Lex();
2635 MetadataBase *N = 0;
2636 if (ParseMDNode(N)) return true;
2637 Metadata &TheMetadata = M->getContext().getMetadata();
2638 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
2639 if (!MDDbgKind)
2640 MDDbgKind = TheMetadata.RegisterMDKind("dbg");
2641 TheMetadata.setMD(MDDbgKind, cast<MDNode>(N), Inst);
2642 }
2643 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002644 BB->getInstList().push_back(Inst);
2645
2646 // Set the name on the instruction.
2647 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2648 } while (!isa<TerminatorInst>(Inst));
2649
2650 return false;
2651}
2652
2653//===----------------------------------------------------------------------===//
2654// Instruction Parsing.
2655//===----------------------------------------------------------------------===//
2656
2657/// ParseInstruction - Parse one of the many different instructions.
2658///
2659bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2660 PerFunctionState &PFS) {
2661 lltok::Kind Token = Lex.getKind();
2662 if (Token == lltok::Eof)
2663 return TokError("found end of file when expecting more instructions");
2664 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002665 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002666 Lex.Lex(); // Eat the keyword.
2667
2668 switch (Token) {
2669 default: return Error(Loc, "expected instruction opcode");
2670 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002671 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2672 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002673 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2674 case lltok::kw_br: return ParseBr(Inst, PFS);
2675 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2676 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2677 // Binary Operators.
2678 case lltok::kw_add:
2679 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002680 case lltok::kw_mul: {
2681 bool NUW = false;
2682 bool NSW = false;
2683 LocTy ModifierLoc = Lex.getLoc();
2684 if (EatIfPresent(lltok::kw_nuw))
2685 NUW = true;
2686 if (EatIfPresent(lltok::kw_nsw)) {
2687 NSW = true;
2688 if (EatIfPresent(lltok::kw_nuw))
2689 NUW = true;
2690 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002691 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002692 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2693 if (!Result) {
2694 if (!Inst->getType()->isIntOrIntVector()) {
2695 if (NUW)
2696 return Error(ModifierLoc, "nuw only applies to integer operations");
2697 if (NSW)
2698 return Error(ModifierLoc, "nsw only applies to integer operations");
2699 }
2700 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002701 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002702 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002703 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002704 }
2705 return Result;
2706 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002707 case lltok::kw_fadd:
2708 case lltok::kw_fsub:
2709 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2710
Dan Gohman59858cf2009-07-27 16:11:46 +00002711 case lltok::kw_sdiv: {
2712 bool Exact = false;
2713 if (EatIfPresent(lltok::kw_exact))
2714 Exact = true;
2715 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2716 if (!Result)
2717 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002718 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002719 return Result;
2720 }
2721
Chris Lattnerdf986172009-01-02 07:01:27 +00002722 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002724 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002725 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002726 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 case lltok::kw_shl:
2728 case lltok::kw_lshr:
2729 case lltok::kw_ashr:
2730 case lltok::kw_and:
2731 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002732 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002733 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002734 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002735 // Casts.
2736 case lltok::kw_trunc:
2737 case lltok::kw_zext:
2738 case lltok::kw_sext:
2739 case lltok::kw_fptrunc:
2740 case lltok::kw_fpext:
2741 case lltok::kw_bitcast:
2742 case lltok::kw_uitofp:
2743 case lltok::kw_sitofp:
2744 case lltok::kw_fptoui:
2745 case lltok::kw_fptosi:
2746 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002747 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 // Other.
2749 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002750 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2752 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2753 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2754 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2755 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2756 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2757 // Memory.
2758 case lltok::kw_alloca:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002759 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002760 case lltok::kw_free: return ParseFree(Inst, PFS);
2761 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2762 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2763 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002764 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002766 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002768 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002769 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2771 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2772 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2773 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2774 }
2775}
2776
2777/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2778bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002779 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002780 switch (Lex.getKind()) {
2781 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2782 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2783 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2784 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2785 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2786 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2787 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2788 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2789 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2790 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2791 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2792 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2793 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2794 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2795 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2796 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2797 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2798 }
2799 } else {
2800 switch (Lex.getKind()) {
2801 default: TokError("expected icmp predicate (e.g. 'eq')");
2802 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2803 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2804 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2805 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2806 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2807 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2808 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2809 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2810 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2811 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2812 }
2813 }
2814 Lex.Lex();
2815 return false;
2816}
2817
2818//===----------------------------------------------------------------------===//
2819// Terminator Instructions.
2820//===----------------------------------------------------------------------===//
2821
2822/// ParseRet - Parse a return instruction.
2823/// ::= 'ret' void
2824/// ::= 'ret' TypeAndValue
2825/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2826bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2827 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002828 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002829 if (ParseType(Ty, true /*void allowed*/)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002830
Owen Anderson1d0be152009-08-13 21:58:54 +00002831 if (Ty == Type::getVoidTy(Context)) {
2832 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 return false;
2834 }
2835
2836 Value *RV;
2837 if (ParseValue(Ty, RV, PFS)) return true;
2838
2839 // The normal case is one return value.
2840 if (Lex.getKind() == lltok::comma) {
2841 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2842 // of 'ret {i32,i32} {i32 1, i32 2}'
2843 SmallVector<Value*, 8> RVs;
2844 RVs.push_back(RV);
2845
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002846 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002847 if (ParseTypeAndValue(RV, PFS)) return true;
2848 RVs.push_back(RV);
2849 }
2850
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002851 RV = UndefValue::get(PFS.getFunction().getReturnType());
Chris Lattnerdf986172009-01-02 07:01:27 +00002852 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2853 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2854 BB->getInstList().push_back(I);
2855 RV = I;
2856 }
2857 }
Owen Anderson1d0be152009-08-13 21:58:54 +00002858 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 return false;
2860}
2861
2862
2863/// ParseBr
2864/// ::= 'br' TypeAndValue
2865/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2866bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2867 LocTy Loc, Loc2;
2868 Value *Op0, *Op1, *Op2;
2869 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2870
2871 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2872 Inst = BranchInst::Create(BB);
2873 return false;
2874 }
2875
Owen Anderson1d0be152009-08-13 21:58:54 +00002876 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002877 return Error(Loc, "branch condition must have 'i1' type");
2878
2879 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2880 ParseTypeAndValue(Op1, Loc, PFS) ||
2881 ParseToken(lltok::comma, "expected ',' after true destination") ||
2882 ParseTypeAndValue(Op2, Loc2, PFS))
2883 return true;
2884
2885 if (!isa<BasicBlock>(Op1))
2886 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 if (!isa<BasicBlock>(Op2))
2888 return Error(Loc2, "true destination of branch must be a basic block");
2889
2890 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2891 return false;
2892}
2893
2894/// ParseSwitch
2895/// Instruction
2896/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2897/// JumpTable
2898/// ::= (TypeAndValue ',' TypeAndValue)*
2899bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2900 LocTy CondLoc, BBLoc;
2901 Value *Cond, *DefaultBB;
2902 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2903 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2904 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2905 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2906 return true;
2907
2908 if (!isa<IntegerType>(Cond->getType()))
2909 return Error(CondLoc, "switch condition must have integer type");
2910 if (!isa<BasicBlock>(DefaultBB))
2911 return Error(BBLoc, "default destination must be a basic block");
2912
2913 // Parse the jump table pairs.
2914 SmallPtrSet<Value*, 32> SeenCases;
2915 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2916 while (Lex.getKind() != lltok::rsquare) {
2917 Value *Constant, *DestBB;
2918
2919 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2920 ParseToken(lltok::comma, "expected ',' after case value") ||
2921 ParseTypeAndValue(DestBB, BBLoc, PFS))
2922 return true;
2923
2924 if (!SeenCases.insert(Constant))
2925 return Error(CondLoc, "duplicate case value in switch");
2926 if (!isa<ConstantInt>(Constant))
2927 return Error(CondLoc, "case value is not a constant integer");
2928 if (!isa<BasicBlock>(DestBB))
2929 return Error(BBLoc, "case destination is not a basic block");
2930
2931 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2932 cast<BasicBlock>(DestBB)));
2933 }
2934
2935 Lex.Lex(); // Eat the ']'.
2936
2937 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2938 Table.size());
2939 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2940 SI->addCase(Table[i].first, Table[i].second);
2941 Inst = SI;
2942 return false;
2943}
2944
2945/// ParseInvoke
2946/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2947/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2948bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2949 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002950 unsigned RetAttrs, FnAttrs;
2951 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002952 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 LocTy RetTypeLoc;
2954 ValID CalleeID;
2955 SmallVector<ParamInfo, 16> ArgList;
2956
2957 Value *NormalBB, *UnwindBB;
2958 if (ParseOptionalCallingConv(CC) ||
2959 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002960 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002961 ParseValID(CalleeID) ||
2962 ParseParameterList(ArgList, PFS) ||
2963 ParseOptionalAttrs(FnAttrs, 2) ||
2964 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2965 ParseTypeAndValue(NormalBB, PFS) ||
2966 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2967 ParseTypeAndValue(UnwindBB, PFS))
2968 return true;
2969
2970 if (!isa<BasicBlock>(NormalBB))
2971 return Error(CallLoc, "normal destination is not a basic block");
2972 if (!isa<BasicBlock>(UnwindBB))
2973 return Error(CallLoc, "unwind destination is not a basic block");
2974
2975 // If RetType is a non-function pointer type, then this is the short syntax
2976 // for the call, which means that RetType is just the return type. Infer the
2977 // rest of the function argument types from the arguments that are present.
2978 const PointerType *PFTy = 0;
2979 const FunctionType *Ty = 0;
2980 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2981 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2982 // Pull out the types of all of the arguments...
2983 std::vector<const Type*> ParamTypes;
2984 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2985 ParamTypes.push_back(ArgList[i].V->getType());
2986
2987 if (!FunctionType::isValidReturnType(RetType))
2988 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2989
Owen Andersondebcb012009-07-29 22:17:13 +00002990 Ty = FunctionType::get(RetType, ParamTypes, false);
2991 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002992 }
2993
2994 // Look up the callee.
2995 Value *Callee;
2996 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2997
2998 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2999 // function attributes.
3000 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3001 if (FnAttrs & ObsoleteFuncAttrs) {
3002 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3003 FnAttrs &= ~ObsoleteFuncAttrs;
3004 }
3005
3006 // Set up the Attributes for the function.
3007 SmallVector<AttributeWithIndex, 8> Attrs;
3008 if (RetAttrs != Attribute::None)
3009 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3010
3011 SmallVector<Value*, 8> Args;
3012
3013 // Loop through FunctionType's arguments and ensure they are specified
3014 // correctly. Also, gather any parameter attributes.
3015 FunctionType::param_iterator I = Ty->param_begin();
3016 FunctionType::param_iterator E = Ty->param_end();
3017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3018 const Type *ExpectedTy = 0;
3019 if (I != E) {
3020 ExpectedTy = *I++;
3021 } else if (!Ty->isVarArg()) {
3022 return Error(ArgList[i].Loc, "too many arguments specified");
3023 }
3024
3025 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3026 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3027 ExpectedTy->getDescription() + "'");
3028 Args.push_back(ArgList[i].V);
3029 if (ArgList[i].Attrs != Attribute::None)
3030 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3031 }
3032
3033 if (I != E)
3034 return Error(CallLoc, "not enough parameters specified for call");
3035
3036 if (FnAttrs != Attribute::None)
3037 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3038
3039 // Finish off the Attributes and check them
3040 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3041
3042 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3043 cast<BasicBlock>(UnwindBB),
3044 Args.begin(), Args.end());
3045 II->setCallingConv(CC);
3046 II->setAttributes(PAL);
3047 Inst = II;
3048 return false;
3049}
3050
3051
3052
3053//===----------------------------------------------------------------------===//
3054// Binary Operators.
3055//===----------------------------------------------------------------------===//
3056
3057/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003058/// ::= ArithmeticOps TypeAndValue ',' Value
3059///
3060/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3061/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003062bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003063 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 LocTy Loc; Value *LHS, *RHS;
3065 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3066 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3067 ParseValue(LHS->getType(), RHS, PFS))
3068 return true;
3069
Chris Lattnere914b592009-01-05 08:24:46 +00003070 bool Valid;
3071 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003072 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003073 case 0: // int or FP.
3074 Valid = LHS->getType()->isIntOrIntVector() ||
3075 LHS->getType()->isFPOrFPVector();
3076 break;
3077 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3078 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3079 }
3080
3081 if (!Valid)
3082 return Error(Loc, "invalid operand type for instruction");
Chris Lattnerdf986172009-01-02 07:01:27 +00003083
3084 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3085 return false;
3086}
3087
3088/// ParseLogical
3089/// ::= ArithmeticOps TypeAndValue ',' Value {
3090bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3091 unsigned Opc) {
3092 LocTy Loc; Value *LHS, *RHS;
3093 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3094 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3095 ParseValue(LHS->getType(), RHS, PFS))
3096 return true;
3097
3098 if (!LHS->getType()->isIntOrIntVector())
3099 return Error(Loc,"instruction requires integer or integer vector operands");
3100
3101 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3102 return false;
3103}
3104
3105
3106/// ParseCompare
3107/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3108/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003109bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3110 unsigned Opc) {
3111 // Parse the integer/fp comparison predicate.
3112 LocTy Loc;
3113 unsigned Pred;
3114 Value *LHS, *RHS;
3115 if (ParseCmpPredicate(Pred, Opc) ||
3116 ParseTypeAndValue(LHS, Loc, PFS) ||
3117 ParseToken(lltok::comma, "expected ',' after compare value") ||
3118 ParseValue(LHS->getType(), RHS, PFS))
3119 return true;
3120
3121 if (Opc == Instruction::FCmp) {
3122 if (!LHS->getType()->isFPOrFPVector())
3123 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003124 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003125 } else {
3126 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003127 if (!LHS->getType()->isIntOrIntVector() &&
3128 !isa<PointerType>(LHS->getType()))
3129 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003130 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003131 }
3132 return false;
3133}
3134
3135//===----------------------------------------------------------------------===//
3136// Other Instructions.
3137//===----------------------------------------------------------------------===//
3138
3139
3140/// ParseCast
3141/// ::= CastOpc TypeAndValue 'to' Type
3142bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3143 unsigned Opc) {
3144 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003145 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003146 if (ParseTypeAndValue(Op, Loc, PFS) ||
3147 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3148 ParseType(DestTy))
3149 return true;
3150
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003151 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3152 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003153 return Error(Loc, "invalid cast opcode for cast from '" +
3154 Op->getType()->getDescription() + "' to '" +
3155 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003156 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3158 return false;
3159}
3160
3161/// ParseSelect
3162/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3163bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3164 LocTy Loc;
3165 Value *Op0, *Op1, *Op2;
3166 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3167 ParseToken(lltok::comma, "expected ',' after select condition") ||
3168 ParseTypeAndValue(Op1, PFS) ||
3169 ParseToken(lltok::comma, "expected ',' after select value") ||
3170 ParseTypeAndValue(Op2, PFS))
3171 return true;
3172
3173 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3174 return Error(Loc, Reason);
3175
3176 Inst = SelectInst::Create(Op0, Op1, Op2);
3177 return false;
3178}
3179
Chris Lattner0088a5c2009-01-05 08:18:44 +00003180/// ParseVA_Arg
3181/// ::= 'va_arg' TypeAndValue ',' Type
3182bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003184 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003185 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (ParseTypeAndValue(Op, PFS) ||
3187 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003188 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 return true;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003190
3191 if (!EltTy->isFirstClassType())
3192 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003193
3194 Inst = new VAArgInst(Op, EltTy);
3195 return false;
3196}
3197
3198/// ParseExtractElement
3199/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3200bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3201 LocTy Loc;
3202 Value *Op0, *Op1;
3203 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3204 ParseToken(lltok::comma, "expected ',' after extract value") ||
3205 ParseTypeAndValue(Op1, PFS))
3206 return true;
3207
3208 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3209 return Error(Loc, "invalid extractelement operands");
3210
Eric Christophera3500da2009-07-25 02:28:41 +00003211 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 return false;
3213}
3214
3215/// ParseInsertElement
3216/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3217bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3218 LocTy Loc;
3219 Value *Op0, *Op1, *Op2;
3220 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3221 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3222 ParseTypeAndValue(Op1, PFS) ||
3223 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3224 ParseTypeAndValue(Op2, PFS))
3225 return true;
3226
3227 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003228 return Error(Loc, "invalid insertelement operands");
Chris Lattnerdf986172009-01-02 07:01:27 +00003229
3230 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3231 return false;
3232}
3233
3234/// ParseShuffleVector
3235/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3236bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3237 LocTy Loc;
3238 Value *Op0, *Op1, *Op2;
3239 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3240 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3241 ParseTypeAndValue(Op1, PFS) ||
3242 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3243 ParseTypeAndValue(Op2, PFS))
3244 return true;
3245
3246 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3247 return Error(Loc, "invalid extractelement operands");
3248
3249 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3250 return false;
3251}
3252
3253/// ParsePHI
3254/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3255bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003256 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 Value *Op0, *Op1;
3258 LocTy TypeLoc = Lex.getLoc();
3259
3260 if (ParseType(Ty) ||
3261 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3262 ParseValue(Ty, Op0, PFS) ||
3263 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003264 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003265 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3266 return true;
3267
3268 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3269 while (1) {
3270 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3271
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003272 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 break;
3274
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003275 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 ParseValue(Ty, Op0, PFS) ||
3277 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003278 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3280 return true;
3281 }
3282
3283 if (!Ty->isFirstClassType())
3284 return Error(TypeLoc, "phi node must have first class type");
3285
3286 PHINode *PN = PHINode::Create(Ty);
3287 PN->reserveOperandSpace(PHIVals.size());
3288 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3289 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3290 Inst = PN;
3291 return false;
3292}
3293
3294/// ParseCall
3295/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3296/// ParameterList OptionalAttrs
3297bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3298 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003299 unsigned RetAttrs, FnAttrs;
3300 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003301 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003302 LocTy RetTypeLoc;
3303 ValID CalleeID;
3304 SmallVector<ParamInfo, 16> ArgList;
3305 LocTy CallLoc = Lex.getLoc();
3306
3307 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3308 ParseOptionalCallingConv(CC) ||
3309 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003310 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 ParseValID(CalleeID) ||
3312 ParseParameterList(ArgList, PFS) ||
3313 ParseOptionalAttrs(FnAttrs, 2))
3314 return true;
3315
3316 // If RetType is a non-function pointer type, then this is the short syntax
3317 // for the call, which means that RetType is just the return type. Infer the
3318 // rest of the function argument types from the arguments that are present.
3319 const PointerType *PFTy = 0;
3320 const FunctionType *Ty = 0;
3321 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3322 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3323 // Pull out the types of all of the arguments...
3324 std::vector<const Type*> ParamTypes;
3325 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3326 ParamTypes.push_back(ArgList[i].V->getType());
3327
3328 if (!FunctionType::isValidReturnType(RetType))
3329 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3330
Owen Andersondebcb012009-07-29 22:17:13 +00003331 Ty = FunctionType::get(RetType, ParamTypes, false);
3332 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 }
3334
3335 // Look up the callee.
3336 Value *Callee;
3337 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3338
Chris Lattnerdf986172009-01-02 07:01:27 +00003339 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3340 // function attributes.
3341 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3342 if (FnAttrs & ObsoleteFuncAttrs) {
3343 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3344 FnAttrs &= ~ObsoleteFuncAttrs;
3345 }
3346
3347 // Set up the Attributes for the function.
3348 SmallVector<AttributeWithIndex, 8> Attrs;
3349 if (RetAttrs != Attribute::None)
3350 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3351
3352 SmallVector<Value*, 8> Args;
3353
3354 // Loop through FunctionType's arguments and ensure they are specified
3355 // correctly. Also, gather any parameter attributes.
3356 FunctionType::param_iterator I = Ty->param_begin();
3357 FunctionType::param_iterator E = Ty->param_end();
3358 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3359 const Type *ExpectedTy = 0;
3360 if (I != E) {
3361 ExpectedTy = *I++;
3362 } else if (!Ty->isVarArg()) {
3363 return Error(ArgList[i].Loc, "too many arguments specified");
3364 }
3365
3366 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3367 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3368 ExpectedTy->getDescription() + "'");
3369 Args.push_back(ArgList[i].V);
3370 if (ArgList[i].Attrs != Attribute::None)
3371 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3372 }
3373
3374 if (I != E)
3375 return Error(CallLoc, "not enough parameters specified for call");
3376
3377 if (FnAttrs != Attribute::None)
3378 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3379
3380 // Finish off the Attributes and check them
3381 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3382
3383 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3384 CI->setTailCall(isTail);
3385 CI->setCallingConv(CC);
3386 CI->setAttributes(PAL);
3387 Inst = CI;
3388 return false;
3389}
3390
3391//===----------------------------------------------------------------------===//
3392// Memory Instructions.
3393//===----------------------------------------------------------------------===//
3394
3395/// ParseAlloc
3396/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3397/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3398bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3399 unsigned Opc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003400 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003401 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003402 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003404 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003405
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003406 if (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003407 if (Lex.getKind() == lltok::kw_align) {
3408 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003409 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3410 ParseOptionalCommaAlignment(Alignment)) {
3411 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 }
3413 }
3414
Owen Anderson1d0be152009-08-13 21:58:54 +00003415 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003416 return Error(SizeLoc, "element count must be i32");
3417
3418 if (Opc == Instruction::Malloc)
Owen Anderson50dead02009-07-15 23:53:25 +00003419 Inst = new MallocInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003420 else
Owen Anderson50dead02009-07-15 23:53:25 +00003421 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 return false;
3423}
3424
3425/// ParseFree
3426/// ::= 'free' TypeAndValue
3427bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3428 Value *Val; LocTy Loc;
3429 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3430 if (!isa<PointerType>(Val->getType()))
3431 return Error(Loc, "operand to free must be a pointer");
3432 Inst = new FreeInst(Val);
3433 return false;
3434}
3435
3436/// ParseLoad
Dan Gohmana119de82009-06-14 23:30:43 +00003437/// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003438bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3439 bool isVolatile) {
3440 Value *Val; LocTy Loc;
3441 unsigned Alignment;
3442 if (ParseTypeAndValue(Val, Loc, PFS) ||
3443 ParseOptionalCommaAlignment(Alignment))
3444 return true;
3445
3446 if (!isa<PointerType>(Val->getType()) ||
3447 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3448 return Error(Loc, "load operand must be a pointer to a first class type");
3449
3450 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3451 return false;
3452}
3453
3454/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003455/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003456bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3457 bool isVolatile) {
3458 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3459 unsigned Alignment;
3460 if (ParseTypeAndValue(Val, Loc, PFS) ||
3461 ParseToken(lltok::comma, "expected ',' after store operand") ||
3462 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3463 ParseOptionalCommaAlignment(Alignment))
3464 return true;
3465
3466 if (!isa<PointerType>(Ptr->getType()))
3467 return Error(PtrLoc, "store operand must be a pointer");
3468 if (!Val->getType()->isFirstClassType())
3469 return Error(Loc, "store operand must be a first class value");
3470 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3471 return Error(Loc, "stored value and pointer type do not match");
3472
3473 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3474 return false;
3475}
3476
3477/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003478/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003479/// FIXME: Remove support for getresult in LLVM 3.0
3480bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3481 Value *Val; LocTy ValLoc, EltLoc;
3482 unsigned Element;
3483 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3484 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003485 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003486 return true;
3487
3488 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3489 return Error(ValLoc, "getresult inst requires an aggregate operand");
3490 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3491 return Error(EltLoc, "invalid getresult index for value");
3492 Inst = ExtractValueInst::Create(Val, Element);
3493 return false;
3494}
3495
3496/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003497/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003498bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3499 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003500
Dan Gohmandcb40a32009-07-29 15:58:36 +00003501 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003502
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003503 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003504
3505 if (!isa<PointerType>(Ptr->getType()))
3506 return Error(Loc, "base of getelementptr must be a pointer");
3507
3508 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003509 while (EatIfPresent(lltok::comma)) {
3510 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 if (!isa<IntegerType>(Val->getType()))
3512 return Error(EltLoc, "getelementptr index must be an integer");
3513 Indices.push_back(Val);
3514 }
3515
3516 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3517 Indices.begin(), Indices.end()))
3518 return Error(Loc, "invalid getelementptr indices");
3519 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003520 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003521 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 return false;
3523}
3524
3525/// ParseExtractValue
3526/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3527bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3528 Value *Val; LocTy Loc;
3529 SmallVector<unsigned, 4> Indices;
3530 if (ParseTypeAndValue(Val, Loc, PFS) ||
3531 ParseIndexList(Indices))
3532 return true;
3533
3534 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3535 return Error(Loc, "extractvalue operand must be array or struct");
3536
3537 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3538 Indices.end()))
3539 return Error(Loc, "invalid indices for extractvalue");
3540 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3541 return false;
3542}
3543
3544/// ParseInsertValue
3545/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3546bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3547 Value *Val0, *Val1; LocTy Loc0, Loc1;
3548 SmallVector<unsigned, 4> Indices;
3549 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3550 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3551 ParseTypeAndValue(Val1, Loc1, PFS) ||
3552 ParseIndexList(Indices))
3553 return true;
3554
3555 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3556 return Error(Loc0, "extractvalue operand must be array or struct");
3557
3558 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3559 Indices.end()))
3560 return Error(Loc0, "invalid indices for insertvalue");
3561 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3562 return false;
3563}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003564
3565//===----------------------------------------------------------------------===//
3566// Embedded metadata.
3567//===----------------------------------------------------------------------===//
3568
3569/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003570/// ::= Element (',' Element)*
3571/// Element
3572/// ::= 'null' | TypeAndValue
3573bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003574 assert(Lex.getKind() == lltok::lbrace);
3575 Lex.Lex();
3576 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003577 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003578 if (Lex.getKind() == lltok::kw_null) {
3579 Lex.Lex();
3580 V = 0;
3581 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003582 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003583 if (ParseType(Ty)) return true;
3584 if (Lex.getKind() == lltok::Metadata) {
3585 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003586 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003587 if (!ParseMDNode(Node))
3588 V = Node;
3589 else {
3590 MetadataBase *MDS = 0;
3591 if (ParseMDString(MDS)) return true;
3592 V = MDS;
3593 }
3594 } else {
3595 Constant *C;
3596 if (ParseGlobalValue(Ty, C)) return true;
3597 V = C;
3598 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003599 }
3600 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003601 } while (EatIfPresent(lltok::comma));
3602
3603 return false;
3604}