blob: 1e1ddf07d2e5e45419e2728e294abd630999430d [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;
Daniel Dunbara279bc32009-09-20 02:20:51 +000048
Chris Lattnerdf986172009-01-02 07:01:27 +000049 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) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000080
Chris Lattnerdf986172009-01-02 07:01:27 +000081 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
84 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000085
Chris Lattnerdf986172009-01-02 07:01:27 +000086 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000090
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) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000095
Devang Patel1c7eea62009-07-08 19:23:54 +000096
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
Daniel Dunbara279bc32009-09-20 02:20:51 +0000100
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 Patel0475c912009-09-29 00:01:14 +0000128 case lltok::NamedOrCustomMD: 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000163
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 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();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000180
181 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000182 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
183 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000184
Chris Lattnerdf986172009-01-02 07:01:27 +0000185 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000231 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000266
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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000273
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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000278
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 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.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Owen Anderson1d0be152009-08-13 21:58:54 +0000291 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000293 if (ParseToken(lltok::equal, "expected '=' after name") ||
294 ParseToken(lltok::kw_type, "expected 'type' after name") ||
295 ParseType(Ty))
296 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 // 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?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000318
Chris Lattnerdf986172009-01-02 07:01:27 +0000319 // 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000323
Chris Lattnerdf986172009-01-02 07:01:27 +0000324 // 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();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000335
Chris Lattnerdf986172009-01-02 07:01:27 +0000336 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();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Dan Gohman3845e502009-08-12 23:32:33 +0000394 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();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000407
Chris Lattnerdf986172009-01-02 07:01:27 +0000408 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000414
Chris Lattnerdf986172009-01-02 07:01:27 +0000415 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000435
Devang Patel256be962009-07-20 19:00:08 +0000436 // 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459}
Devang Patel256be962009-07-20 19:00:08 +0000460
Devang Pateleff2ab62009-07-29 00:34:02 +0000461///ParseNamedMetadata:
462/// !foo = !{ !1, !2 }
463bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000464 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000465 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:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000496/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000497bool 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000512
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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000521 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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000563
Chris Lattnerdf986172009-01-02 07:01:27 +0000564 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000577
Chris Lattnerdf986172009-01-02 07:01:27 +0000578 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);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586
Chris Lattnerdf986172009-01-02 07:01:27 +0000587 // 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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000603
Chris Lattnerdf986172009-01-02 07:01:27 +0000604 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000610
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 // 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!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000614
Chris Lattnerdf986172009-01-02 07:01:27 +0000615 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000632
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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000639
Chris Lattnerdf986172009-01-02 07:01:27 +0000640 // 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
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000650 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000651 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 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) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000670 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000671 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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // 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);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000683
Chris Lattnerdf986172009-01-02 07:01:27 +0000684 // 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);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000691
Chris Lattnerdf986172009-01-02 07:01:27 +0000692 // Parse attributes on the global.
693 while (Lex.getKind() == lltok::comma) {
694 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000695
Chris Lattnerdf986172009-01-02 07:01:27 +0000696 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000709
Chris Lattnerdf986172009-01-02 07:01:27 +0000710 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000728
Chris Lattnerdf986172009-01-02 07:01:27 +0000729 // Look this name up in the normal function symbol table.
730 GlobalValue *Val =
731 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattnerdf986172009-01-02 07:01:27 +0000733 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000741
Chris Lattnerdf986172009-01-02 07:01:27 +0000742 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattnerdf986172009-01-02 07:01:27 +0000765 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattnerdf986172009-01-02 07:01:27 +0000778 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000786
Chris Lattnerdf986172009-01-02 07:01:27 +0000787 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 // 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000808
Chris Lattnerdf986172009-01-02 07:01:27 +0000809 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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861}
Chris Lattnerdf986172009-01-02 07:01:27 +0000862
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();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000870
Chris Lattnerdf986172009-01-02 07:01:27 +0000871 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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000891
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");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000894
Chris Lattnerdf986172009-01-02 07:01:27 +0000895 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;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000918
Chris Lattnerdf986172009-01-02 07:01:27 +0000919 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'
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977///
Chris Lattnerdf986172009-01-02 07:01:27 +0000978bool 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 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001023
Chris Lattnerdf986172009-01-02 07:01:27 +00001024 Lex.Lex();
1025 return false;
1026}
1027
Devang Patel0475c912009-09-29 00:01:14 +00001028/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001029/// ::= /* empty */
Devang Patel0475c912009-09-29 00:01:14 +00001030/// ::= !dbg !42
1031bool LLParser::ParseOptionalCustomMetadata() {
Devang Patelf633a062009-09-17 23:04:48 +00001032
Devang Patel0475c912009-09-29 00:01:14 +00001033 std::string Name;
1034 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1035 Name = Lex.getStrVal();
1036 Lex.Lex();
1037 } else
Devang Patelf633a062009-09-17 23:04:48 +00001038 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001039
Devang Patelf633a062009-09-17 23:04:48 +00001040 if (Lex.getKind() != lltok::Metadata)
1041 return TokError("Expected '!' here");
1042 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001043
Devang Patelf633a062009-09-17 23:04:48 +00001044 MetadataBase *Node;
1045 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001046
Devang Patele30e6782009-09-28 21:41:20 +00001047 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001048 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1049 if (!MDK)
1050 MDK = TheMetadata.RegisterMDKind(Name.c_str());
1051 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001052
Devang Patelf633a062009-09-17 23:04:48 +00001053 return false;
1054}
1055
Chris Lattnerdf986172009-01-02 07:01:27 +00001056/// ParseOptionalAlignment
1057/// ::= /* empty */
1058/// ::= 'align' 4
1059bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1060 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001061 if (!EatIfPresent(lltok::kw_align))
1062 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001063 LocTy AlignLoc = Lex.getLoc();
1064 if (ParseUInt32(Alignment)) return true;
1065 if (!isPowerOf2_32(Alignment))
1066 return Error(AlignLoc, "alignment is not a power of two");
1067 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001068}
1069
Devang Patelf633a062009-09-17 23:04:48 +00001070/// ParseOptionalInfo
1071/// ::= OptionalInfo (',' OptionalInfo)+
1072bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1073
1074 // FIXME: Handle customized metadata info attached with an instruction.
1075 do {
Devang Patel0475c912009-09-29 00:01:14 +00001076 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1077 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001078 } else if (Lex.getKind() == lltok::kw_align) {
1079 if (ParseOptionalAlignment(Alignment)) return true;
1080 } else
1081 return true;
1082 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001083
Devang Patelf633a062009-09-17 23:04:48 +00001084 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001085}
1086
Devang Patelf633a062009-09-17 23:04:48 +00001087
Chris Lattnerdf986172009-01-02 07:01:27 +00001088/// ParseIndexList
1089/// ::= (',' uint32)+
1090bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1091 if (Lex.getKind() != lltok::comma)
1092 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001093
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001094 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001095 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001096 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001097 Indices.push_back(Idx);
1098 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001099
Chris Lattnerdf986172009-01-02 07:01:27 +00001100 return false;
1101}
1102
1103//===----------------------------------------------------------------------===//
1104// Type Parsing.
1105//===----------------------------------------------------------------------===//
1106
1107/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001108bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1109 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001110 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001111
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 // Verify no unresolved uprefs.
1113 if (!UpRefs.empty())
1114 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001116 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001117 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001118
Chris Lattnerdf986172009-01-02 07:01:27 +00001119 return false;
1120}
1121
1122/// HandleUpRefs - Every time we finish a new layer of types, this function is
1123/// called. It loops through the UpRefs vector, which is a list of the
1124/// currently active types. For each type, if the up-reference is contained in
1125/// the newly completed type, we decrement the level count. When the level
1126/// count reaches zero, the up-referenced type is the type that is passed in:
1127/// thus we can complete the cycle.
1128///
1129PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1130 // If Ty isn't abstract, or if there are no up-references in it, then there is
1131 // nothing to resolve here.
1132 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001133
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 PATypeHolder Ty(ty);
1135#if 0
1136 errs() << "Type '" << Ty->getDescription()
1137 << "' newly formed. Resolving upreferences.\n"
1138 << UpRefs.size() << " upreferences active!\n";
1139#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1142 // to zero), we resolve them all together before we resolve them to Ty. At
1143 // the end of the loop, if there is anything to resolve to Ty, it will be in
1144 // this variable.
1145 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001146
Chris Lattnerdf986172009-01-02 07:01:27 +00001147 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1148 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1149 bool ContainsType =
1150 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1151 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152
Chris Lattnerdf986172009-01-02 07:01:27 +00001153#if 0
1154 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1155 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1156 << (ContainsType ? "true" : "false")
1157 << " level=" << UpRefs[i].NestingLevel << "\n";
1158#endif
1159 if (!ContainsType)
1160 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001161
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 // Decrement level of upreference
1163 unsigned Level = --UpRefs[i].NestingLevel;
1164 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001165
Chris Lattnerdf986172009-01-02 07:01:27 +00001166 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1167 if (Level != 0)
1168 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001169
Chris Lattnerdf986172009-01-02 07:01:27 +00001170#if 0
1171 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1172#endif
1173 if (!TypeToResolve)
1174 TypeToResolve = UpRefs[i].UpRefTy;
1175 else
1176 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1177 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1178 --i; // Do not skip the next element.
1179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001180
Chris Lattnerdf986172009-01-02 07:01:27 +00001181 if (TypeToResolve)
1182 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001183
Chris Lattnerdf986172009-01-02 07:01:27 +00001184 return Ty;
1185}
1186
1187
1188/// ParseTypeRec - The recursive function used to process the internal
1189/// implementation details of types.
1190bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1191 switch (Lex.getKind()) {
1192 default:
1193 return TokError("expected type");
1194 case lltok::Type:
1195 // TypeRec ::= 'float' | 'void' (etc)
1196 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001197 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001198 break;
1199 case lltok::kw_opaque:
1200 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001201 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001202 Lex.Lex();
1203 break;
1204 case lltok::lbrace:
1205 // TypeRec ::= '{' ... '}'
1206 if (ParseStructType(Result, false))
1207 return true;
1208 break;
1209 case lltok::lsquare:
1210 // TypeRec ::= '[' ... ']'
1211 Lex.Lex(); // eat the lsquare.
1212 if (ParseArrayVectorType(Result, false))
1213 return true;
1214 break;
1215 case lltok::less: // Either vector or packed struct.
1216 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001217 Lex.Lex();
1218 if (Lex.getKind() == lltok::lbrace) {
1219 if (ParseStructType(Result, true) ||
1220 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001221 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 } else if (ParseArrayVectorType(Result, true))
1223 return true;
1224 break;
1225 case lltok::LocalVar:
1226 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1227 // TypeRec ::= %foo
1228 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1229 Result = T;
1230 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001231 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001232 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1233 std::make_pair(Result,
1234 Lex.getLoc())));
1235 M->addTypeName(Lex.getStrVal(), Result.get());
1236 }
1237 Lex.Lex();
1238 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001239
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 case lltok::LocalVarID:
1241 // TypeRec ::= %4
1242 if (Lex.getUIntVal() < NumberedTypes.size())
1243 Result = NumberedTypes[Lex.getUIntVal()];
1244 else {
1245 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1246 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1247 if (I != ForwardRefTypeIDs.end())
1248 Result = I->second.first;
1249 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001250 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1252 std::make_pair(Result,
1253 Lex.getLoc())));
1254 }
1255 }
1256 Lex.Lex();
1257 break;
1258 case lltok::backslash: {
1259 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001260 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001261 unsigned Val;
1262 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001263 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1265 Result = OT;
1266 break;
1267 }
1268 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001269
1270 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 while (1) {
1272 switch (Lex.getKind()) {
1273 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001274 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001275
1276 // TypeRec ::= TypeRec '*'
1277 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001278 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001280 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001281 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001282 if (!PointerType::isValidElementType(Result.get()))
1283 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001284 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 Lex.Lex();
1286 break;
1287
1288 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1289 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001290 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001292 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001293 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001294 if (!PointerType::isValidElementType(Result.get()))
1295 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 unsigned AddrSpace;
1297 if (ParseOptionalAddrSpace(AddrSpace) ||
1298 ParseToken(lltok::star, "expected '*' in address space"))
1299 return true;
1300
Owen Andersondebcb012009-07-29 22:17:13 +00001301 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 break;
1303 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001304
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1306 case lltok::lparen:
1307 if (ParseFunctionType(Result))
1308 return true;
1309 break;
1310 }
1311 }
1312}
1313
1314/// ParseParameterList
1315/// ::= '(' ')'
1316/// ::= '(' Arg (',' Arg)* ')'
1317/// Arg
1318/// ::= Type OptionalAttributes Value OptionalAttributes
1319bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1320 PerFunctionState &PFS) {
1321 if (ParseToken(lltok::lparen, "expected '(' in call"))
1322 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001323
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 while (Lex.getKind() != lltok::rparen) {
1325 // If this isn't the first argument, we need a comma.
1326 if (!ArgList.empty() &&
1327 ParseToken(lltok::comma, "expected ',' in argument list"))
1328 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 // Parse the argument.
1331 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001332 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001333 unsigned ArgAttrs1, ArgAttrs2;
1334 Value *V;
1335 if (ParseType(ArgTy, ArgLoc) ||
1336 ParseOptionalAttrs(ArgAttrs1, 0) ||
1337 ParseValue(ArgTy, V, PFS) ||
1338 // FIXME: Should not allow attributes after the argument, remove this in
1339 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001340 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001341 return true;
1342 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1343 }
1344
1345 Lex.Lex(); // Lex the ')'.
1346 return false;
1347}
1348
1349
1350
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001351/// ParseArgumentList - Parse the argument list for a function type or function
1352/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001353/// ::= '(' ArgTypeListI ')'
1354/// ArgTypeListI
1355/// ::= /*empty*/
1356/// ::= '...'
1357/// ::= ArgTypeList ',' '...'
1358/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001359///
Chris Lattnerdf986172009-01-02 07:01:27 +00001360bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001361 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 isVarArg = false;
1363 assert(Lex.getKind() == lltok::lparen);
1364 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001365
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 if (Lex.getKind() == lltok::rparen) {
1367 // empty
1368 } else if (Lex.getKind() == lltok::dotdotdot) {
1369 isVarArg = true;
1370 Lex.Lex();
1371 } else {
1372 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001373 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001374 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001375 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001376
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001377 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1378 // types (such as a function returning a pointer to itself). If parsing a
1379 // function prototype, we require fully resolved types.
1380 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001381 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001382
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001383 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001384 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001385
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 if (Lex.getKind() == lltok::LocalVar ||
1387 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1388 Name = Lex.getStrVal();
1389 Lex.Lex();
1390 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001391
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001392 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001393 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001394
Chris Lattnerdf986172009-01-02 07:01:27 +00001395 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001396
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001397 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001398 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001399 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 break;
1402 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
Chris Lattnerdf986172009-01-02 07:01:27 +00001404 // Otherwise must be an argument type.
1405 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001406 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001407 ParseOptionalAttrs(Attrs, 0)) return true;
1408
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001409 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001410 return Error(TypeLoc, "argument can not have void type");
1411
Chris Lattnerdf986172009-01-02 07:01:27 +00001412 if (Lex.getKind() == lltok::LocalVar ||
1413 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1414 Name = Lex.getStrVal();
1415 Lex.Lex();
1416 } else {
1417 Name = "";
1418 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001419
1420 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1421 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001422
Chris Lattnerdf986172009-01-02 07:01:27 +00001423 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1424 }
1425 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001426
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001427 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001428}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001429
Chris Lattnerdf986172009-01-02 07:01:27 +00001430/// ParseFunctionType
1431/// ::= Type ArgumentList OptionalAttrs
1432bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1433 assert(Lex.getKind() == lltok::lparen);
1434
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001435 if (!FunctionType::isValidReturnType(Result))
1436 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001437
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 std::vector<ArgInfo> ArgList;
1439 bool isVarArg;
1440 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001441 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 // FIXME: Allow, but ignore attributes on function types!
1443 // FIXME: Remove in LLVM 3.0
1444 ParseOptionalAttrs(Attrs, 2))
1445 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattnerdf986172009-01-02 07:01:27 +00001447 // Reject names on the arguments lists.
1448 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1449 if (!ArgList[i].Name.empty())
1450 return Error(ArgList[i].Loc, "argument name invalid in function type");
1451 if (!ArgList[i].Attrs != 0) {
1452 // Allow but ignore attributes on function types; this permits
1453 // auto-upgrade.
1454 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1455 }
1456 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 std::vector<const Type*> ArgListTy;
1459 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1460 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Owen Andersondebcb012009-07-29 22:17:13 +00001462 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001463 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001464 return false;
1465}
1466
1467/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1468/// TypeRec
1469/// ::= '{' '}'
1470/// ::= '{' TypeRec (',' TypeRec)* '}'
1471/// ::= '<' '{' '}' '>'
1472/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1473bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1474 assert(Lex.getKind() == lltok::lbrace);
1475 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001477 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001478 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001479 return false;
1480 }
1481
1482 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001483 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 if (ParseTypeRec(Result)) return true;
1485 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001487 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001488 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001489 if (!StructType::isValidElementType(Result))
1490 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001491
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001492 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001493 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001495
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001496 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001497 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001498 if (!StructType::isValidElementType(Result))
1499 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001500
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 ParamsList.push_back(Result);
1502 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001503
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001504 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1505 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnerdf986172009-01-02 07:01:27 +00001507 std::vector<const Type*> ParamsListTy;
1508 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1509 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001510 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001511 return false;
1512}
1513
1514/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1515/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001516/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001517/// ::= '[' APSINTVAL 'x' Types ']'
1518/// ::= '<' APSINTVAL 'x' Types '>'
1519bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1520 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1521 Lex.getAPSIntVal().getBitWidth() > 64)
1522 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 LocTy SizeLoc = Lex.getLoc();
1525 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001527
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001528 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1529 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001530
1531 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001532 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001535 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001536 return Error(TypeLoc, "array and vector element type cannot be void");
1537
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001538 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1539 "expected end of sequential type"))
1540 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001543 if (Size == 0)
1544 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001545 if ((unsigned)Size != Size)
1546 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001547 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001548 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001549 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001550 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001551 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001553 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001554 }
1555 return false;
1556}
1557
1558//===----------------------------------------------------------------------===//
1559// Function Semantic Analysis.
1560//===----------------------------------------------------------------------===//
1561
1562LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1563 : P(p), F(f) {
1564
1565 // Insert unnamed arguments into the NumberedVals list.
1566 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1567 AI != E; ++AI)
1568 if (!AI->hasName())
1569 NumberedVals.push_back(AI);
1570}
1571
1572LLParser::PerFunctionState::~PerFunctionState() {
1573 // If there were any forward referenced non-basicblock values, delete them.
1574 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1575 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1576 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001577 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001578 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001579 delete I->second.first;
1580 I->second.first = 0;
1581 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001582
Chris Lattnerdf986172009-01-02 07:01:27 +00001583 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1584 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1585 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001586 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001587 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001588 delete I->second.first;
1589 I->second.first = 0;
1590 }
1591}
1592
1593bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1594 if (!ForwardRefVals.empty())
1595 return P.Error(ForwardRefVals.begin()->second.second,
1596 "use of undefined value '%" + ForwardRefVals.begin()->first +
1597 "'");
1598 if (!ForwardRefValIDs.empty())
1599 return P.Error(ForwardRefValIDs.begin()->second.second,
1600 "use of undefined value '%" +
1601 utostr(ForwardRefValIDs.begin()->first) + "'");
1602 return false;
1603}
1604
1605
1606/// GetVal - Get a value with the specified name or ID, creating a
1607/// forward reference record if needed. This can return null if the value
1608/// exists but does not have the right type.
1609Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1610 const Type *Ty, LocTy Loc) {
1611 // Look this name up in the normal function symbol table.
1612 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattnerdf986172009-01-02 07:01:27 +00001614 // If this is a forward reference for the value, see if we already created a
1615 // forward ref record.
1616 if (Val == 0) {
1617 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1618 I = ForwardRefVals.find(Name);
1619 if (I != ForwardRefVals.end())
1620 Val = I->second.first;
1621 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattnerdf986172009-01-02 07:01:27 +00001623 // If we have the value in the symbol table or fwd-ref table, return it.
1624 if (Val) {
1625 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001626 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001627 P.Error(Loc, "'%" + Name + "' is not a basic block");
1628 else
1629 P.Error(Loc, "'%" + Name + "' defined with type '" +
1630 Val->getType()->getDescription() + "'");
1631 return 0;
1632 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001635 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1636 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001637 P.Error(Loc, "invalid use of a non-first-class type");
1638 return 0;
1639 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001640
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 // Otherwise, create a new forward reference for this value and remember it.
1642 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001643 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001644 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001645 else
1646 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1649 return FwdVal;
1650}
1651
1652Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1653 LocTy Loc) {
1654 // Look this name up in the normal function symbol table.
1655 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 // If this is a forward reference for the value, see if we already created a
1658 // forward ref record.
1659 if (Val == 0) {
1660 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1661 I = ForwardRefValIDs.find(ID);
1662 if (I != ForwardRefValIDs.end())
1663 Val = I->second.first;
1664 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattnerdf986172009-01-02 07:01:27 +00001666 // If we have the value in the symbol table or fwd-ref table, return it.
1667 if (Val) {
1668 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001669 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1671 else
1672 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1673 Val->getType()->getDescription() + "'");
1674 return 0;
1675 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676
Owen Anderson1d0be152009-08-13 21:58:54 +00001677 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1678 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 P.Error(Loc, "invalid use of a non-first-class type");
1680 return 0;
1681 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682
Chris Lattnerdf986172009-01-02 07:01:27 +00001683 // Otherwise, create a new forward reference for this value and remember it.
1684 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001685 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001686 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001687 else
1688 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001689
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1691 return FwdVal;
1692}
1693
1694/// SetInstName - After an instruction is parsed and inserted into its
1695/// basic block, this installs its name.
1696bool LLParser::PerFunctionState::SetInstName(int NameID,
1697 const std::string &NameStr,
1698 LocTy NameLoc, Instruction *Inst) {
1699 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001700 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 if (NameID != -1 || !NameStr.empty())
1702 return P.Error(NameLoc, "instructions returning void cannot have a name");
1703 return false;
1704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnerdf986172009-01-02 07:01:27 +00001706 // If this was a numbered instruction, verify that the instruction is the
1707 // expected value and resolve any forward references.
1708 if (NameStr.empty()) {
1709 // If neither a name nor an ID was specified, just use the next ID.
1710 if (NameID == -1)
1711 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 if (unsigned(NameID) != NumberedVals.size())
1714 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1715 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001716
Chris Lattnerdf986172009-01-02 07:01:27 +00001717 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1718 ForwardRefValIDs.find(NameID);
1719 if (FI != ForwardRefValIDs.end()) {
1720 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001721 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 FI->second.first->getType()->getDescription() + "'");
1723 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001724 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001725 ForwardRefValIDs.erase(FI);
1726 }
1727
1728 NumberedVals.push_back(Inst);
1729 return false;
1730 }
1731
1732 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1733 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1734 FI = ForwardRefVals.find(NameStr);
1735 if (FI != ForwardRefVals.end()) {
1736 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001737 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 FI->second.first->getType()->getDescription() + "'");
1739 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001740 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 ForwardRefVals.erase(FI);
1742 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001743
Chris Lattnerdf986172009-01-02 07:01:27 +00001744 // Set the name on the instruction.
1745 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001746
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001748 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001749 NameStr + "'");
1750 return false;
1751}
1752
1753/// GetBB - Get a basic block with the specified name or ID, creating a
1754/// forward reference record if needed.
1755BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1756 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001757 return cast_or_null<BasicBlock>(GetVal(Name,
1758 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001759}
1760
1761BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001762 return cast_or_null<BasicBlock>(GetVal(ID,
1763 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001764}
1765
1766/// DefineBB - Define the specified basic block, which is either named or
1767/// unnamed. If there is an error, this returns null otherwise it returns
1768/// the block being defined.
1769BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1770 LocTy Loc) {
1771 BasicBlock *BB;
1772 if (Name.empty())
1773 BB = GetBB(NumberedVals.size(), Loc);
1774 else
1775 BB = GetBB(Name, Loc);
1776 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001777
Chris Lattnerdf986172009-01-02 07:01:27 +00001778 // Move the block to the end of the function. Forward ref'd blocks are
1779 // inserted wherever they happen to be referenced.
1780 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001781
Chris Lattnerdf986172009-01-02 07:01:27 +00001782 // Remove the block from forward ref sets.
1783 if (Name.empty()) {
1784 ForwardRefValIDs.erase(NumberedVals.size());
1785 NumberedVals.push_back(BB);
1786 } else {
1787 // BB forward references are already in the function symbol table.
1788 ForwardRefVals.erase(Name);
1789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001790
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 return BB;
1792}
1793
1794//===----------------------------------------------------------------------===//
1795// Constants.
1796//===----------------------------------------------------------------------===//
1797
1798/// ParseValID - Parse an abstract value that doesn't necessarily have a
1799/// type implied. For example, if we parse "4" we don't know what integer type
1800/// it has. The value will later be combined with its type and checked for
1801/// sanity.
1802bool LLParser::ParseValID(ValID &ID) {
1803 ID.Loc = Lex.getLoc();
1804 switch (Lex.getKind()) {
1805 default: return TokError("expected value token");
1806 case lltok::GlobalID: // @42
1807 ID.UIntVal = Lex.getUIntVal();
1808 ID.Kind = ValID::t_GlobalID;
1809 break;
1810 case lltok::GlobalVar: // @foo
1811 ID.StrVal = Lex.getStrVal();
1812 ID.Kind = ValID::t_GlobalName;
1813 break;
1814 case lltok::LocalVarID: // %42
1815 ID.UIntVal = Lex.getUIntVal();
1816 ID.Kind = ValID::t_LocalID;
1817 break;
1818 case lltok::LocalVar: // %foo
1819 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1820 ID.StrVal = Lex.getStrVal();
1821 ID.Kind = ValID::t_LocalName;
1822 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001823 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001824 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001825 Lex.Lex();
1826 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001827 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001828 if (ParseMDNodeVector(Elts) ||
1829 ParseToken(lltok::rbrace, "expected end of metadata node"))
1830 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001831
Owen Anderson647e3012009-07-31 21:35:40 +00001832 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001833 return false;
1834 }
1835
Devang Patel923078c2009-07-01 19:21:12 +00001836 // Standalone metadata reference
1837 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001838 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001839 return false;
Devang Patel256be962009-07-20 19:00:08 +00001840
Nick Lewycky21cc4462009-04-04 07:22:01 +00001841 // MDString:
1842 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001843 if (ParseMDString(ID.MetadataVal)) return true;
1844 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001845 return false;
1846 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001849 ID.Kind = ValID::t_APSInt;
1850 break;
1851 case lltok::APFloat:
1852 ID.APFloatVal = Lex.getAPFloatVal();
1853 ID.Kind = ValID::t_APFloat;
1854 break;
1855 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001856 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 ID.Kind = ValID::t_Constant;
1858 break;
1859 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001860 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 ID.Kind = ValID::t_Constant;
1862 break;
1863 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1864 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1865 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 case lltok::lbrace: {
1868 // ValID ::= '{' ConstVector '}'
1869 Lex.Lex();
1870 SmallVector<Constant*, 16> Elts;
1871 if (ParseGlobalValueVector(Elts) ||
1872 ParseToken(lltok::rbrace, "expected end of struct constant"))
1873 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001875 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1876 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 ID.Kind = ValID::t_Constant;
1878 return false;
1879 }
1880 case lltok::less: {
1881 // ValID ::= '<' ConstVector '>' --> Vector.
1882 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1883 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001884 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001885
Chris Lattnerdf986172009-01-02 07:01:27 +00001886 SmallVector<Constant*, 16> Elts;
1887 LocTy FirstEltLoc = Lex.getLoc();
1888 if (ParseGlobalValueVector(Elts) ||
1889 (isPackedStruct &&
1890 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1891 ParseToken(lltok::greater, "expected end of constant"))
1892 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001893
Chris Lattnerdf986172009-01-02 07:01:27 +00001894 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001895 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001896 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 ID.Kind = ValID::t_Constant;
1898 return false;
1899 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 if (Elts.empty())
1902 return Error(ID.Loc, "constant vector must not be empty");
1903
1904 if (!Elts[0]->getType()->isInteger() &&
1905 !Elts[0]->getType()->isFloatingPoint())
1906 return Error(FirstEltLoc,
1907 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 // Verify that all the vector elements have the same type.
1910 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1911 if (Elts[i]->getType() != Elts[0]->getType())
1912 return Error(FirstEltLoc,
1913 "vector element #" + utostr(i) +
1914 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Owen Andersonaf7ec972009-07-28 21:19:26 +00001916 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 ID.Kind = ValID::t_Constant;
1918 return false;
1919 }
1920 case lltok::lsquare: { // Array Constant
1921 Lex.Lex();
1922 SmallVector<Constant*, 16> Elts;
1923 LocTy FirstEltLoc = Lex.getLoc();
1924 if (ParseGlobalValueVector(Elts) ||
1925 ParseToken(lltok::rsquare, "expected end of array constant"))
1926 return true;
1927
1928 // Handle empty element.
1929 if (Elts.empty()) {
1930 // Use undef instead of an array because it's inconvenient to determine
1931 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001932 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 return false;
1934 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001935
Chris Lattnerdf986172009-01-02 07:01:27 +00001936 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Owen Andersondebcb012009-07-29 22:17:13 +00001940 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001941
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001943 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001944 if (Elts[i]->getType() != Elts[0]->getType())
1945 return Error(FirstEltLoc,
1946 "array element #" + utostr(i) +
1947 " is not of type '" +Elts[0]->getType()->getDescription());
1948 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001949
Owen Anderson1fd70962009-07-28 18:32:17 +00001950 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 ID.Kind = ValID::t_Constant;
1952 return false;
1953 }
1954 case lltok::kw_c: // c "foo"
1955 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001956 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001957 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1958 ID.Kind = ValID::t_Constant;
1959 return false;
1960
1961 case lltok::kw_asm: {
Dale Johannesen43602982009-10-13 20:46:56 +00001962 // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT
1963 bool HasSideEffect, MsAsm;
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 Lex.Lex();
1965 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen43602982009-10-13 20:46:56 +00001966 ParseOptionalToken(lltok::kw_msasm, MsAsm) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001967 ParseStringConstant(ID.StrVal) ||
1968 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 ParseToken(lltok::StringConstant, "expected constraint string"))
1970 return true;
1971 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen43602982009-10-13 20:46:56 +00001972 ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 ID.Kind = ValID::t_InlineAsm;
1974 return false;
1975 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001976
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 case lltok::kw_trunc:
1978 case lltok::kw_zext:
1979 case lltok::kw_sext:
1980 case lltok::kw_fptrunc:
1981 case lltok::kw_fpext:
1982 case lltok::kw_bitcast:
1983 case lltok::kw_uitofp:
1984 case lltok::kw_sitofp:
1985 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001986 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00001987 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00001990 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001991 Constant *SrcVal;
1992 Lex.Lex();
1993 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1994 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00001995 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001996 ParseType(DestTy) ||
1997 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1998 return true;
1999 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2000 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2001 SrcVal->getType()->getDescription() + "' to '" +
2002 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002003 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002004 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002005 ID.Kind = ValID::t_Constant;
2006 return false;
2007 }
2008 case lltok::kw_extractvalue: {
2009 Lex.Lex();
2010 Constant *Val;
2011 SmallVector<unsigned, 4> Indices;
2012 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2013 ParseGlobalTypeAndValue(Val) ||
2014 ParseIndexList(Indices) ||
2015 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2016 return true;
2017 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2018 return Error(ID.Loc, "extractvalue operand must be array or struct");
2019 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2020 Indices.end()))
2021 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002022 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002023 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 ID.Kind = ValID::t_Constant;
2025 return false;
2026 }
2027 case lltok::kw_insertvalue: {
2028 Lex.Lex();
2029 Constant *Val0, *Val1;
2030 SmallVector<unsigned, 4> Indices;
2031 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2032 ParseGlobalTypeAndValue(Val0) ||
2033 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2034 ParseGlobalTypeAndValue(Val1) ||
2035 ParseIndexList(Indices) ||
2036 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2037 return true;
2038 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2039 return Error(ID.Loc, "extractvalue operand must be array or struct");
2040 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2041 Indices.end()))
2042 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002043 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002044 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002045 ID.Kind = ValID::t_Constant;
2046 return false;
2047 }
2048 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002049 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002050 unsigned PredVal, Opc = Lex.getUIntVal();
2051 Constant *Val0, *Val1;
2052 Lex.Lex();
2053 if (ParseCmpPredicate(PredVal, Opc) ||
2054 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2055 ParseGlobalTypeAndValue(Val0) ||
2056 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2057 ParseGlobalTypeAndValue(Val1) ||
2058 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2059 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002060
Chris Lattnerdf986172009-01-02 07:01:27 +00002061 if (Val0->getType() != Val1->getType())
2062 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 if (Opc == Instruction::FCmp) {
2067 if (!Val0->getType()->isFPOrFPVector())
2068 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002069 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002070 } else {
2071 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 if (!Val0->getType()->isIntOrIntVector() &&
2073 !isa<PointerType>(Val0->getType()))
2074 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002075 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002076 }
2077 ID.Kind = ValID::t_Constant;
2078 return false;
2079 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 // Binary Operators.
2082 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002083 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002085 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002087 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 case lltok::kw_udiv:
2089 case lltok::kw_sdiv:
2090 case lltok::kw_fdiv:
2091 case lltok::kw_urem:
2092 case lltok::kw_srem:
2093 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002094 bool NUW = false;
2095 bool NSW = false;
2096 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 unsigned Opc = Lex.getUIntVal();
2098 Constant *Val0, *Val1;
2099 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002100 LocTy ModifierLoc = Lex.getLoc();
2101 if (Opc == Instruction::Add ||
2102 Opc == Instruction::Sub ||
2103 Opc == Instruction::Mul) {
2104 if (EatIfPresent(lltok::kw_nuw))
2105 NUW = true;
2106 if (EatIfPresent(lltok::kw_nsw)) {
2107 NSW = true;
2108 if (EatIfPresent(lltok::kw_nuw))
2109 NUW = true;
2110 }
2111 } else if (Opc == Instruction::SDiv) {
2112 if (EatIfPresent(lltok::kw_exact))
2113 Exact = true;
2114 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002115 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2116 ParseGlobalTypeAndValue(Val0) ||
2117 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2118 ParseGlobalTypeAndValue(Val1) ||
2119 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2120 return true;
2121 if (Val0->getType() != Val1->getType())
2122 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002123 if (!Val0->getType()->isIntOrIntVector()) {
2124 if (NUW)
2125 return Error(ModifierLoc, "nuw only applies to integer operations");
2126 if (NSW)
2127 return Error(ModifierLoc, "nsw only applies to integer operations");
2128 }
2129 // API compatibility: Accept either integer or floating-point types with
2130 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002131 if (!Val0->getType()->isIntOrIntVector() &&
2132 !Val0->getType()->isFPOrFPVector())
2133 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002134 unsigned Flags = 0;
2135 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2136 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2137 if (Exact) Flags |= SDivOperator::IsExact;
2138 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002139 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 ID.Kind = ValID::t_Constant;
2141 return false;
2142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 // Logical Operations
2145 case lltok::kw_shl:
2146 case lltok::kw_lshr:
2147 case lltok::kw_ashr:
2148 case lltok::kw_and:
2149 case lltok::kw_or:
2150 case lltok::kw_xor: {
2151 unsigned Opc = Lex.getUIntVal();
2152 Constant *Val0, *Val1;
2153 Lex.Lex();
2154 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2155 ParseGlobalTypeAndValue(Val0) ||
2156 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2157 ParseGlobalTypeAndValue(Val1) ||
2158 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2159 return true;
2160 if (Val0->getType() != Val1->getType())
2161 return Error(ID.Loc, "operands of constexpr must have same type");
2162 if (!Val0->getType()->isIntOrIntVector())
2163 return Error(ID.Loc,
2164 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002165 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 ID.Kind = ValID::t_Constant;
2167 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002168 }
2169
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 case lltok::kw_getelementptr:
2171 case lltok::kw_shufflevector:
2172 case lltok::kw_insertelement:
2173 case lltok::kw_extractelement:
2174 case lltok::kw_select: {
2175 unsigned Opc = Lex.getUIntVal();
2176 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002177 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002179 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002180 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2182 ParseGlobalValueVector(Elts) ||
2183 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2184 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002185
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 if (Opc == Instruction::GetElementPtr) {
2187 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2188 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002189
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002191 (Value**)(Elts.data() + 1),
2192 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002193 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002194 ID.ConstantVal = InBounds ?
2195 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2196 Elts.data() + 1,
2197 Elts.size() - 1) :
2198 ConstantExpr::getGetElementPtr(Elts[0],
2199 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 } else if (Opc == Instruction::Select) {
2201 if (Elts.size() != 3)
2202 return Error(ID.Loc, "expected three operands to select");
2203 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2204 Elts[2]))
2205 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002206 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002207 } else if (Opc == Instruction::ShuffleVector) {
2208 if (Elts.size() != 3)
2209 return Error(ID.Loc, "expected three operands to shufflevector");
2210 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2211 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002212 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002213 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002214 } else if (Opc == Instruction::ExtractElement) {
2215 if (Elts.size() != 2)
2216 return Error(ID.Loc, "expected two operands to extractelement");
2217 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2218 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002219 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 } else {
2221 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2222 if (Elts.size() != 3)
2223 return Error(ID.Loc, "expected three operands to insertelement");
2224 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2225 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002226 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002227 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002229
Chris Lattnerdf986172009-01-02 07:01:27 +00002230 ID.Kind = ValID::t_Constant;
2231 return false;
2232 }
2233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002234
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 Lex.Lex();
2236 return false;
2237}
2238
2239/// ParseGlobalValue - Parse a global value with the specified type.
2240bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2241 V = 0;
2242 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002243 return ParseValID(ID) ||
2244 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002245}
2246
2247/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2248/// constant.
2249bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2250 Constant *&V) {
2251 if (isa<FunctionType>(Ty))
2252 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002253
Chris Lattnerdf986172009-01-02 07:01:27 +00002254 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002255 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002256 case ValID::t_Metadata:
2257 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002258 case ValID::t_LocalID:
2259 case ValID::t_LocalName:
2260 return Error(ID.Loc, "invalid use of function-local name");
2261 case ValID::t_InlineAsm:
2262 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2263 case ValID::t_GlobalName:
2264 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2265 return V == 0;
2266 case ValID::t_GlobalID:
2267 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2268 return V == 0;
2269 case ValID::t_APSInt:
2270 if (!isa<IntegerType>(Ty))
2271 return Error(ID.Loc, "integer constant must have integer type");
2272 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002273 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 return false;
2275 case ValID::t_APFloat:
2276 if (!Ty->isFloatingPoint() ||
2277 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2278 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002279
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 // The lexer has no type info, so builds all float and double FP constants
2281 // as double. Fix this here. Long double does not need this.
2282 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002283 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 bool Ignored;
2285 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2286 &Ignored);
2287 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002288 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002289
Chris Lattner959873d2009-01-05 18:24:23 +00002290 if (V->getType() != Ty)
2291 return Error(ID.Loc, "floating point constant does not have type '" +
2292 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002293
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 return false;
2295 case ValID::t_Null:
2296 if (!isa<PointerType>(Ty))
2297 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002298 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 return false;
2300 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002301 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002302 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002303 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002304 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002305 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002307 case ValID::t_EmptyArray:
2308 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2309 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002310 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002311 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002312 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002313 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002314 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002315 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002316 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002317 return false;
2318 case ValID::t_Constant:
2319 if (ID.ConstantVal->getType() != Ty)
2320 return Error(ID.Loc, "constant expression type mismatch");
2321 V = ID.ConstantVal;
2322 return false;
2323 }
2324}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002325
Chris Lattnerdf986172009-01-02 07:01:27 +00002326bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002327 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 return ParseType(Type) ||
2329 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002330}
Chris Lattnerdf986172009-01-02 07:01:27 +00002331
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002332/// ParseGlobalValueVector
2333/// ::= /*empty*/
2334/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002335bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2336 // Empty list.
2337 if (Lex.getKind() == lltok::rbrace ||
2338 Lex.getKind() == lltok::rsquare ||
2339 Lex.getKind() == lltok::greater ||
2340 Lex.getKind() == lltok::rparen)
2341 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002342
Chris Lattnerdf986172009-01-02 07:01:27 +00002343 Constant *C;
2344 if (ParseGlobalTypeAndValue(C)) return true;
2345 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002346
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002347 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002348 if (ParseGlobalTypeAndValue(C)) return true;
2349 Elts.push_back(C);
2350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002351
Chris Lattnerdf986172009-01-02 07:01:27 +00002352 return false;
2353}
2354
2355
2356//===----------------------------------------------------------------------===//
2357// Function Parsing.
2358//===----------------------------------------------------------------------===//
2359
2360bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2361 PerFunctionState &PFS) {
2362 if (ID.Kind == ValID::t_LocalID)
2363 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2364 else if (ID.Kind == ValID::t_LocalName)
2365 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002366 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002367 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2368 const FunctionType *FTy =
2369 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2370 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2371 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002372 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002373 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002374 } else if (ID.Kind == ValID::t_Metadata) {
2375 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 } else {
2377 Constant *C;
2378 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2379 V = C;
2380 return false;
2381 }
2382
2383 return V == 0;
2384}
2385
2386bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2387 V = 0;
2388 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002389 return ParseValID(ID) ||
2390 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002391}
2392
2393bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002394 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002395 return ParseType(T) ||
2396 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002397}
2398
2399/// FunctionHeader
2400/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2401/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2402/// OptionalAlign OptGC
2403bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2404 // Parse the linkage.
2405 LocTy LinkageLoc = Lex.getLoc();
2406 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002407
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002408 unsigned Visibility, RetAttrs;
2409 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002410 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 LocTy RetTypeLoc = Lex.getLoc();
2412 if (ParseOptionalLinkage(Linkage) ||
2413 ParseOptionalVisibility(Visibility) ||
2414 ParseOptionalCallingConv(CC) ||
2415 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002416 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002417 return true;
2418
2419 // Verify that the linkage is ok.
2420 switch ((GlobalValue::LinkageTypes)Linkage) {
2421 case GlobalValue::ExternalLinkage:
2422 break; // always ok.
2423 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002424 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002425 if (isDefine)
2426 return Error(LinkageLoc, "invalid linkage for function definition");
2427 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002428 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002429 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002431 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002432 case GlobalValue::LinkOnceAnyLinkage:
2433 case GlobalValue::LinkOnceODRLinkage:
2434 case GlobalValue::WeakAnyLinkage:
2435 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 case GlobalValue::DLLExportLinkage:
2437 if (!isDefine)
2438 return Error(LinkageLoc, "invalid linkage for function declaration");
2439 break;
2440 case GlobalValue::AppendingLinkage:
2441 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002442 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002443 return Error(LinkageLoc, "invalid function linkage type");
2444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattner99bb3152009-01-05 08:00:30 +00002446 if (!FunctionType::isValidReturnType(RetType) ||
2447 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002448 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002451
2452 std::string FunctionName;
2453 if (Lex.getKind() == lltok::GlobalVar) {
2454 FunctionName = Lex.getStrVal();
2455 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2456 unsigned NameID = Lex.getUIntVal();
2457
2458 if (NameID != NumberedVals.size())
2459 return TokError("function expected to be numbered '%" +
2460 utostr(NumberedVals.size()) + "'");
2461 } else {
2462 return TokError("expected function name");
2463 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002464
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002465 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002466
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002467 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002469
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 std::vector<ArgInfo> ArgList;
2471 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002474 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002475 std::string GC;
2476
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002477 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002478 ParseOptionalAttrs(FuncAttrs, 2) ||
2479 (EatIfPresent(lltok::kw_section) &&
2480 ParseStringConstant(Section)) ||
2481 ParseOptionalAlignment(Alignment) ||
2482 (EatIfPresent(lltok::kw_gc) &&
2483 ParseStringConstant(GC)))
2484 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002485
2486 // If the alignment was parsed as an attribute, move to the alignment field.
2487 if (FuncAttrs & Attribute::Alignment) {
2488 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2489 FuncAttrs &= ~Attribute::Alignment;
2490 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002491
Chris Lattnerdf986172009-01-02 07:01:27 +00002492 // Okay, if we got here, the function is syntactically valid. Convert types
2493 // and do semantic checks.
2494 std::vector<const Type*> ParamTypeList;
2495 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002496 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002497 // attributes.
2498 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2499 if (FuncAttrs & ObsoleteFuncAttrs) {
2500 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2501 FuncAttrs &= ~ObsoleteFuncAttrs;
2502 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002503
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 if (RetAttrs != Attribute::None)
2505 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506
Chris Lattnerdf986172009-01-02 07:01:27 +00002507 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2508 ParamTypeList.push_back(ArgList[i].Type);
2509 if (ArgList[i].Attrs != Attribute::None)
2510 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2511 }
2512
2513 if (FuncAttrs != Attribute::None)
2514 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2515
2516 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002517
Chris Lattnera9a9e072009-03-09 04:49:14 +00002518 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002519 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002520 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2521
Owen Andersonfba933c2009-07-01 23:57:11 +00002522 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002523 FunctionType::get(RetType, ParamTypeList, isVarArg);
2524 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002525
2526 Fn = 0;
2527 if (!FunctionName.empty()) {
2528 // If this was a definition of a forward reference, remove the definition
2529 // from the forward reference table and fill in the forward ref.
2530 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2531 ForwardRefVals.find(FunctionName);
2532 if (FRVI != ForwardRefVals.end()) {
2533 Fn = M->getFunction(FunctionName);
2534 ForwardRefVals.erase(FRVI);
2535 } else if ((Fn = M->getFunction(FunctionName))) {
2536 // If this function already exists in the symbol table, then it is
2537 // multiply defined. We accept a few cases for old backwards compat.
2538 // FIXME: Remove this stuff for LLVM 3.0.
2539 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2540 (!Fn->isDeclaration() && isDefine)) {
2541 // If the redefinition has different type or different attributes,
2542 // reject it. If both have bodies, reject it.
2543 return Error(NameLoc, "invalid redefinition of function '" +
2544 FunctionName + "'");
2545 } else if (Fn->isDeclaration()) {
2546 // Make sure to strip off any argument names so we can't get conflicts.
2547 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2548 AI != AE; ++AI)
2549 AI->setName("");
2550 }
2551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002552
Dan Gohman41905542009-08-29 23:37:49 +00002553 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 // If this is a definition of a forward referenced function, make sure the
2555 // types agree.
2556 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2557 = ForwardRefValIDs.find(NumberedVals.size());
2558 if (I != ForwardRefValIDs.end()) {
2559 Fn = cast<Function>(I->second.first);
2560 if (Fn->getType() != PFT)
2561 return Error(NameLoc, "type of definition and forward reference of '@" +
2562 utostr(NumberedVals.size()) +"' disagree");
2563 ForwardRefValIDs.erase(I);
2564 }
2565 }
2566
2567 if (Fn == 0)
2568 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2569 else // Move the forward-reference to the correct spot in the module.
2570 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2571
2572 if (FunctionName.empty())
2573 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002574
Chris Lattnerdf986172009-01-02 07:01:27 +00002575 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2576 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2577 Fn->setCallingConv(CC);
2578 Fn->setAttributes(PAL);
2579 Fn->setAlignment(Alignment);
2580 Fn->setSection(Section);
2581 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Chris Lattnerdf986172009-01-02 07:01:27 +00002583 // Add all of the arguments we parsed to the function.
2584 Function::arg_iterator ArgIt = Fn->arg_begin();
2585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2586 // If the argument has a name, insert it into the argument symbol table.
2587 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002588
Chris Lattnerdf986172009-01-02 07:01:27 +00002589 // Set the name, if it conflicted, it will be auto-renamed.
2590 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002591
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 if (ArgIt->getNameStr() != ArgList[i].Name)
2593 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2594 ArgList[i].Name + "'");
2595 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 return false;
2598}
2599
2600
2601/// ParseFunctionBody
2602/// ::= '{' BasicBlock+ '}'
2603/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2604///
2605bool LLParser::ParseFunctionBody(Function &Fn) {
2606 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2607 return TokError("expected '{' in function body");
2608 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002609
Chris Lattnerdf986172009-01-02 07:01:27 +00002610 PerFunctionState PFS(*this, Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2613 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002614
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 // Eat the }.
2616 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002617
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 // Verify function is ok.
2619 return PFS.VerifyFunctionComplete();
2620}
2621
2622/// ParseBasicBlock
2623/// ::= LabelStr? Instruction*
2624bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2625 // If this basic block starts out with a name, remember it.
2626 std::string Name;
2627 LocTy NameLoc = Lex.getLoc();
2628 if (Lex.getKind() == lltok::LabelStr) {
2629 Name = Lex.getStrVal();
2630 Lex.Lex();
2631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2634 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635
Chris Lattnerdf986172009-01-02 07:01:27 +00002636 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Chris Lattnerdf986172009-01-02 07:01:27 +00002638 // Parse the instructions in this block until we get a terminator.
2639 Instruction *Inst;
2640 do {
2641 // This instruction may have three possibilities for a name: a) none
2642 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2643 LocTy NameLoc = Lex.getLoc();
2644 int NameID = -1;
2645 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Chris Lattnerdf986172009-01-02 07:01:27 +00002647 if (Lex.getKind() == lltok::LocalVarID) {
2648 NameID = Lex.getUIntVal();
2649 Lex.Lex();
2650 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2651 return true;
2652 } else if (Lex.getKind() == lltok::LocalVar ||
2653 // FIXME: REMOVE IN LLVM 3.0
2654 Lex.getKind() == lltok::StringConstant) {
2655 NameStr = Lex.getStrVal();
2656 Lex.Lex();
2657 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2658 return true;
2659 }
Devang Patelf633a062009-09-17 23:04:48 +00002660
Chris Lattnerdf986172009-01-02 07:01:27 +00002661 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002662 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002663 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002664
2665 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002666 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002667 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002669 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002670 MDsOnInst.clear();
2671
Chris Lattnerdf986172009-01-02 07:01:27 +00002672 BB->getInstList().push_back(Inst);
2673
2674 // Set the name on the instruction.
2675 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2676 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002677
Chris Lattnerdf986172009-01-02 07:01:27 +00002678 return false;
2679}
2680
2681//===----------------------------------------------------------------------===//
2682// Instruction Parsing.
2683//===----------------------------------------------------------------------===//
2684
2685/// ParseInstruction - Parse one of the many different instructions.
2686///
2687bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2688 PerFunctionState &PFS) {
2689 lltok::Kind Token = Lex.getKind();
2690 if (Token == lltok::Eof)
2691 return TokError("found end of file when expecting more instructions");
2692 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002693 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002695
Chris Lattnerdf986172009-01-02 07:01:27 +00002696 switch (Token) {
2697 default: return Error(Loc, "expected instruction opcode");
2698 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002699 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2700 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2702 case lltok::kw_br: return ParseBr(Inst, PFS);
2703 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2704 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2705 // Binary Operators.
2706 case lltok::kw_add:
2707 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002708 case lltok::kw_mul: {
2709 bool NUW = false;
2710 bool NSW = false;
2711 LocTy ModifierLoc = Lex.getLoc();
2712 if (EatIfPresent(lltok::kw_nuw))
2713 NUW = true;
2714 if (EatIfPresent(lltok::kw_nsw)) {
2715 NSW = true;
2716 if (EatIfPresent(lltok::kw_nuw))
2717 NUW = true;
2718 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002719 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002720 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2721 if (!Result) {
2722 if (!Inst->getType()->isIntOrIntVector()) {
2723 if (NUW)
2724 return Error(ModifierLoc, "nuw only applies to integer operations");
2725 if (NSW)
2726 return Error(ModifierLoc, "nsw only applies to integer operations");
2727 }
2728 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002729 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002730 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002731 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002732 }
2733 return Result;
2734 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002735 case lltok::kw_fadd:
2736 case lltok::kw_fsub:
2737 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2738
Dan Gohman59858cf2009-07-27 16:11:46 +00002739 case lltok::kw_sdiv: {
2740 bool Exact = false;
2741 if (EatIfPresent(lltok::kw_exact))
2742 Exact = true;
2743 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2744 if (!Result)
2745 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002746 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002747 return Result;
2748 }
2749
Chris Lattnerdf986172009-01-02 07:01:27 +00002750 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002752 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002753 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002754 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002755 case lltok::kw_shl:
2756 case lltok::kw_lshr:
2757 case lltok::kw_ashr:
2758 case lltok::kw_and:
2759 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002760 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002762 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 // Casts.
2764 case lltok::kw_trunc:
2765 case lltok::kw_zext:
2766 case lltok::kw_sext:
2767 case lltok::kw_fptrunc:
2768 case lltok::kw_fpext:
2769 case lltok::kw_bitcast:
2770 case lltok::kw_uitofp:
2771 case lltok::kw_sitofp:
2772 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002773 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002775 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 // Other.
2777 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002778 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002779 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2780 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2781 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2782 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2783 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2784 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2785 // Memory.
Victor Hernandez3e0c99a2009-09-25 18:11:52 +00002786 case lltok::kw_alloca:
2787 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002788 case lltok::kw_free: return ParseFree(Inst, PFS);
2789 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2790 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2791 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002792 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002794 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002795 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002796 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002797 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2799 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2800 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2801 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2802 }
2803}
2804
2805/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2806bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002807 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 switch (Lex.getKind()) {
2809 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2810 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2811 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2812 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2813 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2814 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2815 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2816 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2817 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2818 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2819 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2820 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2821 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2822 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2823 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2824 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2825 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2826 }
2827 } else {
2828 switch (Lex.getKind()) {
2829 default: TokError("expected icmp predicate (e.g. 'eq')");
2830 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2831 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2832 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2833 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2834 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2835 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2836 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2837 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2838 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2839 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2840 }
2841 }
2842 Lex.Lex();
2843 return false;
2844}
2845
2846//===----------------------------------------------------------------------===//
2847// Terminator Instructions.
2848//===----------------------------------------------------------------------===//
2849
2850/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002851/// ::= 'ret' void (',' !dbg, !1)
2852/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2853/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002854/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002855bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2856 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002857 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002858 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002860 if (Ty->isVoidTy()) {
Devang Patelf633a062009-09-17 23:04:48 +00002861 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002862 if (ParseOptionalCustomMetadata()) return true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002863 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002864 return false;
2865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002866
Chris Lattnerdf986172009-01-02 07:01:27 +00002867 Value *RV;
2868 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002869
Devang Patelf633a062009-09-17 23:04:48 +00002870 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002871 // Parse optional custom metadata, e.g. !dbg
2872 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2873 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002874 } else {
2875 // The normal case is one return value.
2876 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2877 // of 'ret {i32,i32} {i32 1, i32 2}'
2878 SmallVector<Value*, 8> RVs;
2879 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002880
Devang Patelf633a062009-09-17 23:04:48 +00002881 do {
Devang Patel0475c912009-09-29 00:01:14 +00002882 // If optional custom metadata, e.g. !dbg is seen then this is the
2883 // end of MRV.
2884 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002885 break;
2886 if (ParseTypeAndValue(RV, PFS)) return true;
2887 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00002888 } while (EatIfPresent(lltok::comma));
2889
2890 RV = UndefValue::get(PFS.getFunction().getReturnType());
2891 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002892 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2893 BB->getInstList().push_back(I);
2894 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00002895 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002896 }
2897 }
Devang Patelf633a062009-09-17 23:04:48 +00002898 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002899 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002900
Owen Anderson1d0be152009-08-13 21:58:54 +00002901 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002902 return false;
2903}
2904
2905
2906/// ParseBr
2907/// ::= 'br' TypeAndValue
2908/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2909bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2910 LocTy Loc, Loc2;
2911 Value *Op0, *Op1, *Op2;
2912 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002913
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2915 Inst = BranchInst::Create(BB);
2916 return false;
2917 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002918
Owen Anderson1d0be152009-08-13 21:58:54 +00002919 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002920 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002921
Chris Lattnerdf986172009-01-02 07:01:27 +00002922 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2923 ParseTypeAndValue(Op1, Loc, PFS) ||
2924 ParseToken(lltok::comma, "expected ',' after true destination") ||
2925 ParseTypeAndValue(Op2, Loc2, PFS))
2926 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 if (!isa<BasicBlock>(Op1))
2929 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 if (!isa<BasicBlock>(Op2))
2931 return Error(Loc2, "true destination of branch must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattnerdf986172009-01-02 07:01:27 +00002933 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2934 return false;
2935}
2936
2937/// ParseSwitch
2938/// Instruction
2939/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2940/// JumpTable
2941/// ::= (TypeAndValue ',' TypeAndValue)*
2942bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2943 LocTy CondLoc, BBLoc;
2944 Value *Cond, *DefaultBB;
2945 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2946 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2947 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2948 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2949 return true;
2950
2951 if (!isa<IntegerType>(Cond->getType()))
2952 return Error(CondLoc, "switch condition must have integer type");
2953 if (!isa<BasicBlock>(DefaultBB))
2954 return Error(BBLoc, "default destination must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 // Parse the jump table pairs.
2957 SmallPtrSet<Value*, 32> SeenCases;
2958 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2959 while (Lex.getKind() != lltok::rsquare) {
2960 Value *Constant, *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002961
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2963 ParseToken(lltok::comma, "expected ',' after case value") ||
2964 ParseTypeAndValue(DestBB, BBLoc, PFS))
2965 return true;
2966
2967 if (!SeenCases.insert(Constant))
2968 return Error(CondLoc, "duplicate case value in switch");
2969 if (!isa<ConstantInt>(Constant))
2970 return Error(CondLoc, "case value is not a constant integer");
2971 if (!isa<BasicBlock>(DestBB))
2972 return Error(BBLoc, "case destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002973
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2975 cast<BasicBlock>(DestBB)));
2976 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002979
Chris Lattnerdf986172009-01-02 07:01:27 +00002980 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2981 Table.size());
2982 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2983 SI->addCase(Table[i].first, Table[i].second);
2984 Inst = SI;
2985 return false;
2986}
2987
2988/// ParseInvoke
2989/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2990/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2991bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2992 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002993 unsigned RetAttrs, FnAttrs;
2994 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002995 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 LocTy RetTypeLoc;
2997 ValID CalleeID;
2998 SmallVector<ParamInfo, 16> ArgList;
2999
3000 Value *NormalBB, *UnwindBB;
3001 if (ParseOptionalCallingConv(CC) ||
3002 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003003 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 ParseValID(CalleeID) ||
3005 ParseParameterList(ArgList, PFS) ||
3006 ParseOptionalAttrs(FnAttrs, 2) ||
3007 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3008 ParseTypeAndValue(NormalBB, PFS) ||
3009 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3010 ParseTypeAndValue(UnwindBB, PFS))
3011 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003012
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 if (!isa<BasicBlock>(NormalBB))
3014 return Error(CallLoc, "normal destination is not a basic block");
3015 if (!isa<BasicBlock>(UnwindBB))
3016 return Error(CallLoc, "unwind destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003017
Chris Lattnerdf986172009-01-02 07:01:27 +00003018 // If RetType is a non-function pointer type, then this is the short syntax
3019 // for the call, which means that RetType is just the return type. Infer the
3020 // rest of the function argument types from the arguments that are present.
3021 const PointerType *PFTy = 0;
3022 const FunctionType *Ty = 0;
3023 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3024 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3025 // Pull out the types of all of the arguments...
3026 std::vector<const Type*> ParamTypes;
3027 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3028 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003029
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 if (!FunctionType::isValidReturnType(RetType))
3031 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003032
Owen Andersondebcb012009-07-29 22:17:13 +00003033 Ty = FunctionType::get(RetType, ParamTypes, false);
3034 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003036
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 // Look up the callee.
3038 Value *Callee;
3039 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003040
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3042 // function attributes.
3043 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3044 if (FnAttrs & ObsoleteFuncAttrs) {
3045 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3046 FnAttrs &= ~ObsoleteFuncAttrs;
3047 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003048
Chris Lattnerdf986172009-01-02 07:01:27 +00003049 // Set up the Attributes for the function.
3050 SmallVector<AttributeWithIndex, 8> Attrs;
3051 if (RetAttrs != Attribute::None)
3052 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003053
Chris Lattnerdf986172009-01-02 07:01:27 +00003054 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003055
Chris Lattnerdf986172009-01-02 07:01:27 +00003056 // Loop through FunctionType's arguments and ensure they are specified
3057 // correctly. Also, gather any parameter attributes.
3058 FunctionType::param_iterator I = Ty->param_begin();
3059 FunctionType::param_iterator E = Ty->param_end();
3060 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3061 const Type *ExpectedTy = 0;
3062 if (I != E) {
3063 ExpectedTy = *I++;
3064 } else if (!Ty->isVarArg()) {
3065 return Error(ArgList[i].Loc, "too many arguments specified");
3066 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003067
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3069 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3070 ExpectedTy->getDescription() + "'");
3071 Args.push_back(ArgList[i].V);
3072 if (ArgList[i].Attrs != Attribute::None)
3073 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3074 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003075
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 if (I != E)
3077 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003078
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 if (FnAttrs != Attribute::None)
3080 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003081
Chris Lattnerdf986172009-01-02 07:01:27 +00003082 // Finish off the Attributes and check them
3083 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003084
Chris Lattnerdf986172009-01-02 07:01:27 +00003085 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3086 cast<BasicBlock>(UnwindBB),
3087 Args.begin(), Args.end());
3088 II->setCallingConv(CC);
3089 II->setAttributes(PAL);
3090 Inst = II;
3091 return false;
3092}
3093
3094
3095
3096//===----------------------------------------------------------------------===//
3097// Binary Operators.
3098//===----------------------------------------------------------------------===//
3099
3100/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003101/// ::= ArithmeticOps TypeAndValue ',' Value
3102///
3103/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3104/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003105bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003106 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 LocTy Loc; Value *LHS, *RHS;
3108 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3109 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3110 ParseValue(LHS->getType(), RHS, PFS))
3111 return true;
3112
Chris Lattnere914b592009-01-05 08:24:46 +00003113 bool Valid;
3114 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003115 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003116 case 0: // int or FP.
3117 Valid = LHS->getType()->isIntOrIntVector() ||
3118 LHS->getType()->isFPOrFPVector();
3119 break;
3120 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3121 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3122 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003123
Chris Lattnere914b592009-01-05 08:24:46 +00003124 if (!Valid)
3125 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003126
Chris Lattnerdf986172009-01-02 07:01:27 +00003127 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3128 return false;
3129}
3130
3131/// ParseLogical
3132/// ::= ArithmeticOps TypeAndValue ',' Value {
3133bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3134 unsigned Opc) {
3135 LocTy Loc; Value *LHS, *RHS;
3136 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3137 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3138 ParseValue(LHS->getType(), RHS, PFS))
3139 return true;
3140
3141 if (!LHS->getType()->isIntOrIntVector())
3142 return Error(Loc,"instruction requires integer or integer vector operands");
3143
3144 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3145 return false;
3146}
3147
3148
3149/// ParseCompare
3150/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3151/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003152bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3153 unsigned Opc) {
3154 // Parse the integer/fp comparison predicate.
3155 LocTy Loc;
3156 unsigned Pred;
3157 Value *LHS, *RHS;
3158 if (ParseCmpPredicate(Pred, Opc) ||
3159 ParseTypeAndValue(LHS, Loc, PFS) ||
3160 ParseToken(lltok::comma, "expected ',' after compare value") ||
3161 ParseValue(LHS->getType(), RHS, PFS))
3162 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003163
Chris Lattnerdf986172009-01-02 07:01:27 +00003164 if (Opc == Instruction::FCmp) {
3165 if (!LHS->getType()->isFPOrFPVector())
3166 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003167 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003168 } else {
3169 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003170 if (!LHS->getType()->isIntOrIntVector() &&
3171 !isa<PointerType>(LHS->getType()))
3172 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003173 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003174 }
3175 return false;
3176}
3177
3178//===----------------------------------------------------------------------===//
3179// Other Instructions.
3180//===----------------------------------------------------------------------===//
3181
3182
3183/// ParseCast
3184/// ::= CastOpc TypeAndValue 'to' Type
3185bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3186 unsigned Opc) {
3187 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003188 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003189 if (ParseTypeAndValue(Op, Loc, PFS) ||
3190 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3191 ParseType(DestTy))
3192 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003193
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003194 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3195 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 return Error(Loc, "invalid cast opcode for cast from '" +
3197 Op->getType()->getDescription() + "' to '" +
3198 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003199 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3201 return false;
3202}
3203
3204/// ParseSelect
3205/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3206bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3207 LocTy Loc;
3208 Value *Op0, *Op1, *Op2;
3209 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3210 ParseToken(lltok::comma, "expected ',' after select condition") ||
3211 ParseTypeAndValue(Op1, PFS) ||
3212 ParseToken(lltok::comma, "expected ',' after select value") ||
3213 ParseTypeAndValue(Op2, PFS))
3214 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003215
Chris Lattnerdf986172009-01-02 07:01:27 +00003216 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3217 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003218
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 Inst = SelectInst::Create(Op0, Op1, Op2);
3220 return false;
3221}
3222
Chris Lattner0088a5c2009-01-05 08:18:44 +00003223/// ParseVA_Arg
3224/// ::= 'va_arg' TypeAndValue ',' Type
3225bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003227 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003228 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 if (ParseTypeAndValue(Op, PFS) ||
3230 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003231 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Chris Lattner0088a5c2009-01-05 08:18:44 +00003234 if (!EltTy->isFirstClassType())
3235 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003236
3237 Inst = new VAArgInst(Op, EltTy);
3238 return false;
3239}
3240
3241/// ParseExtractElement
3242/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3243bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3244 LocTy Loc;
3245 Value *Op0, *Op1;
3246 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3247 ParseToken(lltok::comma, "expected ',' after extract value") ||
3248 ParseTypeAndValue(Op1, PFS))
3249 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3252 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003253
Eric Christophera3500da2009-07-25 02:28:41 +00003254 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 return false;
3256}
3257
3258/// ParseInsertElement
3259/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3260bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3261 LocTy Loc;
3262 Value *Op0, *Op1, *Op2;
3263 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3264 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3265 ParseTypeAndValue(Op1, PFS) ||
3266 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3267 ParseTypeAndValue(Op2, PFS))
3268 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003271 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3274 return false;
3275}
3276
3277/// ParseShuffleVector
3278/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3279bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3280 LocTy Loc;
3281 Value *Op0, *Op1, *Op2;
3282 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3283 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3284 ParseTypeAndValue(Op1, PFS) ||
3285 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3286 ParseTypeAndValue(Op2, PFS))
3287 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003288
Chris Lattnerdf986172009-01-02 07:01:27 +00003289 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3290 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003291
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3293 return false;
3294}
3295
3296/// ParsePHI
Victor Hernandez3e0c99a2009-09-25 18:11:52 +00003297/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003298bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003299 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 Value *Op0, *Op1;
3301 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 if (ParseType(Ty) ||
3304 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3305 ParseValue(Ty, Op0, PFS) ||
3306 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003307 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3309 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003310
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3312 while (1) {
3313 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003314
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003315 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 break;
3317
Devang Patela43d46f2009-10-16 18:45:49 +00003318 if (Lex.getKind() == lltok::NamedOrCustomMD)
3319 break;
3320
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003321 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 ParseValue(Ty, Op0, PFS) ||
3323 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003324 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3326 return true;
3327 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003328
Devang Patela43d46f2009-10-16 18:45:49 +00003329 if (Lex.getKind() == lltok::NamedOrCustomMD)
3330 if (ParseOptionalCustomMetadata()) return true;
3331
Chris Lattnerdf986172009-01-02 07:01:27 +00003332 if (!Ty->isFirstClassType())
3333 return Error(TypeLoc, "phi node must have first class type");
3334
3335 PHINode *PN = PHINode::Create(Ty);
3336 PN->reserveOperandSpace(PHIVals.size());
3337 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3338 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3339 Inst = PN;
3340 return false;
3341}
3342
3343/// ParseCall
3344/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3345/// ParameterList OptionalAttrs
3346bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3347 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003348 unsigned RetAttrs, FnAttrs;
3349 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003350 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 LocTy RetTypeLoc;
3352 ValID CalleeID;
3353 SmallVector<ParamInfo, 16> ArgList;
3354 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003355
Chris Lattnerdf986172009-01-02 07:01:27 +00003356 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3357 ParseOptionalCallingConv(CC) ||
3358 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003359 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 ParseValID(CalleeID) ||
3361 ParseParameterList(ArgList, PFS) ||
3362 ParseOptionalAttrs(FnAttrs, 2))
3363 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003364
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 // If RetType is a non-function pointer type, then this is the short syntax
3366 // for the call, which means that RetType is just the return type. Infer the
3367 // rest of the function argument types from the arguments that are present.
3368 const PointerType *PFTy = 0;
3369 const FunctionType *Ty = 0;
3370 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3371 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3372 // Pull out the types of all of the arguments...
3373 std::vector<const Type*> ParamTypes;
3374 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3375 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003376
Chris Lattnerdf986172009-01-02 07:01:27 +00003377 if (!FunctionType::isValidReturnType(RetType))
3378 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Owen Andersondebcb012009-07-29 22:17:13 +00003380 Ty = FunctionType::get(RetType, ParamTypes, false);
3381 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003383
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 // Look up the callee.
3385 Value *Callee;
3386 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003387
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3389 // function attributes.
3390 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3391 if (FnAttrs & ObsoleteFuncAttrs) {
3392 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3393 FnAttrs &= ~ObsoleteFuncAttrs;
3394 }
3395
3396 // Set up the Attributes for the function.
3397 SmallVector<AttributeWithIndex, 8> Attrs;
3398 if (RetAttrs != Attribute::None)
3399 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003400
Chris Lattnerdf986172009-01-02 07:01:27 +00003401 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003402
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 // Loop through FunctionType's arguments and ensure they are specified
3404 // correctly. Also, gather any parameter attributes.
3405 FunctionType::param_iterator I = Ty->param_begin();
3406 FunctionType::param_iterator E = Ty->param_end();
3407 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3408 const Type *ExpectedTy = 0;
3409 if (I != E) {
3410 ExpectedTy = *I++;
3411 } else if (!Ty->isVarArg()) {
3412 return Error(ArgList[i].Loc, "too many arguments specified");
3413 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003414
Chris Lattnerdf986172009-01-02 07:01:27 +00003415 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3416 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3417 ExpectedTy->getDescription() + "'");
3418 Args.push_back(ArgList[i].V);
3419 if (ArgList[i].Attrs != Attribute::None)
3420 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3421 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003422
Chris Lattnerdf986172009-01-02 07:01:27 +00003423 if (I != E)
3424 return Error(CallLoc, "not enough parameters specified for call");
3425
3426 if (FnAttrs != Attribute::None)
3427 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3428
3429 // Finish off the Attributes and check them
3430 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003431
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3433 CI->setTailCall(isTail);
3434 CI->setCallingConv(CC);
3435 CI->setAttributes(PAL);
3436 Inst = CI;
3437 return false;
3438}
3439
3440//===----------------------------------------------------------------------===//
3441// Memory Instructions.
3442//===----------------------------------------------------------------------===//
3443
3444/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003445/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3446/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003447bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez3e0c99a2009-09-25 18:11:52 +00003448 unsigned Opc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003449 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003450 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003451 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003453 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003454
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003455 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003456 if (Lex.getKind() == lltok::kw_align
3457 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003458 if (ParseOptionalInfo(Alignment)) return true;
3459 } else {
3460 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3461 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003462 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003463 }
3464 }
3465
Owen Anderson1d0be152009-08-13 21:58:54 +00003466 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003467 return Error(SizeLoc, "element count must be i32");
3468
Victor Hernandez3e0c99a2009-09-25 18:11:52 +00003469 if (Opc == Instruction::Malloc)
3470 Inst = new MallocInst(Ty, Size, Alignment);
3471 else
Owen Anderson50dead02009-07-15 23:53:25 +00003472 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 return false;
3474}
3475
3476/// ParseFree
3477/// ::= 'free' TypeAndValue
3478bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3479 Value *Val; LocTy Loc;
3480 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3481 if (!isa<PointerType>(Val->getType()))
3482 return Error(Loc, "operand to free must be a pointer");
3483 Inst = new FreeInst(Val);
3484 return false;
3485}
3486
3487/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003488/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003489bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3490 bool isVolatile) {
3491 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003492 unsigned Alignment = 0;
3493 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003494
Devang Patelf633a062009-09-17 23:04:48 +00003495 if (EatIfPresent(lltok::comma))
3496 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003497
3498 if (!isa<PointerType>(Val->getType()) ||
3499 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3500 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003501
Chris Lattnerdf986172009-01-02 07:01:27 +00003502 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3503 return false;
3504}
3505
3506/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003507/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003508bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3509 bool isVolatile) {
3510 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003511 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003512 if (ParseTypeAndValue(Val, Loc, PFS) ||
3513 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003514 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003515 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003516
3517 if (EatIfPresent(lltok::comma))
3518 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003519
Chris Lattnerdf986172009-01-02 07:01:27 +00003520 if (!isa<PointerType>(Ptr->getType()))
3521 return Error(PtrLoc, "store operand must be a pointer");
3522 if (!Val->getType()->isFirstClassType())
3523 return Error(Loc, "store operand must be a first class value");
3524 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3525 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003526
Chris Lattnerdf986172009-01-02 07:01:27 +00003527 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3528 return false;
3529}
3530
3531/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003532/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003533/// FIXME: Remove support for getresult in LLVM 3.0
3534bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3535 Value *Val; LocTy ValLoc, EltLoc;
3536 unsigned Element;
3537 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003539 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003541
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3543 return Error(ValLoc, "getresult inst requires an aggregate operand");
3544 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3545 return Error(EltLoc, "invalid getresult index for value");
3546 Inst = ExtractValueInst::Create(Val, Element);
3547 return false;
3548}
3549
3550/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003551/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003552bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3553 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003554
Dan Gohmandcb40a32009-07-29 15:58:36 +00003555 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003556
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003557 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003558
Chris Lattnerdf986172009-01-02 07:01:27 +00003559 if (!isa<PointerType>(Ptr->getType()))
3560 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003561
Chris Lattnerdf986172009-01-02 07:01:27 +00003562 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003563 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003564 if (Lex.getKind() == lltok::NamedOrCustomMD)
3565 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003566 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 if (!isa<IntegerType>(Val->getType()))
3568 return Error(EltLoc, "getelementptr index must be an integer");
3569 Indices.push_back(Val);
3570 }
Devang Patel6225d642009-10-13 18:49:55 +00003571 if (Lex.getKind() == lltok::NamedOrCustomMD)
3572 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003573
Chris Lattnerdf986172009-01-02 07:01:27 +00003574 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3575 Indices.begin(), Indices.end()))
3576 return Error(Loc, "invalid getelementptr indices");
3577 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003578 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003579 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003580 return false;
3581}
3582
3583/// ParseExtractValue
3584/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3585bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3586 Value *Val; LocTy Loc;
3587 SmallVector<unsigned, 4> Indices;
3588 if (ParseTypeAndValue(Val, Loc, PFS) ||
3589 ParseIndexList(Indices))
3590 return true;
3591
3592 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3593 return Error(Loc, "extractvalue operand must be array or struct");
3594
3595 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3596 Indices.end()))
3597 return Error(Loc, "invalid indices for extractvalue");
3598 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3599 return false;
3600}
3601
3602/// ParseInsertValue
3603/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3604bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3605 Value *Val0, *Val1; LocTy Loc0, Loc1;
3606 SmallVector<unsigned, 4> Indices;
3607 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3608 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3609 ParseTypeAndValue(Val1, Loc1, PFS) ||
3610 ParseIndexList(Indices))
3611 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003612
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3614 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003615
Chris Lattnerdf986172009-01-02 07:01:27 +00003616 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3617 Indices.end()))
3618 return Error(Loc0, "invalid indices for insertvalue");
3619 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3620 return false;
3621}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003622
3623//===----------------------------------------------------------------------===//
3624// Embedded metadata.
3625//===----------------------------------------------------------------------===//
3626
3627/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003628/// ::= Element (',' Element)*
3629/// Element
3630/// ::= 'null' | TypeAndValue
3631bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003632 assert(Lex.getKind() == lltok::lbrace);
3633 Lex.Lex();
3634 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003635 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003636 if (Lex.getKind() == lltok::kw_null) {
3637 Lex.Lex();
3638 V = 0;
3639 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003640 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003641 if (ParseType(Ty)) return true;
3642 if (Lex.getKind() == lltok::Metadata) {
3643 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003644 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003645 if (!ParseMDNode(Node))
3646 V = Node;
3647 else {
3648 MetadataBase *MDS = 0;
3649 if (ParseMDString(MDS)) return true;
3650 V = MDS;
3651 }
3652 } else {
3653 Constant *C;
3654 if (ParseGlobalValue(Ty, C)) return true;
3655 V = C;
3656 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003657 }
3658 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003659 } while (EatIfPresent(lltok::comma));
3660
3661 return false;
3662}