blob: 52fd2b21e1a06dad0a0fc3b95022182c6086a38c [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() {
Victor Hernandez68afa542009-10-21 19:11:40 +000072 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000073 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000074 if (MallocF) {
75 MallocF->setName("malloc");
76 // If setName() does not set the name to "malloc", then there is already a
77 // declaration of "malloc". In that case, iterate over all calls to MallocF
78 // and get them to call the declared "malloc" instead.
79 if (MallocF->getName() != "malloc") {
Victor Hernandez68afa542009-10-21 19:11:40 +000080 Constant* RealMallocF = M->getFunction("malloc");
81 if (RealMallocF->getType() != MallocF->getType())
82 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
83 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000084 MallocF->eraseFromParent();
85 MallocF = NULL;
86 }
87 }
88
Chris Lattnerdf986172009-01-02 07:01:27 +000089 if (!ForwardRefTypes.empty())
90 return Error(ForwardRefTypes.begin()->second.second,
91 "use of undefined type named '" +
92 ForwardRefTypes.begin()->first + "'");
93 if (!ForwardRefTypeIDs.empty())
94 return Error(ForwardRefTypeIDs.begin()->second.second,
95 "use of undefined type '%" +
96 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerdf986172009-01-02 07:01:27 +000098 if (!ForwardRefVals.empty())
99 return Error(ForwardRefVals.begin()->second.second,
100 "use of undefined value '@" + ForwardRefVals.begin()->first +
101 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefValIDs.empty())
104 return Error(ForwardRefValIDs.begin()->second.second,
105 "use of undefined value '@" +
106 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Devang Patel1c7eea62009-07-08 19:23:54 +0000108 if (!ForwardRefMDNodes.empty())
109 return Error(ForwardRefMDNodes.begin()->second.second,
110 "use of undefined metadata '!" +
111 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113
Chris Lattnerdf986172009-01-02 07:01:27 +0000114 // Look for intrinsic functions and CallInst that need to be upgraded
115 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
116 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patele4b27562009-08-28 23:24:31 +0000118 // Check debug info intrinsics.
119 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000120 return false;
121}
122
123//===----------------------------------------------------------------------===//
124// Top-Level Entities
125//===----------------------------------------------------------------------===//
126
127bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000128 while (1) {
129 switch (Lex.getKind()) {
130 default: return TokError("expected top-level entity");
131 case lltok::Eof: return false;
132 //case lltok::kw_define:
133 case lltok::kw_declare: if (ParseDeclare()) return true; break;
134 case lltok::kw_define: if (ParseDefine()) return true; break;
135 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
136 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
137 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
138 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000139 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000140 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
141 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000142 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000143 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000144 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000145 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000146
147 // The Global variable production with no name can have many different
148 // optional leading prefixes, the production is:
149 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
150 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000151 case lltok::kw_private : // OptionalLinkage
152 case lltok::kw_linker_private: // OptionalLinkage
153 case lltok::kw_internal: // OptionalLinkage
154 case lltok::kw_weak: // OptionalLinkage
155 case lltok::kw_weak_odr: // OptionalLinkage
156 case lltok::kw_linkonce: // OptionalLinkage
157 case lltok::kw_linkonce_odr: // OptionalLinkage
158 case lltok::kw_appending: // OptionalLinkage
159 case lltok::kw_dllexport: // OptionalLinkage
160 case lltok::kw_common: // OptionalLinkage
161 case lltok::kw_dllimport: // OptionalLinkage
162 case lltok::kw_extern_weak: // OptionalLinkage
163 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000164 unsigned Linkage, Visibility;
165 if (ParseOptionalLinkage(Linkage) ||
166 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000167 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 return true;
169 break;
170 }
171 case lltok::kw_default: // OptionalVisibility
172 case lltok::kw_hidden: // OptionalVisibility
173 case lltok::kw_protected: { // OptionalVisibility
174 unsigned Visibility;
175 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000176 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 return true;
178 break;
179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000180
Chris Lattnerdf986172009-01-02 07:01:27 +0000181 case lltok::kw_thread_local: // OptionalThreadLocal
182 case lltok::kw_addrspace: // OptionalAddrSpace
183 case lltok::kw_constant: // GlobalType
184 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000185 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 break;
187 }
188 }
189}
190
191
192/// toplevelentity
193/// ::= 'module' 'asm' STRINGCONSTANT
194bool LLParser::ParseModuleAsm() {
195 assert(Lex.getKind() == lltok::kw_module);
196 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000197
198 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000199 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
200 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000201
Chris Lattnerdf986172009-01-02 07:01:27 +0000202 const std::string &AsmSoFar = M->getModuleInlineAsm();
203 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000206 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 return false;
208}
209
210/// toplevelentity
211/// ::= 'target' 'triple' '=' STRINGCONSTANT
212/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
213bool LLParser::ParseTargetDefinition() {
214 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000215 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 switch (Lex.Lex()) {
217 default: return TokError("unknown target property");
218 case lltok::kw_triple:
219 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000220 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
221 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000222 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000223 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000224 return false;
225 case lltok::kw_datalayout:
226 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000227 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
228 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000230 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 return false;
232 }
233}
234
235/// toplevelentity
236/// ::= 'deplibs' '=' '[' ']'
237/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
238bool LLParser::ParseDepLibs() {
239 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000240 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000241 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
242 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
243 return true;
244
245 if (EatIfPresent(lltok::rsquare))
246 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 std::string Str;
249 if (ParseStringConstant(Str)) return true;
250 M->addLibrary(Str);
251
252 while (EatIfPresent(lltok::comma)) {
253 if (ParseStringConstant(Str)) return true;
254 M->addLibrary(Str);
255 }
256
257 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000258}
259
Dan Gohman3845e502009-08-12 23:32:33 +0000260/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000261/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000262/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000263bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000264 unsigned TypeID = NumberedTypes.size();
265
266 // Handle the LocalVarID form.
267 if (Lex.getKind() == lltok::LocalVarID) {
268 if (Lex.getUIntVal() != TypeID)
269 return Error(Lex.getLoc(), "type expected to be numbered '%" +
270 utostr(TypeID) + "'");
271 Lex.Lex(); // eat LocalVarID;
272
273 if (ParseToken(lltok::equal, "expected '=' after name"))
274 return true;
275 }
276
Chris Lattnerdf986172009-01-02 07:01:27 +0000277 assert(Lex.getKind() == lltok::kw_type);
278 LocTy TypeLoc = Lex.getLoc();
279 Lex.Lex(); // eat kw_type
280
Owen Anderson1d0be152009-08-13 21:58:54 +0000281 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000283
Chris Lattnerdf986172009-01-02 07:01:27 +0000284 // See if this type was previously referenced.
285 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
286 FI = ForwardRefTypeIDs.find(TypeID);
287 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000288 if (FI->second.first.get() == Ty)
289 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerdf986172009-01-02 07:01:27 +0000291 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
292 Ty = FI->second.first.get();
293 ForwardRefTypeIDs.erase(FI);
294 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerdf986172009-01-02 07:01:27 +0000298 return false;
299}
300
301/// toplevelentity
302/// ::= LocalVar '=' 'type' type
303bool LLParser::ParseNamedType() {
304 std::string Name = Lex.getStrVal();
305 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000306 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000307
Owen Anderson1d0be152009-08-13 21:58:54 +0000308 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000310 if (ParseToken(lltok::equal, "expected '=' after name") ||
311 ParseToken(lltok::kw_type, "expected 'type' after name") ||
312 ParseType(Ty))
313 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 // Set the type name, checking for conflicts as we do so.
316 bool AlreadyExists = M->addTypeName(Name, Ty);
317 if (!AlreadyExists) return false;
318
319 // See if this type is a forward reference. We need to eagerly resolve
320 // types to allow recursive type redefinitions below.
321 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
322 FI = ForwardRefTypes.find(Name);
323 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000324 if (FI->second.first.get() == Ty)
325 return Error(NameLoc, "self referential type is invalid");
326
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
328 Ty = FI->second.first.get();
329 ForwardRefTypes.erase(FI);
330 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 // Inserting a name that is already defined, get the existing name.
333 const Type *Existing = M->getTypeByName(Name);
334 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000335
Chris Lattnerdf986172009-01-02 07:01:27 +0000336 // Otherwise, this is an attempt to redefine a type. That's okay if
337 // the redefinition is identical to the original.
338 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
339 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000340
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 // Any other kind of (non-equivalent) redefinition is an error.
342 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
343 Ty->getDescription() + "'");
344}
345
346
347/// toplevelentity
348/// ::= 'declare' FunctionHeader
349bool LLParser::ParseDeclare() {
350 assert(Lex.getKind() == lltok::kw_declare);
351 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000352
Chris Lattnerdf986172009-01-02 07:01:27 +0000353 Function *F;
354 return ParseFunctionHeader(F, false);
355}
356
357/// toplevelentity
358/// ::= 'define' FunctionHeader '{' ...
359bool LLParser::ParseDefine() {
360 assert(Lex.getKind() == lltok::kw_define);
361 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000364 return ParseFunctionHeader(F, true) ||
365 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000366}
367
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000368/// ParseGlobalType
369/// ::= 'constant'
370/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000371bool LLParser::ParseGlobalType(bool &IsConstant) {
372 if (Lex.getKind() == lltok::kw_constant)
373 IsConstant = true;
374 else if (Lex.getKind() == lltok::kw_global)
375 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000376 else {
377 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000378 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000379 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 Lex.Lex();
381 return false;
382}
383
Dan Gohman3845e502009-08-12 23:32:33 +0000384/// ParseUnnamedGlobal:
385/// OptionalVisibility ALIAS ...
386/// OptionalLinkage OptionalVisibility ... -> global variable
387/// GlobalID '=' OptionalVisibility ALIAS ...
388/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
389bool LLParser::ParseUnnamedGlobal() {
390 unsigned VarID = NumberedVals.size();
391 std::string Name;
392 LocTy NameLoc = Lex.getLoc();
393
394 // Handle the GlobalID form.
395 if (Lex.getKind() == lltok::GlobalID) {
396 if (Lex.getUIntVal() != VarID)
397 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
398 utostr(VarID) + "'");
399 Lex.Lex(); // eat GlobalID;
400
401 if (ParseToken(lltok::equal, "expected '=' after name"))
402 return true;
403 }
404
405 bool HasLinkage;
406 unsigned Linkage, Visibility;
407 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
408 ParseOptionalVisibility(Visibility))
409 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Dan Gohman3845e502009-08-12 23:32:33 +0000411 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
412 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
413 return ParseAlias(Name, NameLoc, Visibility);
414}
415
Chris Lattnerdf986172009-01-02 07:01:27 +0000416/// ParseNamedGlobal:
417/// GlobalVar '=' OptionalVisibility ALIAS ...
418/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
419bool LLParser::ParseNamedGlobal() {
420 assert(Lex.getKind() == lltok::GlobalVar);
421 LocTy NameLoc = Lex.getLoc();
422 std::string Name = Lex.getStrVal();
423 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000424
Chris Lattnerdf986172009-01-02 07:01:27 +0000425 bool HasLinkage;
426 unsigned Linkage, Visibility;
427 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
428 ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
430 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Chris Lattnerdf986172009-01-02 07:01:27 +0000432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
435}
436
Devang Patel256be962009-07-20 19:00:08 +0000437// MDString:
438// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000439bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000440 std::string Str;
441 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000442 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000443 return false;
444}
445
446// MDNode:
447// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000448bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000449 // !{ ..., !42, ... }
450 unsigned MID = 0;
451 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000452
Devang Patel256be962009-07-20 19:00:08 +0000453 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000454 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000455 if (I != MetadataCache.end()) {
456 Node = I->second;
457 return false;
458 }
459
460 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000461 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000462 FI = ForwardRefMDNodes.find(MID);
463 if (FI != ForwardRefMDNodes.end()) {
464 Node = FI->second.first;
465 return false;
466 }
467
468 // Create MDNode forward reference
469 SmallVector<Value *, 1> Elts;
470 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000471 Elts.push_back(MDString::get(Context, FwdRefName));
472 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000473 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
474 Node = FwdNode;
475 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000476}
Devang Patel256be962009-07-20 19:00:08 +0000477
Devang Pateleff2ab62009-07-29 00:34:02 +0000478///ParseNamedMetadata:
479/// !foo = !{ !1, !2 }
480bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000481 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000482 Lex.Lex();
483 std::string Name = Lex.getStrVal();
484
485 if (ParseToken(lltok::equal, "expected '=' here"))
486 return true;
487
488 if (Lex.getKind() != lltok::Metadata)
489 return TokError("Expected '!' here");
490 Lex.Lex();
491
492 if (Lex.getKind() != lltok::lbrace)
493 return TokError("Expected '{' here");
494 Lex.Lex();
495 SmallVector<MetadataBase *, 8> Elts;
496 do {
497 if (Lex.getKind() != lltok::Metadata)
498 return TokError("Expected '!' here");
499 Lex.Lex();
500 MetadataBase *N = 0;
501 if (ParseMDNode(N)) return true;
502 Elts.push_back(N);
503 } while (EatIfPresent(lltok::comma));
504
505 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
506 return true;
507
Owen Anderson1d0be152009-08-13 21:58:54 +0000508 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000509 return false;
510}
511
Devang Patel923078c2009-07-01 19:21:12 +0000512/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000513/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000514bool LLParser::ParseStandaloneMetadata() {
515 assert(Lex.getKind() == lltok::Metadata);
516 Lex.Lex();
517 unsigned MetadataID = 0;
518 if (ParseUInt32(MetadataID))
519 return true;
520 if (MetadataCache.find(MetadataID) != MetadataCache.end())
521 return TokError("Metadata id is already used");
522 if (ParseToken(lltok::equal, "expected '=' here"))
523 return true;
524
525 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000526 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000527 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000528 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529
Devang Patel104cf9e2009-07-23 01:07:34 +0000530 if (Lex.getKind() != lltok::Metadata)
531 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000532
Devang Patel104cf9e2009-07-23 01:07:34 +0000533 Lex.Lex();
534 if (Lex.getKind() != lltok::lbrace)
535 return TokError("Expected '{' here");
536
537 SmallVector<Value *, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000539 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000540 return true;
541
Owen Anderson647e3012009-07-31 21:35:40 +0000542 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000543 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000544 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000545 FI = ForwardRefMDNodes.find(MetadataID);
546 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000547 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000548 FwdNode->replaceAllUsesWith(Init);
549 ForwardRefMDNodes.erase(FI);
550 }
551
Devang Patel923078c2009-07-01 19:21:12 +0000552 return false;
553}
554
Chris Lattnerdf986172009-01-02 07:01:27 +0000555/// ParseAlias:
556/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
557/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000558/// ::= TypeAndValue
559/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000560/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000561///
562/// Everything through visibility has already been parsed.
563///
564bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
567 Lex.Lex();
568 unsigned Linkage;
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
571 return true;
572
573 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000576 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000577 Linkage != GlobalValue::PrivateLinkage &&
578 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000579 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000580
Chris Lattnerdf986172009-01-02 07:01:27 +0000581 Constant *Aliasee;
582 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000583 if (Lex.getKind() != lltok::kw_bitcast &&
584 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000585 if (ParseGlobalTypeAndValue(Aliasee)) return true;
586 } else {
587 // The bitcast dest type is not present, it is implied by the dest type.
588 ValID ID;
589 if (ParseValID(ID)) return true;
590 if (ID.Kind != ValID::t_Constant)
591 return Error(AliaseeLoc, "invalid aliasee");
592 Aliasee = ID.ConstantVal;
593 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000594
Chris Lattnerdf986172009-01-02 07:01:27 +0000595 if (!isa<PointerType>(Aliasee->getType()))
596 return Error(AliaseeLoc, "alias must have pointer type");
597
598 // Okay, create the alias but do not insert it into the module yet.
599 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
600 (GlobalValue::LinkageTypes)Linkage, Name,
601 Aliasee);
602 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000603
Chris Lattnerdf986172009-01-02 07:01:27 +0000604 // See if this value already exists in the symbol table. If so, it is either
605 // a redefinition or a definition of a forward reference.
606 if (GlobalValue *Val =
607 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
608 // See if this was a redefinition. If so, there is no entry in
609 // ForwardRefVals.
610 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
611 I = ForwardRefVals.find(Name);
612 if (I == ForwardRefVals.end())
613 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
614
615 // Otherwise, this was a definition of forward ref. Verify that types
616 // agree.
617 if (Val->getType() != GA->getType())
618 return Error(NameLoc,
619 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000620
Chris Lattnerdf986172009-01-02 07:01:27 +0000621 // If they agree, just RAUW the old value with the alias and remove the
622 // forward ref info.
623 Val->replaceAllUsesWith(GA);
624 Val->eraseFromParent();
625 ForwardRefVals.erase(I);
626 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000627
Chris Lattnerdf986172009-01-02 07:01:27 +0000628 // Insert into the module, we know its name won't collide now.
629 M->getAliasList().push_back(GA);
630 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000631
Chris Lattnerdf986172009-01-02 07:01:27 +0000632 return false;
633}
634
635/// ParseGlobal
636/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
637/// OptionalAddrSpace GlobalType Type Const
638/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
639/// OptionalAddrSpace GlobalType Type Const
640///
641/// Everything through visibility has been parsed already.
642///
643bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
644 unsigned Linkage, bool HasLinkage,
645 unsigned Visibility) {
646 unsigned AddrSpace;
647 bool ThreadLocal, IsConstant;
648 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000649
Owen Anderson1d0be152009-08-13 21:58:54 +0000650 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000651 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
652 ParseOptionalAddrSpace(AddrSpace) ||
653 ParseGlobalType(IsConstant) ||
654 ParseType(Ty, TyLoc))
655 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000656
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 // If the linkage is specified and is external, then no initializer is
658 // present.
659 Constant *Init = 0;
660 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000661 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 Linkage != GlobalValue::ExternalLinkage)) {
663 if (ParseGlobalValue(Ty, Init))
664 return true;
665 }
666
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000667 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000668 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 GlobalVariable *GV = 0;
671
672 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000673 if (!Name.empty()) {
674 if ((GV = M->getGlobalVariable(Name, true)) &&
675 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 return Error(NameLoc, "redefinition of global '@" + Name + "'");
677 } else {
678 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
679 I = ForwardRefValIDs.find(NumberedVals.size());
680 if (I != ForwardRefValIDs.end()) {
681 GV = cast<GlobalVariable>(I->second.first);
682 ForwardRefValIDs.erase(I);
683 }
684 }
685
686 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000687 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000688 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000689 } else {
690 if (GV->getType()->getElementType() != Ty)
691 return Error(TyLoc,
692 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000693
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 // Move the forward-reference to the correct spot in the module.
695 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
696 }
697
698 if (Name.empty())
699 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000700
Chris Lattnerdf986172009-01-02 07:01:27 +0000701 // Set the parsed properties on the global.
702 if (Init)
703 GV->setInitializer(Init);
704 GV->setConstant(IsConstant);
705 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
706 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
707 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000708
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 // Parse attributes on the global.
710 while (Lex.getKind() == lltok::comma) {
711 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000712
Chris Lattnerdf986172009-01-02 07:01:27 +0000713 if (Lex.getKind() == lltok::kw_section) {
714 Lex.Lex();
715 GV->setSection(Lex.getStrVal());
716 if (ParseToken(lltok::StringConstant, "expected global section string"))
717 return true;
718 } else if (Lex.getKind() == lltok::kw_align) {
719 unsigned Alignment;
720 if (ParseOptionalAlignment(Alignment)) return true;
721 GV->setAlignment(Alignment);
722 } else {
723 TokError("unknown global variable property!");
724 }
725 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000726
Chris Lattnerdf986172009-01-02 07:01:27 +0000727 return false;
728}
729
730
731//===----------------------------------------------------------------------===//
732// GlobalValue Reference/Resolution Routines.
733//===----------------------------------------------------------------------===//
734
735/// GetGlobalVal - Get a value with the specified name or ID, creating a
736/// forward reference record if needed. This can return null if the value
737/// exists but does not have the right type.
738GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
739 LocTy Loc) {
740 const PointerType *PTy = dyn_cast<PointerType>(Ty);
741 if (PTy == 0) {
742 Error(Loc, "global variable reference must have pointer type");
743 return 0;
744 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000745
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 // Look this name up in the normal function symbol table.
747 GlobalValue *Val =
748 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 // If this is a forward reference for the value, see if we already created a
751 // forward ref record.
752 if (Val == 0) {
753 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
754 I = ForwardRefVals.find(Name);
755 if (I != ForwardRefVals.end())
756 Val = I->second.first;
757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // If we have the value in the symbol table or fwd-ref table, return it.
760 if (Val) {
761 if (Val->getType() == Ty) return Val;
762 Error(Loc, "'@" + Name + "' defined with type '" +
763 Val->getType()->getDescription() + "'");
764 return 0;
765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Chris Lattnerdf986172009-01-02 07:01:27 +0000767 // Otherwise, create a new forward reference for this value and remember it.
768 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000769 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
770 // Function types can return opaque but functions can't.
771 if (isa<OpaqueType>(FT->getReturnType())) {
772 Error(Loc, "function may not return opaque type");
773 return 0;
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000776 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000777 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000778 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
779 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
783 return FwdVal;
784}
785
786GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
787 const PointerType *PTy = dyn_cast<PointerType>(Ty);
788 if (PTy == 0) {
789 Error(Loc, "global variable reference must have pointer type");
790 return 0;
791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Chris Lattnerdf986172009-01-02 07:01:27 +0000793 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 // If this is a forward reference for the value, see if we already created a
796 // forward ref record.
797 if (Val == 0) {
798 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
799 I = ForwardRefValIDs.find(ID);
800 if (I != ForwardRefValIDs.end())
801 Val = I->second.first;
802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Chris Lattnerdf986172009-01-02 07:01:27 +0000804 // If we have the value in the symbol table or fwd-ref table, return it.
805 if (Val) {
806 if (Val->getType() == Ty) return Val;
807 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
808 Val->getType()->getDescription() + "'");
809 return 0;
810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 // Otherwise, create a new forward reference for this value and remember it.
813 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000814 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
815 // Function types can return opaque but functions can't.
816 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000817 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000818 return 0;
819 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000820 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000821 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000822 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
823 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Chris Lattnerdf986172009-01-02 07:01:27 +0000826 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
827 return FwdVal;
828}
829
830
831//===----------------------------------------------------------------------===//
832// Helper Routines.
833//===----------------------------------------------------------------------===//
834
835/// ParseToken - If the current token has the specified kind, eat it and return
836/// success. Otherwise, emit the specified error and return failure.
837bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
838 if (Lex.getKind() != T)
839 return TokError(ErrMsg);
840 Lex.Lex();
841 return false;
842}
843
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000844/// ParseStringConstant
845/// ::= StringConstant
846bool LLParser::ParseStringConstant(std::string &Result) {
847 if (Lex.getKind() != lltok::StringConstant)
848 return TokError("expected string constant");
849 Result = Lex.getStrVal();
850 Lex.Lex();
851 return false;
852}
853
854/// ParseUInt32
855/// ::= uint32
856bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
858 return TokError("expected integer");
859 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
860 if (Val64 != unsigned(Val64))
861 return TokError("expected 32-bit integer (too large)");
862 Val = Val64;
863 Lex.Lex();
864 return false;
865}
866
867
868/// ParseOptionalAddrSpace
869/// := /*empty*/
870/// := 'addrspace' '(' uint32 ')'
871bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
872 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000873 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000874 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000875 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000876 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000877 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000878}
Chris Lattnerdf986172009-01-02 07:01:27 +0000879
880/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
881/// indicates what kind of attribute list this is: 0: function arg, 1: result,
882/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000883/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000884bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
885 Attrs = Attribute::None;
886 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000887
Chris Lattnerdf986172009-01-02 07:01:27 +0000888 while (1) {
889 switch (Lex.getKind()) {
890 case lltok::kw_sext:
891 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000892 // Treat these as signext/zeroext if they occur in the argument list after
893 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
894 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
895 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000897 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000898 if (Lex.getKind() == lltok::kw_sext)
899 Attrs |= Attribute::SExt;
900 else
901 Attrs |= Attribute::ZExt;
902 break;
903 }
904 // FALL THROUGH.
905 default: // End of attributes.
906 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
907 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000908
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000909 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000911
Chris Lattnerdf986172009-01-02 07:01:27 +0000912 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000913 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
914 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
915 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
916 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
917 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
918 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
919 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
920 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000921
Devang Patel578efa92009-06-05 21:57:13 +0000922 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
923 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
924 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
925 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
926 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000927 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000928 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
929 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
930 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
931 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
932 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
933 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000934 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000935
Chris Lattnerdf986172009-01-02 07:01:27 +0000936 case lltok::kw_align: {
937 unsigned Alignment;
938 if (ParseOptionalAlignment(Alignment))
939 return true;
940 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
941 continue;
942 }
943 }
944 Lex.Lex();
945 }
946}
947
948/// ParseOptionalLinkage
949/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000950/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000951/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000952/// ::= 'internal'
953/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000954/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000955/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000956/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000957/// ::= 'appending'
958/// ::= 'dllexport'
959/// ::= 'common'
960/// ::= 'dllimport'
961/// ::= 'extern_weak'
962/// ::= 'external'
963bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
964 HasLinkage = false;
965 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000966 default: Res=GlobalValue::ExternalLinkage; return false;
967 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
968 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
969 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
970 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
971 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
972 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
973 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000974 case lltok::kw_available_externally:
975 Res = GlobalValue::AvailableExternallyLinkage;
976 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000977 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
978 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
979 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
980 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
981 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
982 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000983 }
984 Lex.Lex();
985 HasLinkage = true;
986 return false;
987}
988
989/// ParseOptionalVisibility
990/// ::= /*empty*/
991/// ::= 'default'
992/// ::= 'hidden'
993/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +0000994///
Chris Lattnerdf986172009-01-02 07:01:27 +0000995bool LLParser::ParseOptionalVisibility(unsigned &Res) {
996 switch (Lex.getKind()) {
997 default: Res = GlobalValue::DefaultVisibility; return false;
998 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
999 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1000 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1001 }
1002 Lex.Lex();
1003 return false;
1004}
1005
1006/// ParseOptionalCallingConv
1007/// ::= /*empty*/
1008/// ::= 'ccc'
1009/// ::= 'fastcc'
1010/// ::= 'coldcc'
1011/// ::= 'x86_stdcallcc'
1012/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001013/// ::= 'arm_apcscc'
1014/// ::= 'arm_aapcscc'
1015/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001016/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001017///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001018bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001019 switch (Lex.getKind()) {
1020 default: CC = CallingConv::C; return false;
1021 case lltok::kw_ccc: CC = CallingConv::C; break;
1022 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1023 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1024 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1025 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001026 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1027 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1028 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001029 case lltok::kw_cc: {
1030 unsigned ArbitraryCC;
1031 Lex.Lex();
1032 if (ParseUInt32(ArbitraryCC)) {
1033 return true;
1034 } else
1035 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1036 return false;
1037 }
1038 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001039 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001040
Chris Lattnerdf986172009-01-02 07:01:27 +00001041 Lex.Lex();
1042 return false;
1043}
1044
Devang Patel0475c912009-09-29 00:01:14 +00001045/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001046/// ::= /* empty */
Devang Patel0475c912009-09-29 00:01:14 +00001047/// ::= !dbg !42
1048bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001049 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001050 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001051
Chris Lattner52e20312009-10-19 05:31:10 +00001052 std::string Name = Lex.getStrVal();
1053 Lex.Lex();
1054
Devang Patelf633a062009-09-17 23:04:48 +00001055 if (Lex.getKind() != lltok::Metadata)
1056 return TokError("Expected '!' here");
1057 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001058
Devang Patelf633a062009-09-17 23:04:48 +00001059 MetadataBase *Node;
1060 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001061
Devang Patele30e6782009-09-28 21:41:20 +00001062 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001063 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1064 if (!MDK)
Devang Pateld9723e92009-10-20 22:50:27 +00001065 MDK = TheMetadata.registerMDKind(Name.c_str());
Devang Patel0475c912009-09-29 00:01:14 +00001066 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001067
Devang Patelf633a062009-09-17 23:04:48 +00001068 return false;
1069}
1070
Chris Lattnerdf986172009-01-02 07:01:27 +00001071/// ParseOptionalAlignment
1072/// ::= /* empty */
1073/// ::= 'align' 4
1074bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1075 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001076 if (!EatIfPresent(lltok::kw_align))
1077 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001078 LocTy AlignLoc = Lex.getLoc();
1079 if (ParseUInt32(Alignment)) return true;
1080 if (!isPowerOf2_32(Alignment))
1081 return Error(AlignLoc, "alignment is not a power of two");
1082 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001083}
1084
Devang Patelf633a062009-09-17 23:04:48 +00001085/// ParseOptionalInfo
1086/// ::= OptionalInfo (',' OptionalInfo)+
1087bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1088
1089 // FIXME: Handle customized metadata info attached with an instruction.
1090 do {
Devang Patel0475c912009-09-29 00:01:14 +00001091 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1092 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001093 } else if (Lex.getKind() == lltok::kw_align) {
1094 if (ParseOptionalAlignment(Alignment)) return true;
1095 } else
1096 return true;
1097 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001098
Devang Patelf633a062009-09-17 23:04:48 +00001099 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001100}
1101
Devang Patelf633a062009-09-17 23:04:48 +00001102
Chris Lattnerdf986172009-01-02 07:01:27 +00001103/// ParseIndexList
1104/// ::= (',' uint32)+
1105bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1106 if (Lex.getKind() != lltok::comma)
1107 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001108
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001109 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001110 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001111 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001112 Indices.push_back(Idx);
1113 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001114
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 return false;
1116}
1117
1118//===----------------------------------------------------------------------===//
1119// Type Parsing.
1120//===----------------------------------------------------------------------===//
1121
1122/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001123bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1124 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001125 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001126
Chris Lattnerdf986172009-01-02 07:01:27 +00001127 // Verify no unresolved uprefs.
1128 if (!UpRefs.empty())
1129 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001130
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001131 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001132 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001133
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 return false;
1135}
1136
1137/// HandleUpRefs - Every time we finish a new layer of types, this function is
1138/// called. It loops through the UpRefs vector, which is a list of the
1139/// currently active types. For each type, if the up-reference is contained in
1140/// the newly completed type, we decrement the level count. When the level
1141/// count reaches zero, the up-referenced type is the type that is passed in:
1142/// thus we can complete the cycle.
1143///
1144PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1145 // If Ty isn't abstract, or if there are no up-references in it, then there is
1146 // nothing to resolve here.
1147 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001148
Chris Lattnerdf986172009-01-02 07:01:27 +00001149 PATypeHolder Ty(ty);
1150#if 0
1151 errs() << "Type '" << Ty->getDescription()
1152 << "' newly formed. Resolving upreferences.\n"
1153 << UpRefs.size() << " upreferences active!\n";
1154#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001155
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1157 // to zero), we resolve them all together before we resolve them to Ty. At
1158 // the end of the loop, if there is anything to resolve to Ty, it will be in
1159 // this variable.
1160 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001161
Chris Lattnerdf986172009-01-02 07:01:27 +00001162 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1163 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1164 bool ContainsType =
1165 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1166 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001167
Chris Lattnerdf986172009-01-02 07:01:27 +00001168#if 0
1169 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1170 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1171 << (ContainsType ? "true" : "false")
1172 << " level=" << UpRefs[i].NestingLevel << "\n";
1173#endif
1174 if (!ContainsType)
1175 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001176
Chris Lattnerdf986172009-01-02 07:01:27 +00001177 // Decrement level of upreference
1178 unsigned Level = --UpRefs[i].NestingLevel;
1179 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001180
Chris Lattnerdf986172009-01-02 07:01:27 +00001181 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1182 if (Level != 0)
1183 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001184
Chris Lattnerdf986172009-01-02 07:01:27 +00001185#if 0
1186 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1187#endif
1188 if (!TypeToResolve)
1189 TypeToResolve = UpRefs[i].UpRefTy;
1190 else
1191 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1192 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1193 --i; // Do not skip the next element.
1194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001195
Chris Lattnerdf986172009-01-02 07:01:27 +00001196 if (TypeToResolve)
1197 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001198
Chris Lattnerdf986172009-01-02 07:01:27 +00001199 return Ty;
1200}
1201
1202
1203/// ParseTypeRec - The recursive function used to process the internal
1204/// implementation details of types.
1205bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1206 switch (Lex.getKind()) {
1207 default:
1208 return TokError("expected type");
1209 case lltok::Type:
1210 // TypeRec ::= 'float' | 'void' (etc)
1211 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001212 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001213 break;
1214 case lltok::kw_opaque:
1215 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001216 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001217 Lex.Lex();
1218 break;
1219 case lltok::lbrace:
1220 // TypeRec ::= '{' ... '}'
1221 if (ParseStructType(Result, false))
1222 return true;
1223 break;
1224 case lltok::lsquare:
1225 // TypeRec ::= '[' ... ']'
1226 Lex.Lex(); // eat the lsquare.
1227 if (ParseArrayVectorType(Result, false))
1228 return true;
1229 break;
1230 case lltok::less: // Either vector or packed struct.
1231 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001232 Lex.Lex();
1233 if (Lex.getKind() == lltok::lbrace) {
1234 if (ParseStructType(Result, true) ||
1235 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001236 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 } else if (ParseArrayVectorType(Result, true))
1238 return true;
1239 break;
1240 case lltok::LocalVar:
1241 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1242 // TypeRec ::= %foo
1243 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1244 Result = T;
1245 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001246 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001247 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1248 std::make_pair(Result,
1249 Lex.getLoc())));
1250 M->addTypeName(Lex.getStrVal(), Result.get());
1251 }
1252 Lex.Lex();
1253 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001254
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 case lltok::LocalVarID:
1256 // TypeRec ::= %4
1257 if (Lex.getUIntVal() < NumberedTypes.size())
1258 Result = NumberedTypes[Lex.getUIntVal()];
1259 else {
1260 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1261 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1262 if (I != ForwardRefTypeIDs.end())
1263 Result = I->second.first;
1264 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001265 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001266 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1267 std::make_pair(Result,
1268 Lex.getLoc())));
1269 }
1270 }
1271 Lex.Lex();
1272 break;
1273 case lltok::backslash: {
1274 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001275 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001276 unsigned Val;
1277 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001278 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001279 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1280 Result = OT;
1281 break;
1282 }
1283 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001284
1285 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 while (1) {
1287 switch (Lex.getKind()) {
1288 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001290
1291 // TypeRec ::= TypeRec '*'
1292 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001293 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001295 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001296 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001297 if (!PointerType::isValidElementType(Result.get()))
1298 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001299 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001300 Lex.Lex();
1301 break;
1302
1303 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1304 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001305 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001306 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001307 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001308 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001309 if (!PointerType::isValidElementType(Result.get()))
1310 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 unsigned AddrSpace;
1312 if (ParseOptionalAddrSpace(AddrSpace) ||
1313 ParseToken(lltok::star, "expected '*' in address space"))
1314 return true;
1315
Owen Andersondebcb012009-07-29 22:17:13 +00001316 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001317 break;
1318 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001319
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1321 case lltok::lparen:
1322 if (ParseFunctionType(Result))
1323 return true;
1324 break;
1325 }
1326 }
1327}
1328
1329/// ParseParameterList
1330/// ::= '(' ')'
1331/// ::= '(' Arg (',' Arg)* ')'
1332/// Arg
1333/// ::= Type OptionalAttributes Value OptionalAttributes
1334bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1335 PerFunctionState &PFS) {
1336 if (ParseToken(lltok::lparen, "expected '(' in call"))
1337 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001338
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 while (Lex.getKind() != lltok::rparen) {
1340 // If this isn't the first argument, we need a comma.
1341 if (!ArgList.empty() &&
1342 ParseToken(lltok::comma, "expected ',' in argument list"))
1343 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001344
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 // Parse the argument.
1346 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001347 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001348 unsigned ArgAttrs1, ArgAttrs2;
1349 Value *V;
1350 if (ParseType(ArgTy, ArgLoc) ||
1351 ParseOptionalAttrs(ArgAttrs1, 0) ||
1352 ParseValue(ArgTy, V, PFS) ||
1353 // FIXME: Should not allow attributes after the argument, remove this in
1354 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001355 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001356 return true;
1357 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1358 }
1359
1360 Lex.Lex(); // Lex the ')'.
1361 return false;
1362}
1363
1364
1365
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001366/// ParseArgumentList - Parse the argument list for a function type or function
1367/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001368/// ::= '(' ArgTypeListI ')'
1369/// ArgTypeListI
1370/// ::= /*empty*/
1371/// ::= '...'
1372/// ::= ArgTypeList ',' '...'
1373/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001374///
Chris Lattnerdf986172009-01-02 07:01:27 +00001375bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001376 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001377 isVarArg = false;
1378 assert(Lex.getKind() == lltok::lparen);
1379 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001380
Chris Lattnerdf986172009-01-02 07:01:27 +00001381 if (Lex.getKind() == lltok::rparen) {
1382 // empty
1383 } else if (Lex.getKind() == lltok::dotdotdot) {
1384 isVarArg = true;
1385 Lex.Lex();
1386 } else {
1387 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001388 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001389 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001391
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001392 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1393 // types (such as a function returning a pointer to itself). If parsing a
1394 // function prototype, we require fully resolved types.
1395 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001396 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001398 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001399 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 if (Lex.getKind() == lltok::LocalVar ||
1402 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1403 Name = Lex.getStrVal();
1404 Lex.Lex();
1405 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001406
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001407 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001408 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001409
Chris Lattnerdf986172009-01-02 07:01:27 +00001410 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001411
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001412 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001413 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001414 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 break;
1417 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001418
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 // Otherwise must be an argument type.
1420 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001421 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001422 ParseOptionalAttrs(Attrs, 0)) return true;
1423
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001424 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001425 return Error(TypeLoc, "argument can not have void type");
1426
Chris Lattnerdf986172009-01-02 07:01:27 +00001427 if (Lex.getKind() == lltok::LocalVar ||
1428 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1429 Name = Lex.getStrVal();
1430 Lex.Lex();
1431 } else {
1432 Name = "";
1433 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001434
1435 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1436 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001437
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1439 }
1440 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001441
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001442 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001443}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001444
Chris Lattnerdf986172009-01-02 07:01:27 +00001445/// ParseFunctionType
1446/// ::= Type ArgumentList OptionalAttrs
1447bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1448 assert(Lex.getKind() == lltok::lparen);
1449
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001450 if (!FunctionType::isValidReturnType(Result))
1451 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001452
Chris Lattnerdf986172009-01-02 07:01:27 +00001453 std::vector<ArgInfo> ArgList;
1454 bool isVarArg;
1455 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001456 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 // FIXME: Allow, but ignore attributes on function types!
1458 // FIXME: Remove in LLVM 3.0
1459 ParseOptionalAttrs(Attrs, 2))
1460 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 // Reject names on the arguments lists.
1463 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1464 if (!ArgList[i].Name.empty())
1465 return Error(ArgList[i].Loc, "argument name invalid in function type");
1466 if (!ArgList[i].Attrs != 0) {
1467 // Allow but ignore attributes on function types; this permits
1468 // auto-upgrade.
1469 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1470 }
1471 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001472
Chris Lattnerdf986172009-01-02 07:01:27 +00001473 std::vector<const Type*> ArgListTy;
1474 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1475 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Owen Andersondebcb012009-07-29 22:17:13 +00001477 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001478 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001479 return false;
1480}
1481
1482/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1483/// TypeRec
1484/// ::= '{' '}'
1485/// ::= '{' TypeRec (',' TypeRec)* '}'
1486/// ::= '<' '{' '}' '>'
1487/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1488bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1489 assert(Lex.getKind() == lltok::lbrace);
1490 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001491
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001492 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001493 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 return false;
1495 }
1496
1497 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001498 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 if (ParseTypeRec(Result)) return true;
1500 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001501
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001502 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001503 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001504 if (!StructType::isValidElementType(Result))
1505 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001507 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001508 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001510
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001511 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001512 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001513 if (!StructType::isValidElementType(Result))
1514 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001515
Chris Lattnerdf986172009-01-02 07:01:27 +00001516 ParamsList.push_back(Result);
1517 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001518
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001519 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1520 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001521
Chris Lattnerdf986172009-01-02 07:01:27 +00001522 std::vector<const Type*> ParamsListTy;
1523 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1524 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001525 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001526 return false;
1527}
1528
1529/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1530/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001532/// ::= '[' APSINTVAL 'x' Types ']'
1533/// ::= '<' APSINTVAL 'x' Types '>'
1534bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1535 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1536 Lex.getAPSIntVal().getBitWidth() > 64)
1537 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538
Chris Lattnerdf986172009-01-02 07:01:27 +00001539 LocTy SizeLoc = Lex.getLoc();
1540 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001541 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001543 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1544 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001545
1546 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001547 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001548 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001550 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001551 return Error(TypeLoc, "array and vector element type cannot be void");
1552
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001553 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1554 "expected end of sequential type"))
1555 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001558 if (Size == 0)
1559 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 if ((unsigned)Size != Size)
1561 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001562 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001564 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001565 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001566 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001567 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001568 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 }
1570 return false;
1571}
1572
1573//===----------------------------------------------------------------------===//
1574// Function Semantic Analysis.
1575//===----------------------------------------------------------------------===//
1576
1577LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1578 : P(p), F(f) {
1579
1580 // Insert unnamed arguments into the NumberedVals list.
1581 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1582 AI != E; ++AI)
1583 if (!AI->hasName())
1584 NumberedVals.push_back(AI);
1585}
1586
1587LLParser::PerFunctionState::~PerFunctionState() {
1588 // If there were any forward referenced non-basicblock values, delete them.
1589 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1590 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1591 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001592 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001593 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001594 delete I->second.first;
1595 I->second.first = 0;
1596 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnerdf986172009-01-02 07:01:27 +00001598 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1599 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1600 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001601 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001602 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 delete I->second.first;
1604 I->second.first = 0;
1605 }
1606}
1607
1608bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1609 if (!ForwardRefVals.empty())
1610 return P.Error(ForwardRefVals.begin()->second.second,
1611 "use of undefined value '%" + ForwardRefVals.begin()->first +
1612 "'");
1613 if (!ForwardRefValIDs.empty())
1614 return P.Error(ForwardRefValIDs.begin()->second.second,
1615 "use of undefined value '%" +
1616 utostr(ForwardRefValIDs.begin()->first) + "'");
1617 return false;
1618}
1619
1620
1621/// GetVal - Get a value with the specified name or ID, creating a
1622/// forward reference record if needed. This can return null if the value
1623/// exists but does not have the right type.
1624Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1625 const Type *Ty, LocTy Loc) {
1626 // Look this name up in the normal function symbol table.
1627 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 // If this is a forward reference for the value, see if we already created a
1630 // forward ref record.
1631 if (Val == 0) {
1632 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1633 I = ForwardRefVals.find(Name);
1634 if (I != ForwardRefVals.end())
1635 Val = I->second.first;
1636 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001637
Chris Lattnerdf986172009-01-02 07:01:27 +00001638 // If we have the value in the symbol table or fwd-ref table, return it.
1639 if (Val) {
1640 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001641 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001642 P.Error(Loc, "'%" + Name + "' is not a basic block");
1643 else
1644 P.Error(Loc, "'%" + Name + "' defined with type '" +
1645 Val->getType()->getDescription() + "'");
1646 return 0;
1647 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001648
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001650 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1651 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 P.Error(Loc, "invalid use of a non-first-class type");
1653 return 0;
1654 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnerdf986172009-01-02 07:01:27 +00001656 // Otherwise, create a new forward reference for this value and remember it.
1657 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001658 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001659 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001660 else
1661 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001662
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1664 return FwdVal;
1665}
1666
1667Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1668 LocTy Loc) {
1669 // Look this name up in the normal function symbol table.
1670 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671
Chris Lattnerdf986172009-01-02 07:01:27 +00001672 // If this is a forward reference for the value, see if we already created a
1673 // forward ref record.
1674 if (Val == 0) {
1675 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1676 I = ForwardRefValIDs.find(ID);
1677 if (I != ForwardRefValIDs.end())
1678 Val = I->second.first;
1679 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 // If we have the value in the symbol table or fwd-ref table, return it.
1682 if (Val) {
1683 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001684 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1686 else
1687 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1688 Val->getType()->getDescription() + "'");
1689 return 0;
1690 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691
Owen Anderson1d0be152009-08-13 21:58:54 +00001692 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1693 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001694 P.Error(Loc, "invalid use of a non-first-class type");
1695 return 0;
1696 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001697
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 // Otherwise, create a new forward reference for this value and remember it.
1699 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001700 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001701 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 else
1703 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001704
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1706 return FwdVal;
1707}
1708
1709/// SetInstName - After an instruction is parsed and inserted into its
1710/// basic block, this installs its name.
1711bool LLParser::PerFunctionState::SetInstName(int NameID,
1712 const std::string &NameStr,
1713 LocTy NameLoc, Instruction *Inst) {
1714 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001715 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001716 if (NameID != -1 || !NameStr.empty())
1717 return P.Error(NameLoc, "instructions returning void cannot have a name");
1718 return false;
1719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 // If this was a numbered instruction, verify that the instruction is the
1722 // expected value and resolve any forward references.
1723 if (NameStr.empty()) {
1724 // If neither a name nor an ID was specified, just use the next ID.
1725 if (NameID == -1)
1726 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001727
Chris Lattnerdf986172009-01-02 07:01:27 +00001728 if (unsigned(NameID) != NumberedVals.size())
1729 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1730 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001731
Chris Lattnerdf986172009-01-02 07:01:27 +00001732 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1733 ForwardRefValIDs.find(NameID);
1734 if (FI != ForwardRefValIDs.end()) {
1735 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001736 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001737 FI->second.first->getType()->getDescription() + "'");
1738 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001739 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001740 ForwardRefValIDs.erase(FI);
1741 }
1742
1743 NumberedVals.push_back(Inst);
1744 return false;
1745 }
1746
1747 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1748 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1749 FI = ForwardRefVals.find(NameStr);
1750 if (FI != ForwardRefVals.end()) {
1751 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001752 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 FI->second.first->getType()->getDescription() + "'");
1754 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001755 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001756 ForwardRefVals.erase(FI);
1757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001758
Chris Lattnerdf986172009-01-02 07:01:27 +00001759 // Set the name on the instruction.
1760 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001761
Chris Lattnerdf986172009-01-02 07:01:27 +00001762 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001763 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001764 NameStr + "'");
1765 return false;
1766}
1767
1768/// GetBB - Get a basic block with the specified name or ID, creating a
1769/// forward reference record if needed.
1770BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1771 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001772 return cast_or_null<BasicBlock>(GetVal(Name,
1773 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001774}
1775
1776BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001777 return cast_or_null<BasicBlock>(GetVal(ID,
1778 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001779}
1780
1781/// DefineBB - Define the specified basic block, which is either named or
1782/// unnamed. If there is an error, this returns null otherwise it returns
1783/// the block being defined.
1784BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1785 LocTy Loc) {
1786 BasicBlock *BB;
1787 if (Name.empty())
1788 BB = GetBB(NumberedVals.size(), Loc);
1789 else
1790 BB = GetBB(Name, Loc);
1791 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001792
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 // Move the block to the end of the function. Forward ref'd blocks are
1794 // inserted wherever they happen to be referenced.
1795 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001796
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 // Remove the block from forward ref sets.
1798 if (Name.empty()) {
1799 ForwardRefValIDs.erase(NumberedVals.size());
1800 NumberedVals.push_back(BB);
1801 } else {
1802 // BB forward references are already in the function symbol table.
1803 ForwardRefVals.erase(Name);
1804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001805
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 return BB;
1807}
1808
1809//===----------------------------------------------------------------------===//
1810// Constants.
1811//===----------------------------------------------------------------------===//
1812
1813/// ParseValID - Parse an abstract value that doesn't necessarily have a
1814/// type implied. For example, if we parse "4" we don't know what integer type
1815/// it has. The value will later be combined with its type and checked for
1816/// sanity.
1817bool LLParser::ParseValID(ValID &ID) {
1818 ID.Loc = Lex.getLoc();
1819 switch (Lex.getKind()) {
1820 default: return TokError("expected value token");
1821 case lltok::GlobalID: // @42
1822 ID.UIntVal = Lex.getUIntVal();
1823 ID.Kind = ValID::t_GlobalID;
1824 break;
1825 case lltok::GlobalVar: // @foo
1826 ID.StrVal = Lex.getStrVal();
1827 ID.Kind = ValID::t_GlobalName;
1828 break;
1829 case lltok::LocalVarID: // %42
1830 ID.UIntVal = Lex.getUIntVal();
1831 ID.Kind = ValID::t_LocalID;
1832 break;
1833 case lltok::LocalVar: // %foo
1834 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1835 ID.StrVal = Lex.getStrVal();
1836 ID.Kind = ValID::t_LocalName;
1837 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001838 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001839 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001840 Lex.Lex();
1841 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001842 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001843 if (ParseMDNodeVector(Elts) ||
1844 ParseToken(lltok::rbrace, "expected end of metadata node"))
1845 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001846
Owen Anderson647e3012009-07-31 21:35:40 +00001847 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001848 return false;
1849 }
1850
Devang Patel923078c2009-07-01 19:21:12 +00001851 // Standalone metadata reference
1852 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001853 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001854 return false;
Devang Patel256be962009-07-20 19:00:08 +00001855
Nick Lewycky21cc4462009-04-04 07:22:01 +00001856 // MDString:
1857 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001858 if (ParseMDString(ID.MetadataVal)) return true;
1859 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001860 return false;
1861 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001862 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 ID.Kind = ValID::t_APSInt;
1865 break;
1866 case lltok::APFloat:
1867 ID.APFloatVal = Lex.getAPFloatVal();
1868 ID.Kind = ValID::t_APFloat;
1869 break;
1870 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001871 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 ID.Kind = ValID::t_Constant;
1873 break;
1874 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001875 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 ID.Kind = ValID::t_Constant;
1877 break;
1878 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1879 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1880 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnerdf986172009-01-02 07:01:27 +00001882 case lltok::lbrace: {
1883 // ValID ::= '{' ConstVector '}'
1884 Lex.Lex();
1885 SmallVector<Constant*, 16> Elts;
1886 if (ParseGlobalValueVector(Elts) ||
1887 ParseToken(lltok::rbrace, "expected end of struct constant"))
1888 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001890 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1891 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 ID.Kind = ValID::t_Constant;
1893 return false;
1894 }
1895 case lltok::less: {
1896 // ValID ::= '<' ConstVector '>' --> Vector.
1897 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1898 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001899 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 SmallVector<Constant*, 16> Elts;
1902 LocTy FirstEltLoc = Lex.getLoc();
1903 if (ParseGlobalValueVector(Elts) ||
1904 (isPackedStruct &&
1905 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1906 ParseToken(lltok::greater, "expected end of constant"))
1907 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Chris Lattnerdf986172009-01-02 07:01:27 +00001909 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001910 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001911 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001912 ID.Kind = ValID::t_Constant;
1913 return false;
1914 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 if (Elts.empty())
1917 return Error(ID.Loc, "constant vector must not be empty");
1918
1919 if (!Elts[0]->getType()->isInteger() &&
1920 !Elts[0]->getType()->isFloatingPoint())
1921 return Error(FirstEltLoc,
1922 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001923
Chris Lattnerdf986172009-01-02 07:01:27 +00001924 // Verify that all the vector elements have the same type.
1925 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1926 if (Elts[i]->getType() != Elts[0]->getType())
1927 return Error(FirstEltLoc,
1928 "vector element #" + utostr(i) +
1929 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Owen Andersonaf7ec972009-07-28 21:19:26 +00001931 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001932 ID.Kind = ValID::t_Constant;
1933 return false;
1934 }
1935 case lltok::lsquare: { // Array Constant
1936 Lex.Lex();
1937 SmallVector<Constant*, 16> Elts;
1938 LocTy FirstEltLoc = Lex.getLoc();
1939 if (ParseGlobalValueVector(Elts) ||
1940 ParseToken(lltok::rsquare, "expected end of array constant"))
1941 return true;
1942
1943 // Handle empty element.
1944 if (Elts.empty()) {
1945 // Use undef instead of an array because it's inconvenient to determine
1946 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001947 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001948 return false;
1949 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001950
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00001953 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001954
Owen Andersondebcb012009-07-29 22:17:13 +00001955 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001956
Chris Lattnerdf986172009-01-02 07:01:27 +00001957 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001958 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 if (Elts[i]->getType() != Elts[0]->getType())
1960 return Error(FirstEltLoc,
1961 "array element #" + utostr(i) +
1962 " is not of type '" +Elts[0]->getType()->getDescription());
1963 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001964
Owen Anderson1fd70962009-07-28 18:32:17 +00001965 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 ID.Kind = ValID::t_Constant;
1967 return false;
1968 }
1969 case lltok::kw_c: // c "foo"
1970 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001971 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1973 ID.Kind = ValID::t_Constant;
1974 return false;
1975
1976 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001977 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
1978 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 Lex.Lex();
1980 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001981 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001982 ParseStringConstant(ID.StrVal) ||
1983 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 ParseToken(lltok::StringConstant, "expected constraint string"))
1985 return true;
1986 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001987 ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001988 ID.Kind = ValID::t_InlineAsm;
1989 return false;
1990 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001991
Chris Lattnerdf986172009-01-02 07:01:27 +00001992 case lltok::kw_trunc:
1993 case lltok::kw_zext:
1994 case lltok::kw_sext:
1995 case lltok::kw_fptrunc:
1996 case lltok::kw_fpext:
1997 case lltok::kw_bitcast:
1998 case lltok::kw_uitofp:
1999 case lltok::kw_sitofp:
2000 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002001 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002003 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002004 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002005 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002006 Constant *SrcVal;
2007 Lex.Lex();
2008 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2009 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002010 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 ParseType(DestTy) ||
2012 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2013 return true;
2014 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2015 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2016 SrcVal->getType()->getDescription() + "' to '" +
2017 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002018 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002019 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002020 ID.Kind = ValID::t_Constant;
2021 return false;
2022 }
2023 case lltok::kw_extractvalue: {
2024 Lex.Lex();
2025 Constant *Val;
2026 SmallVector<unsigned, 4> Indices;
2027 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2028 ParseGlobalTypeAndValue(Val) ||
2029 ParseIndexList(Indices) ||
2030 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2031 return true;
2032 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2033 return Error(ID.Loc, "extractvalue operand must be array or struct");
2034 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2035 Indices.end()))
2036 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002037 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002038 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_Constant;
2040 return false;
2041 }
2042 case lltok::kw_insertvalue: {
2043 Lex.Lex();
2044 Constant *Val0, *Val1;
2045 SmallVector<unsigned, 4> Indices;
2046 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2047 ParseGlobalTypeAndValue(Val0) ||
2048 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2049 ParseGlobalTypeAndValue(Val1) ||
2050 ParseIndexList(Indices) ||
2051 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2052 return true;
2053 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2054 return Error(ID.Loc, "extractvalue operand must be array or struct");
2055 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2056 Indices.end()))
2057 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002058 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002059 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 ID.Kind = ValID::t_Constant;
2061 return false;
2062 }
2063 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002064 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 unsigned PredVal, Opc = Lex.getUIntVal();
2066 Constant *Val0, *Val1;
2067 Lex.Lex();
2068 if (ParseCmpPredicate(PredVal, Opc) ||
2069 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2070 ParseGlobalTypeAndValue(Val0) ||
2071 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2072 ParseGlobalTypeAndValue(Val1) ||
2073 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2074 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002075
Chris Lattnerdf986172009-01-02 07:01:27 +00002076 if (Val0->getType() != Val1->getType())
2077 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002078
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 if (Opc == Instruction::FCmp) {
2082 if (!Val0->getType()->isFPOrFPVector())
2083 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002084 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002085 } else {
2086 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002087 if (!Val0->getType()->isIntOrIntVector() &&
2088 !isa<PointerType>(Val0->getType()))
2089 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002090 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 }
2092 ID.Kind = ValID::t_Constant;
2093 return false;
2094 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 // Binary Operators.
2097 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002098 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002099 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002100 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002102 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 case lltok::kw_udiv:
2104 case lltok::kw_sdiv:
2105 case lltok::kw_fdiv:
2106 case lltok::kw_urem:
2107 case lltok::kw_srem:
2108 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002109 bool NUW = false;
2110 bool NSW = false;
2111 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002112 unsigned Opc = Lex.getUIntVal();
2113 Constant *Val0, *Val1;
2114 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002115 LocTy ModifierLoc = Lex.getLoc();
2116 if (Opc == Instruction::Add ||
2117 Opc == Instruction::Sub ||
2118 Opc == Instruction::Mul) {
2119 if (EatIfPresent(lltok::kw_nuw))
2120 NUW = true;
2121 if (EatIfPresent(lltok::kw_nsw)) {
2122 NSW = true;
2123 if (EatIfPresent(lltok::kw_nuw))
2124 NUW = true;
2125 }
2126 } else if (Opc == Instruction::SDiv) {
2127 if (EatIfPresent(lltok::kw_exact))
2128 Exact = true;
2129 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002130 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2131 ParseGlobalTypeAndValue(Val0) ||
2132 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2133 ParseGlobalTypeAndValue(Val1) ||
2134 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2135 return true;
2136 if (Val0->getType() != Val1->getType())
2137 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002138 if (!Val0->getType()->isIntOrIntVector()) {
2139 if (NUW)
2140 return Error(ModifierLoc, "nuw only applies to integer operations");
2141 if (NSW)
2142 return Error(ModifierLoc, "nsw only applies to integer operations");
2143 }
2144 // API compatibility: Accept either integer or floating-point types with
2145 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002146 if (!Val0->getType()->isIntOrIntVector() &&
2147 !Val0->getType()->isFPOrFPVector())
2148 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002149 unsigned Flags = 0;
2150 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2151 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2152 if (Exact) Flags |= SDivOperator::IsExact;
2153 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002154 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002155 ID.Kind = ValID::t_Constant;
2156 return false;
2157 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002158
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 // Logical Operations
2160 case lltok::kw_shl:
2161 case lltok::kw_lshr:
2162 case lltok::kw_ashr:
2163 case lltok::kw_and:
2164 case lltok::kw_or:
2165 case lltok::kw_xor: {
2166 unsigned Opc = Lex.getUIntVal();
2167 Constant *Val0, *Val1;
2168 Lex.Lex();
2169 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2170 ParseGlobalTypeAndValue(Val0) ||
2171 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2172 ParseGlobalTypeAndValue(Val1) ||
2173 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2174 return true;
2175 if (Val0->getType() != Val1->getType())
2176 return Error(ID.Loc, "operands of constexpr must have same type");
2177 if (!Val0->getType()->isIntOrIntVector())
2178 return Error(ID.Loc,
2179 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 ID.Kind = ValID::t_Constant;
2182 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002183 }
2184
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 case lltok::kw_getelementptr:
2186 case lltok::kw_shufflevector:
2187 case lltok::kw_insertelement:
2188 case lltok::kw_extractelement:
2189 case lltok::kw_select: {
2190 unsigned Opc = Lex.getUIntVal();
2191 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002192 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002193 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002194 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002195 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002196 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2197 ParseGlobalValueVector(Elts) ||
2198 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2199 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002200
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 if (Opc == Instruction::GetElementPtr) {
2202 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2203 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002204
Chris Lattnerdf986172009-01-02 07:01:27 +00002205 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002206 (Value**)(Elts.data() + 1),
2207 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002209 ID.ConstantVal = InBounds ?
2210 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2211 Elts.data() + 1,
2212 Elts.size() - 1) :
2213 ConstantExpr::getGetElementPtr(Elts[0],
2214 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 } else if (Opc == Instruction::Select) {
2216 if (Elts.size() != 3)
2217 return Error(ID.Loc, "expected three operands to select");
2218 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2219 Elts[2]))
2220 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002221 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 } else if (Opc == Instruction::ShuffleVector) {
2223 if (Elts.size() != 3)
2224 return Error(ID.Loc, "expected three operands to shufflevector");
2225 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2226 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002227 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002228 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 } else if (Opc == Instruction::ExtractElement) {
2230 if (Elts.size() != 2)
2231 return Error(ID.Loc, "expected two operands to extractelement");
2232 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2233 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002234 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 } else {
2236 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2237 if (Elts.size() != 3)
2238 return Error(ID.Loc, "expected three operands to insertelement");
2239 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2240 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002241 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002242 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002243 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002244
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 ID.Kind = ValID::t_Constant;
2246 return false;
2247 }
2248 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 Lex.Lex();
2251 return false;
2252}
2253
2254/// ParseGlobalValue - Parse a global value with the specified type.
2255bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2256 V = 0;
2257 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002258 return ParseValID(ID) ||
2259 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002260}
2261
2262/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2263/// constant.
2264bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2265 Constant *&V) {
2266 if (isa<FunctionType>(Ty))
2267 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002268
Chris Lattnerdf986172009-01-02 07:01:27 +00002269 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002270 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002271 case ValID::t_Metadata:
2272 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002273 case ValID::t_LocalID:
2274 case ValID::t_LocalName:
2275 return Error(ID.Loc, "invalid use of function-local name");
2276 case ValID::t_InlineAsm:
2277 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2278 case ValID::t_GlobalName:
2279 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2280 return V == 0;
2281 case ValID::t_GlobalID:
2282 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2283 return V == 0;
2284 case ValID::t_APSInt:
2285 if (!isa<IntegerType>(Ty))
2286 return Error(ID.Loc, "integer constant must have integer type");
2287 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002288 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002289 return false;
2290 case ValID::t_APFloat:
2291 if (!Ty->isFloatingPoint() ||
2292 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2293 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002294
Chris Lattnerdf986172009-01-02 07:01:27 +00002295 // The lexer has no type info, so builds all float and double FP constants
2296 // as double. Fix this here. Long double does not need this.
2297 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002298 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 bool Ignored;
2300 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2301 &Ignored);
2302 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002303 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002304
Chris Lattner959873d2009-01-05 18:24:23 +00002305 if (V->getType() != Ty)
2306 return Error(ID.Loc, "floating point constant does not have type '" +
2307 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002308
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 return false;
2310 case ValID::t_Null:
2311 if (!isa<PointerType>(Ty))
2312 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002313 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 return false;
2315 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002316 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002317 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002318 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002319 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002320 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002322 case ValID::t_EmptyArray:
2323 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2324 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002325 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002326 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002328 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002329 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002330 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002331 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002332 return false;
2333 case ValID::t_Constant:
2334 if (ID.ConstantVal->getType() != Ty)
2335 return Error(ID.Loc, "constant expression type mismatch");
2336 V = ID.ConstantVal;
2337 return false;
2338 }
2339}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002340
Chris Lattnerdf986172009-01-02 07:01:27 +00002341bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002342 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002343 return ParseType(Type) ||
2344 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345}
Chris Lattnerdf986172009-01-02 07:01:27 +00002346
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002347/// ParseGlobalValueVector
2348/// ::= /*empty*/
2349/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002350bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2351 // Empty list.
2352 if (Lex.getKind() == lltok::rbrace ||
2353 Lex.getKind() == lltok::rsquare ||
2354 Lex.getKind() == lltok::greater ||
2355 Lex.getKind() == lltok::rparen)
2356 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002357
Chris Lattnerdf986172009-01-02 07:01:27 +00002358 Constant *C;
2359 if (ParseGlobalTypeAndValue(C)) return true;
2360 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002362 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002363 if (ParseGlobalTypeAndValue(C)) return true;
2364 Elts.push_back(C);
2365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002366
Chris Lattnerdf986172009-01-02 07:01:27 +00002367 return false;
2368}
2369
2370
2371//===----------------------------------------------------------------------===//
2372// Function Parsing.
2373//===----------------------------------------------------------------------===//
2374
2375bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2376 PerFunctionState &PFS) {
2377 if (ID.Kind == ValID::t_LocalID)
2378 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2379 else if (ID.Kind == ValID::t_LocalName)
2380 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002381 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002382 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2383 const FunctionType *FTy =
2384 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2385 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2386 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002387 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002389 } else if (ID.Kind == ValID::t_Metadata) {
2390 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 } else {
2392 Constant *C;
2393 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2394 V = C;
2395 return false;
2396 }
2397
2398 return V == 0;
2399}
2400
2401bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2402 V = 0;
2403 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002404 return ParseValID(ID) ||
2405 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002406}
2407
2408bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002409 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002410 return ParseType(T) ||
2411 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002412}
2413
2414/// FunctionHeader
2415/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2416/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2417/// OptionalAlign OptGC
2418bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2419 // Parse the linkage.
2420 LocTy LinkageLoc = Lex.getLoc();
2421 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002422
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002423 unsigned Visibility, RetAttrs;
2424 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002425 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002426 LocTy RetTypeLoc = Lex.getLoc();
2427 if (ParseOptionalLinkage(Linkage) ||
2428 ParseOptionalVisibility(Visibility) ||
2429 ParseOptionalCallingConv(CC) ||
2430 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002431 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002432 return true;
2433
2434 // Verify that the linkage is ok.
2435 switch ((GlobalValue::LinkageTypes)Linkage) {
2436 case GlobalValue::ExternalLinkage:
2437 break; // always ok.
2438 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002439 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 if (isDefine)
2441 return Error(LinkageLoc, "invalid linkage for function definition");
2442 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002443 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002444 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002446 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002447 case GlobalValue::LinkOnceAnyLinkage:
2448 case GlobalValue::LinkOnceODRLinkage:
2449 case GlobalValue::WeakAnyLinkage:
2450 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 case GlobalValue::DLLExportLinkage:
2452 if (!isDefine)
2453 return Error(LinkageLoc, "invalid linkage for function declaration");
2454 break;
2455 case GlobalValue::AppendingLinkage:
2456 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002457 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 return Error(LinkageLoc, "invalid function linkage type");
2459 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002460
Chris Lattner99bb3152009-01-05 08:00:30 +00002461 if (!FunctionType::isValidReturnType(RetType) ||
2462 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002464
Chris Lattnerdf986172009-01-02 07:01:27 +00002465 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002466
2467 std::string FunctionName;
2468 if (Lex.getKind() == lltok::GlobalVar) {
2469 FunctionName = Lex.getStrVal();
2470 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2471 unsigned NameID = Lex.getUIntVal();
2472
2473 if (NameID != NumberedVals.size())
2474 return TokError("function expected to be numbered '%" +
2475 utostr(NumberedVals.size()) + "'");
2476 } else {
2477 return TokError("expected function name");
2478 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002479
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002480 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002481
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002482 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002483 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002484
Chris Lattnerdf986172009-01-02 07:01:27 +00002485 std::vector<ArgInfo> ArgList;
2486 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002487 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002490 std::string GC;
2491
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002492 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002493 ParseOptionalAttrs(FuncAttrs, 2) ||
2494 (EatIfPresent(lltok::kw_section) &&
2495 ParseStringConstant(Section)) ||
2496 ParseOptionalAlignment(Alignment) ||
2497 (EatIfPresent(lltok::kw_gc) &&
2498 ParseStringConstant(GC)))
2499 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002500
2501 // If the alignment was parsed as an attribute, move to the alignment field.
2502 if (FuncAttrs & Attribute::Alignment) {
2503 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2504 FuncAttrs &= ~Attribute::Alignment;
2505 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506
Chris Lattnerdf986172009-01-02 07:01:27 +00002507 // Okay, if we got here, the function is syntactically valid. Convert types
2508 // and do semantic checks.
2509 std::vector<const Type*> ParamTypeList;
2510 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002511 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002512 // attributes.
2513 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2514 if (FuncAttrs & ObsoleteFuncAttrs) {
2515 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2516 FuncAttrs &= ~ObsoleteFuncAttrs;
2517 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002518
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 if (RetAttrs != Attribute::None)
2520 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002521
Chris Lattnerdf986172009-01-02 07:01:27 +00002522 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2523 ParamTypeList.push_back(ArgList[i].Type);
2524 if (ArgList[i].Attrs != Attribute::None)
2525 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2526 }
2527
2528 if (FuncAttrs != Attribute::None)
2529 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2530
2531 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002532
Chris Lattnera9a9e072009-03-09 04:49:14 +00002533 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002534 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002535 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2536
Owen Andersonfba933c2009-07-01 23:57:11 +00002537 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002538 FunctionType::get(RetType, ParamTypeList, isVarArg);
2539 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002540
2541 Fn = 0;
2542 if (!FunctionName.empty()) {
2543 // If this was a definition of a forward reference, remove the definition
2544 // from the forward reference table and fill in the forward ref.
2545 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2546 ForwardRefVals.find(FunctionName);
2547 if (FRVI != ForwardRefVals.end()) {
2548 Fn = M->getFunction(FunctionName);
2549 ForwardRefVals.erase(FRVI);
2550 } else if ((Fn = M->getFunction(FunctionName))) {
2551 // If this function already exists in the symbol table, then it is
2552 // multiply defined. We accept a few cases for old backwards compat.
2553 // FIXME: Remove this stuff for LLVM 3.0.
2554 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2555 (!Fn->isDeclaration() && isDefine)) {
2556 // If the redefinition has different type or different attributes,
2557 // reject it. If both have bodies, reject it.
2558 return Error(NameLoc, "invalid redefinition of function '" +
2559 FunctionName + "'");
2560 } else if (Fn->isDeclaration()) {
2561 // Make sure to strip off any argument names so we can't get conflicts.
2562 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2563 AI != AE; ++AI)
2564 AI->setName("");
2565 }
2566 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002567
Dan Gohman41905542009-08-29 23:37:49 +00002568 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 // If this is a definition of a forward referenced function, make sure the
2570 // types agree.
2571 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2572 = ForwardRefValIDs.find(NumberedVals.size());
2573 if (I != ForwardRefValIDs.end()) {
2574 Fn = cast<Function>(I->second.first);
2575 if (Fn->getType() != PFT)
2576 return Error(NameLoc, "type of definition and forward reference of '@" +
2577 utostr(NumberedVals.size()) +"' disagree");
2578 ForwardRefValIDs.erase(I);
2579 }
2580 }
2581
2582 if (Fn == 0)
2583 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2584 else // Move the forward-reference to the correct spot in the module.
2585 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2586
2587 if (FunctionName.empty())
2588 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2591 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2592 Fn->setCallingConv(CC);
2593 Fn->setAttributes(PAL);
2594 Fn->setAlignment(Alignment);
2595 Fn->setSection(Section);
2596 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002597
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 // Add all of the arguments we parsed to the function.
2599 Function::arg_iterator ArgIt = Fn->arg_begin();
2600 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2601 // If the argument has a name, insert it into the argument symbol table.
2602 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002603
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 // Set the name, if it conflicted, it will be auto-renamed.
2605 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002606
Chris Lattnerdf986172009-01-02 07:01:27 +00002607 if (ArgIt->getNameStr() != ArgList[i].Name)
2608 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2609 ArgList[i].Name + "'");
2610 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 return false;
2613}
2614
2615
2616/// ParseFunctionBody
2617/// ::= '{' BasicBlock+ '}'
2618/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2619///
2620bool LLParser::ParseFunctionBody(Function &Fn) {
2621 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2622 return TokError("expected '{' in function body");
2623 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002624
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 PerFunctionState PFS(*this, Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2628 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 // Eat the }.
2631 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 // Verify function is ok.
2634 return PFS.VerifyFunctionComplete();
2635}
2636
2637/// ParseBasicBlock
2638/// ::= LabelStr? Instruction*
2639bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2640 // If this basic block starts out with a name, remember it.
2641 std::string Name;
2642 LocTy NameLoc = Lex.getLoc();
2643 if (Lex.getKind() == lltok::LabelStr) {
2644 Name = Lex.getStrVal();
2645 Lex.Lex();
2646 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2649 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002650
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002652
Chris Lattnerdf986172009-01-02 07:01:27 +00002653 // Parse the instructions in this block until we get a terminator.
2654 Instruction *Inst;
2655 do {
2656 // This instruction may have three possibilities for a name: a) none
2657 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2658 LocTy NameLoc = Lex.getLoc();
2659 int NameID = -1;
2660 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002661
Chris Lattnerdf986172009-01-02 07:01:27 +00002662 if (Lex.getKind() == lltok::LocalVarID) {
2663 NameID = Lex.getUIntVal();
2664 Lex.Lex();
2665 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2666 return true;
2667 } else if (Lex.getKind() == lltok::LocalVar ||
2668 // FIXME: REMOVE IN LLVM 3.0
2669 Lex.getKind() == lltok::StringConstant) {
2670 NameStr = Lex.getStrVal();
2671 Lex.Lex();
2672 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2673 return true;
2674 }
Devang Patelf633a062009-09-17 23:04:48 +00002675
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002677 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002678 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002679
2680 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002681 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002682 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002684 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002685 MDsOnInst.clear();
2686
Chris Lattnerdf986172009-01-02 07:01:27 +00002687 BB->getInstList().push_back(Inst);
2688
2689 // Set the name on the instruction.
2690 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2691 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002692
Chris Lattnerdf986172009-01-02 07:01:27 +00002693 return false;
2694}
2695
2696//===----------------------------------------------------------------------===//
2697// Instruction Parsing.
2698//===----------------------------------------------------------------------===//
2699
2700/// ParseInstruction - Parse one of the many different instructions.
2701///
2702bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2703 PerFunctionState &PFS) {
2704 lltok::Kind Token = Lex.getKind();
2705 if (Token == lltok::Eof)
2706 return TokError("found end of file when expecting more instructions");
2707 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002708 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002709 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002710
Chris Lattnerdf986172009-01-02 07:01:27 +00002711 switch (Token) {
2712 default: return Error(Loc, "expected instruction opcode");
2713 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002714 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2715 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002716 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2717 case lltok::kw_br: return ParseBr(Inst, PFS);
2718 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2719 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2720 // Binary Operators.
2721 case lltok::kw_add:
2722 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002723 case lltok::kw_mul: {
2724 bool NUW = false;
2725 bool NSW = false;
2726 LocTy ModifierLoc = Lex.getLoc();
2727 if (EatIfPresent(lltok::kw_nuw))
2728 NUW = true;
2729 if (EatIfPresent(lltok::kw_nsw)) {
2730 NSW = true;
2731 if (EatIfPresent(lltok::kw_nuw))
2732 NUW = true;
2733 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002734 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002735 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2736 if (!Result) {
2737 if (!Inst->getType()->isIntOrIntVector()) {
2738 if (NUW)
2739 return Error(ModifierLoc, "nuw only applies to integer operations");
2740 if (NSW)
2741 return Error(ModifierLoc, "nsw only applies to integer operations");
2742 }
2743 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002744 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002745 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002746 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002747 }
2748 return Result;
2749 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002750 case lltok::kw_fadd:
2751 case lltok::kw_fsub:
2752 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2753
Dan Gohman59858cf2009-07-27 16:11:46 +00002754 case lltok::kw_sdiv: {
2755 bool Exact = false;
2756 if (EatIfPresent(lltok::kw_exact))
2757 Exact = true;
2758 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2759 if (!Result)
2760 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002761 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002762 return Result;
2763 }
2764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002767 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002768 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002769 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 case lltok::kw_shl:
2771 case lltok::kw_lshr:
2772 case lltok::kw_ashr:
2773 case lltok::kw_and:
2774 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002775 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002777 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002778 // Casts.
2779 case lltok::kw_trunc:
2780 case lltok::kw_zext:
2781 case lltok::kw_sext:
2782 case lltok::kw_fptrunc:
2783 case lltok::kw_fpext:
2784 case lltok::kw_bitcast:
2785 case lltok::kw_uitofp:
2786 case lltok::kw_sitofp:
2787 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002790 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002791 // Other.
2792 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002793 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2795 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2796 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2797 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2798 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2799 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2800 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002801 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2802 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002803 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002804 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2805 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2806 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002807 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002809 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002811 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2814 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2815 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2816 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2817 }
2818}
2819
2820/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2821bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002822 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002823 switch (Lex.getKind()) {
2824 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2825 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2826 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2827 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2828 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2829 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2830 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2831 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2832 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2833 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2834 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2835 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2836 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2837 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2838 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2839 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2840 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2841 }
2842 } else {
2843 switch (Lex.getKind()) {
2844 default: TokError("expected icmp predicate (e.g. 'eq')");
2845 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2846 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2847 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2848 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2849 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2850 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2851 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2852 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2853 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2854 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2855 }
2856 }
2857 Lex.Lex();
2858 return false;
2859}
2860
2861//===----------------------------------------------------------------------===//
2862// Terminator Instructions.
2863//===----------------------------------------------------------------------===//
2864
2865/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002866/// ::= 'ret' void (',' !dbg, !1)
2867/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2868/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002869/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002870bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2871 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002872 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002873 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002874
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002875 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002876 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002877 return false;
2878 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 Value *RV;
2881 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002882
Devang Patelf633a062009-09-17 23:04:48 +00002883 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002884 // Parse optional custom metadata, e.g. !dbg
2885 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2886 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002887 } else {
2888 // The normal case is one return value.
2889 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2890 // of 'ret {i32,i32} {i32 1, i32 2}'
2891 SmallVector<Value*, 8> RVs;
2892 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002893
Devang Patelf633a062009-09-17 23:04:48 +00002894 do {
Devang Patel0475c912009-09-29 00:01:14 +00002895 // If optional custom metadata, e.g. !dbg is seen then this is the
2896 // end of MRV.
2897 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002898 break;
2899 if (ParseTypeAndValue(RV, PFS)) return true;
2900 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00002901 } while (EatIfPresent(lltok::comma));
2902
2903 RV = UndefValue::get(PFS.getFunction().getReturnType());
2904 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2906 BB->getInstList().push_back(I);
2907 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00002908 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002909 }
2910 }
Devang Patelf633a062009-09-17 23:04:48 +00002911
Owen Anderson1d0be152009-08-13 21:58:54 +00002912 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002913 return false;
2914}
2915
2916
2917/// ParseBr
2918/// ::= 'br' TypeAndValue
2919/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2920bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2921 LocTy Loc, Loc2;
2922 Value *Op0, *Op1, *Op2;
2923 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2926 Inst = BranchInst::Create(BB);
2927 return false;
2928 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002929
Owen Anderson1d0be152009-08-13 21:58:54 +00002930 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002931 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattnerdf986172009-01-02 07:01:27 +00002933 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2934 ParseTypeAndValue(Op1, Loc, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after true destination") ||
2936 ParseTypeAndValue(Op2, Loc2, PFS))
2937 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002938
Chris Lattnerdf986172009-01-02 07:01:27 +00002939 if (!isa<BasicBlock>(Op1))
2940 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002941 if (!isa<BasicBlock>(Op2))
2942 return Error(Loc2, "true destination of branch must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002943
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2945 return false;
2946}
2947
2948/// ParseSwitch
2949/// Instruction
2950/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2951/// JumpTable
2952/// ::= (TypeAndValue ',' TypeAndValue)*
2953bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2954 LocTy CondLoc, BBLoc;
2955 Value *Cond, *DefaultBB;
2956 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2957 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2958 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2959 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2960 return true;
2961
2962 if (!isa<IntegerType>(Cond->getType()))
2963 return Error(CondLoc, "switch condition must have integer type");
2964 if (!isa<BasicBlock>(DefaultBB))
2965 return Error(BBLoc, "default destination must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002966
Chris Lattnerdf986172009-01-02 07:01:27 +00002967 // Parse the jump table pairs.
2968 SmallPtrSet<Value*, 32> SeenCases;
2969 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2970 while (Lex.getKind() != lltok::rsquare) {
2971 Value *Constant, *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002972
Chris Lattnerdf986172009-01-02 07:01:27 +00002973 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2974 ParseToken(lltok::comma, "expected ',' after case value") ||
2975 ParseTypeAndValue(DestBB, BBLoc, PFS))
2976 return true;
2977
2978 if (!SeenCases.insert(Constant))
2979 return Error(CondLoc, "duplicate case value in switch");
2980 if (!isa<ConstantInt>(Constant))
2981 return Error(CondLoc, "case value is not a constant integer");
2982 if (!isa<BasicBlock>(DestBB))
2983 return Error(BBLoc, "case destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2986 cast<BasicBlock>(DestBB)));
2987 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002988
Chris Lattnerdf986172009-01-02 07:01:27 +00002989 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002990
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2992 Table.size());
2993 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2994 SI->addCase(Table[i].first, Table[i].second);
2995 Inst = SI;
2996 return false;
2997}
2998
2999/// ParseInvoke
3000/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3001/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3002bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3003 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003004 unsigned RetAttrs, FnAttrs;
3005 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003006 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 LocTy RetTypeLoc;
3008 ValID CalleeID;
3009 SmallVector<ParamInfo, 16> ArgList;
3010
3011 Value *NormalBB, *UnwindBB;
3012 if (ParseOptionalCallingConv(CC) ||
3013 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003014 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 ParseValID(CalleeID) ||
3016 ParseParameterList(ArgList, PFS) ||
3017 ParseOptionalAttrs(FnAttrs, 2) ||
3018 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3019 ParseTypeAndValue(NormalBB, PFS) ||
3020 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3021 ParseTypeAndValue(UnwindBB, PFS))
3022 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003023
Chris Lattnerdf986172009-01-02 07:01:27 +00003024 if (!isa<BasicBlock>(NormalBB))
3025 return Error(CallLoc, "normal destination is not a basic block");
3026 if (!isa<BasicBlock>(UnwindBB))
3027 return Error(CallLoc, "unwind destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003028
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 // If RetType is a non-function pointer type, then this is the short syntax
3030 // for the call, which means that RetType is just the return type. Infer the
3031 // rest of the function argument types from the arguments that are present.
3032 const PointerType *PFTy = 0;
3033 const FunctionType *Ty = 0;
3034 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3035 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3036 // Pull out the types of all of the arguments...
3037 std::vector<const Type*> ParamTypes;
3038 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3039 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003040
Chris Lattnerdf986172009-01-02 07:01:27 +00003041 if (!FunctionType::isValidReturnType(RetType))
3042 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003043
Owen Andersondebcb012009-07-29 22:17:13 +00003044 Ty = FunctionType::get(RetType, ParamTypes, false);
3045 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 // Look up the callee.
3049 Value *Callee;
3050 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003051
Chris Lattnerdf986172009-01-02 07:01:27 +00003052 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3053 // function attributes.
3054 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3055 if (FnAttrs & ObsoleteFuncAttrs) {
3056 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3057 FnAttrs &= ~ObsoleteFuncAttrs;
3058 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003059
Chris Lattnerdf986172009-01-02 07:01:27 +00003060 // Set up the Attributes for the function.
3061 SmallVector<AttributeWithIndex, 8> Attrs;
3062 if (RetAttrs != Attribute::None)
3063 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003064
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003066
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 // Loop through FunctionType's arguments and ensure they are specified
3068 // correctly. Also, gather any parameter attributes.
3069 FunctionType::param_iterator I = Ty->param_begin();
3070 FunctionType::param_iterator E = Ty->param_end();
3071 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3072 const Type *ExpectedTy = 0;
3073 if (I != E) {
3074 ExpectedTy = *I++;
3075 } else if (!Ty->isVarArg()) {
3076 return Error(ArgList[i].Loc, "too many arguments specified");
3077 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003078
Chris Lattnerdf986172009-01-02 07:01:27 +00003079 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3080 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3081 ExpectedTy->getDescription() + "'");
3082 Args.push_back(ArgList[i].V);
3083 if (ArgList[i].Attrs != Attribute::None)
3084 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003086
Chris Lattnerdf986172009-01-02 07:01:27 +00003087 if (I != E)
3088 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 if (FnAttrs != Attribute::None)
3091 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003092
Chris Lattnerdf986172009-01-02 07:01:27 +00003093 // Finish off the Attributes and check them
3094 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3097 cast<BasicBlock>(UnwindBB),
3098 Args.begin(), Args.end());
3099 II->setCallingConv(CC);
3100 II->setAttributes(PAL);
3101 Inst = II;
3102 return false;
3103}
3104
3105
3106
3107//===----------------------------------------------------------------------===//
3108// Binary Operators.
3109//===----------------------------------------------------------------------===//
3110
3111/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003112/// ::= ArithmeticOps TypeAndValue ',' Value
3113///
3114/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3115/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003116bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003117 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 LocTy Loc; Value *LHS, *RHS;
3119 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3121 ParseValue(LHS->getType(), RHS, PFS))
3122 return true;
3123
Chris Lattnere914b592009-01-05 08:24:46 +00003124 bool Valid;
3125 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003126 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003127 case 0: // int or FP.
3128 Valid = LHS->getType()->isIntOrIntVector() ||
3129 LHS->getType()->isFPOrFPVector();
3130 break;
3131 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3132 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3133 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003134
Chris Lattnere914b592009-01-05 08:24:46 +00003135 if (!Valid)
3136 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003137
Chris Lattnerdf986172009-01-02 07:01:27 +00003138 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3139 return false;
3140}
3141
3142/// ParseLogical
3143/// ::= ArithmeticOps TypeAndValue ',' Value {
3144bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3145 unsigned Opc) {
3146 LocTy Loc; Value *LHS, *RHS;
3147 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3148 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3149 ParseValue(LHS->getType(), RHS, PFS))
3150 return true;
3151
3152 if (!LHS->getType()->isIntOrIntVector())
3153 return Error(Loc,"instruction requires integer or integer vector operands");
3154
3155 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3156 return false;
3157}
3158
3159
3160/// ParseCompare
3161/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3162/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003163bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3164 unsigned Opc) {
3165 // Parse the integer/fp comparison predicate.
3166 LocTy Loc;
3167 unsigned Pred;
3168 Value *LHS, *RHS;
3169 if (ParseCmpPredicate(Pred, Opc) ||
3170 ParseTypeAndValue(LHS, Loc, PFS) ||
3171 ParseToken(lltok::comma, "expected ',' after compare value") ||
3172 ParseValue(LHS->getType(), RHS, PFS))
3173 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003174
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 if (Opc == Instruction::FCmp) {
3176 if (!LHS->getType()->isFPOrFPVector())
3177 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003178 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003179 } else {
3180 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003181 if (!LHS->getType()->isIntOrIntVector() &&
3182 !isa<PointerType>(LHS->getType()))
3183 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003184 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 }
3186 return false;
3187}
3188
3189//===----------------------------------------------------------------------===//
3190// Other Instructions.
3191//===----------------------------------------------------------------------===//
3192
3193
3194/// ParseCast
3195/// ::= CastOpc TypeAndValue 'to' Type
3196bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3197 unsigned Opc) {
3198 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003199 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003200 if (ParseTypeAndValue(Op, Loc, PFS) ||
3201 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3202 ParseType(DestTy))
3203 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003205 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3206 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 return Error(Loc, "invalid cast opcode for cast from '" +
3208 Op->getType()->getDescription() + "' to '" +
3209 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003210 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3212 return false;
3213}
3214
3215/// ParseSelect
3216/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3217bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3218 LocTy Loc;
3219 Value *Op0, *Op1, *Op2;
3220 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3221 ParseToken(lltok::comma, "expected ',' after select condition") ||
3222 ParseTypeAndValue(Op1, PFS) ||
3223 ParseToken(lltok::comma, "expected ',' after select value") ||
3224 ParseTypeAndValue(Op2, PFS))
3225 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3228 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003229
Chris Lattnerdf986172009-01-02 07:01:27 +00003230 Inst = SelectInst::Create(Op0, Op1, Op2);
3231 return false;
3232}
3233
Chris Lattner0088a5c2009-01-05 08:18:44 +00003234/// ParseVA_Arg
3235/// ::= 'va_arg' TypeAndValue ',' Type
3236bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003238 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003239 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 if (ParseTypeAndValue(Op, PFS) ||
3241 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003242 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003244
Chris Lattner0088a5c2009-01-05 08:18:44 +00003245 if (!EltTy->isFirstClassType())
3246 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003247
3248 Inst = new VAArgInst(Op, EltTy);
3249 return false;
3250}
3251
3252/// ParseExtractElement
3253/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3254bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3255 LocTy Loc;
3256 Value *Op0, *Op1;
3257 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3258 ParseToken(lltok::comma, "expected ',' after extract value") ||
3259 ParseTypeAndValue(Op1, PFS))
3260 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003261
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3263 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003264
Eric Christophera3500da2009-07-25 02:28:41 +00003265 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003266 return false;
3267}
3268
3269/// ParseInsertElement
3270/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3271bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3272 LocTy Loc;
3273 Value *Op0, *Op1, *Op2;
3274 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3275 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3276 ParseTypeAndValue(Op1, PFS) ||
3277 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3278 ParseTypeAndValue(Op2, PFS))
3279 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003280
Chris Lattnerdf986172009-01-02 07:01:27 +00003281 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003282 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003283
Chris Lattnerdf986172009-01-02 07:01:27 +00003284 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3285 return false;
3286}
3287
3288/// ParseShuffleVector
3289/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3290bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3291 LocTy Loc;
3292 Value *Op0, *Op1, *Op2;
3293 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3294 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3295 ParseTypeAndValue(Op1, PFS) ||
3296 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3297 ParseTypeAndValue(Op2, PFS))
3298 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003299
Chris Lattnerdf986172009-01-02 07:01:27 +00003300 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3301 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3304 return false;
3305}
3306
3307/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003308/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003309bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003310 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 Value *Op0, *Op1;
3312 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003313
Chris Lattnerdf986172009-01-02 07:01:27 +00003314 if (ParseType(Ty) ||
3315 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3316 ParseValue(Ty, Op0, PFS) ||
3317 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003318 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3320 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003321
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3323 while (1) {
3324 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003325
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003326 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 break;
3328
Devang Patela43d46f2009-10-16 18:45:49 +00003329 if (Lex.getKind() == lltok::NamedOrCustomMD)
3330 break;
3331
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003332 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 ParseValue(Ty, Op0, PFS) ||
3334 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003335 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3337 return true;
3338 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003339
Devang Patela43d46f2009-10-16 18:45:49 +00003340 if (Lex.getKind() == lltok::NamedOrCustomMD)
3341 if (ParseOptionalCustomMetadata()) return true;
3342
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 if (!Ty->isFirstClassType())
3344 return Error(TypeLoc, "phi node must have first class type");
3345
3346 PHINode *PN = PHINode::Create(Ty);
3347 PN->reserveOperandSpace(PHIVals.size());
3348 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3349 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3350 Inst = PN;
3351 return false;
3352}
3353
3354/// ParseCall
3355/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3356/// ParameterList OptionalAttrs
3357bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3358 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003359 unsigned RetAttrs, FnAttrs;
3360 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003361 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 LocTy RetTypeLoc;
3363 ValID CalleeID;
3364 SmallVector<ParamInfo, 16> ArgList;
3365 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003366
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3368 ParseOptionalCallingConv(CC) ||
3369 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003370 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 ParseValID(CalleeID) ||
3372 ParseParameterList(ArgList, PFS) ||
3373 ParseOptionalAttrs(FnAttrs, 2))
3374 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003375
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 // If RetType is a non-function pointer type, then this is the short syntax
3377 // for the call, which means that RetType is just the return type. Infer the
3378 // rest of the function argument types from the arguments that are present.
3379 const PointerType *PFTy = 0;
3380 const FunctionType *Ty = 0;
3381 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3382 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3383 // Pull out the types of all of the arguments...
3384 std::vector<const Type*> ParamTypes;
3385 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3386 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003387
Chris Lattnerdf986172009-01-02 07:01:27 +00003388 if (!FunctionType::isValidReturnType(RetType))
3389 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003390
Owen Andersondebcb012009-07-29 22:17:13 +00003391 Ty = FunctionType::get(RetType, ParamTypes, false);
3392 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 // Look up the callee.
3396 Value *Callee;
3397 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003398
Chris Lattnerdf986172009-01-02 07:01:27 +00003399 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3400 // function attributes.
3401 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3402 if (FnAttrs & ObsoleteFuncAttrs) {
3403 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3404 FnAttrs &= ~ObsoleteFuncAttrs;
3405 }
3406
3407 // Set up the Attributes for the function.
3408 SmallVector<AttributeWithIndex, 8> Attrs;
3409 if (RetAttrs != Attribute::None)
3410 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerdf986172009-01-02 07:01:27 +00003412 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003413
Chris Lattnerdf986172009-01-02 07:01:27 +00003414 // Loop through FunctionType's arguments and ensure they are specified
3415 // correctly. Also, gather any parameter attributes.
3416 FunctionType::param_iterator I = Ty->param_begin();
3417 FunctionType::param_iterator E = Ty->param_end();
3418 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3419 const Type *ExpectedTy = 0;
3420 if (I != E) {
3421 ExpectedTy = *I++;
3422 } else if (!Ty->isVarArg()) {
3423 return Error(ArgList[i].Loc, "too many arguments specified");
3424 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003425
Chris Lattnerdf986172009-01-02 07:01:27 +00003426 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3427 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3428 ExpectedTy->getDescription() + "'");
3429 Args.push_back(ArgList[i].V);
3430 if (ArgList[i].Attrs != Attribute::None)
3431 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3432 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003433
Chris Lattnerdf986172009-01-02 07:01:27 +00003434 if (I != E)
3435 return Error(CallLoc, "not enough parameters specified for call");
3436
3437 if (FnAttrs != Attribute::None)
3438 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3439
3440 // Finish off the Attributes and check them
3441 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003442
Chris Lattnerdf986172009-01-02 07:01:27 +00003443 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3444 CI->setTailCall(isTail);
3445 CI->setCallingConv(CC);
3446 CI->setAttributes(PAL);
3447 Inst = CI;
3448 return false;
3449}
3450
3451//===----------------------------------------------------------------------===//
3452// Memory Instructions.
3453//===----------------------------------------------------------------------===//
3454
3455/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003456/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3457/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003458bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003459 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003460 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003461 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003462 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003463 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003464 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003465
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003466 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003467 if (Lex.getKind() == lltok::kw_align
3468 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003469 if (ParseOptionalInfo(Alignment)) return true;
3470 } else {
3471 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3472 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003473 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 }
3475 }
3476
Owen Anderson1d0be152009-08-13 21:58:54 +00003477 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003478 return Error(SizeLoc, "element count must be i32");
3479
Victor Hernandez68afa542009-10-21 19:11:40 +00003480 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003481 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003482 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003483 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003484
3485 // Autoupgrade old malloc instruction to malloc call.
3486 // FIXME: Remove in LLVM 3.0.
3487 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez68afa542009-10-21 19:11:40 +00003488 if (!MallocF)
3489 // Prototype malloc as "void *(int32)".
3490 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003491 MallocF = cast<Function>(
3492 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez68afa542009-10-21 19:11:40 +00003493 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003494 return false;
3495}
3496
3497/// ParseFree
3498/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003499bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3500 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003501 Value *Val; LocTy Loc;
3502 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3503 if (!isa<PointerType>(Val->getType()))
3504 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003505 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return false;
3507}
3508
3509/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003510/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003511bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3512 bool isVolatile) {
3513 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003514 unsigned Alignment = 0;
3515 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003516
Devang Patelf633a062009-09-17 23:04:48 +00003517 if (EatIfPresent(lltok::comma))
3518 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003519
3520 if (!isa<PointerType>(Val->getType()) ||
3521 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3522 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003523
Chris Lattnerdf986172009-01-02 07:01:27 +00003524 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3525 return false;
3526}
3527
3528/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003529/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003530bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3531 bool isVolatile) {
3532 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003533 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 if (ParseTypeAndValue(Val, Loc, PFS) ||
3535 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003536 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003538
3539 if (EatIfPresent(lltok::comma))
3540 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003541
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 if (!isa<PointerType>(Ptr->getType()))
3543 return Error(PtrLoc, "store operand must be a pointer");
3544 if (!Val->getType()->isFirstClassType())
3545 return Error(Loc, "store operand must be a first class value");
3546 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3547 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003548
Chris Lattnerdf986172009-01-02 07:01:27 +00003549 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3550 return false;
3551}
3552
3553/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003554/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003555/// FIXME: Remove support for getresult in LLVM 3.0
3556bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3557 Value *Val; LocTy ValLoc, EltLoc;
3558 unsigned Element;
3559 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3560 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003561 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003563
Chris Lattnerdf986172009-01-02 07:01:27 +00003564 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3565 return Error(ValLoc, "getresult inst requires an aggregate operand");
3566 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3567 return Error(EltLoc, "invalid getresult index for value");
3568 Inst = ExtractValueInst::Create(Val, Element);
3569 return false;
3570}
3571
3572/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003573/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003574bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3575 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003576
Dan Gohmandcb40a32009-07-29 15:58:36 +00003577 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003578
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003579 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003580
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 if (!isa<PointerType>(Ptr->getType()))
3582 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003583
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003585 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003586 if (Lex.getKind() == lltok::NamedOrCustomMD)
3587 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003588 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003589 if (!isa<IntegerType>(Val->getType()))
3590 return Error(EltLoc, "getelementptr index must be an integer");
3591 Indices.push_back(Val);
3592 }
Devang Patel6225d642009-10-13 18:49:55 +00003593 if (Lex.getKind() == lltok::NamedOrCustomMD)
3594 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003595
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3597 Indices.begin(), Indices.end()))
3598 return Error(Loc, "invalid getelementptr indices");
3599 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003600 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003601 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 return false;
3603}
3604
3605/// ParseExtractValue
3606/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3607bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3608 Value *Val; LocTy Loc;
3609 SmallVector<unsigned, 4> Indices;
3610 if (ParseTypeAndValue(Val, Loc, PFS) ||
3611 ParseIndexList(Indices))
3612 return true;
3613
3614 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3615 return Error(Loc, "extractvalue operand must be array or struct");
3616
3617 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3618 Indices.end()))
3619 return Error(Loc, "invalid indices for extractvalue");
3620 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3621 return false;
3622}
3623
3624/// ParseInsertValue
3625/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3626bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3627 Value *Val0, *Val1; LocTy Loc0, Loc1;
3628 SmallVector<unsigned, 4> Indices;
3629 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3630 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3631 ParseTypeAndValue(Val1, Loc1, PFS) ||
3632 ParseIndexList(Indices))
3633 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003634
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3636 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003637
Chris Lattnerdf986172009-01-02 07:01:27 +00003638 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3639 Indices.end()))
3640 return Error(Loc0, "invalid indices for insertvalue");
3641 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3642 return false;
3643}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003644
3645//===----------------------------------------------------------------------===//
3646// Embedded metadata.
3647//===----------------------------------------------------------------------===//
3648
3649/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003650/// ::= Element (',' Element)*
3651/// Element
3652/// ::= 'null' | TypeAndValue
3653bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003654 assert(Lex.getKind() == lltok::lbrace);
3655 Lex.Lex();
3656 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003657 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003658 if (Lex.getKind() == lltok::kw_null) {
3659 Lex.Lex();
3660 V = 0;
3661 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003662 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003663 if (ParseType(Ty)) return true;
3664 if (Lex.getKind() == lltok::Metadata) {
3665 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003666 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003667 if (!ParseMDNode(Node))
3668 V = Node;
3669 else {
3670 MetadataBase *MDS = 0;
3671 if (ParseMDString(MDS)) return true;
3672 V = MDS;
3673 }
3674 } else {
3675 Constant *C;
3676 if (ParseGlobalValue(Ty, C)) return true;
3677 V = C;
3678 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003679 }
3680 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003681 } while (EatIfPresent(lltok::comma));
3682
3683 return false;
3684}