blob: f1d5e4ffbb7f383ee691d8c66e11b7b054273894 [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 Hernandez13ad5aa2009-10-17 00:00:19 +000072 // Update auto-upgraded malloc calls from "autoupgrade_malloc" 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") {
80 Function* realMallocF = M->getFunction("malloc");
81 for (User::use_iterator UI = MallocF->use_begin(), UE= MallocF->use_end();
82 UI != UE; ) {
83 User* user = *UI;
84 UI++;
85 if (CallInst *Call = dyn_cast<CallInst>(user))
86 Call->setCalledFunction(realMallocF);
87 }
88 if (!realMallocF->doesNotAlias(0)) realMallocF->setDoesNotAlias(0);
89 MallocF->eraseFromParent();
90 MallocF = NULL;
91 }
92 }
93
Chris Lattnerdf986172009-01-02 07:01:27 +000094 if (!ForwardRefTypes.empty())
95 return Error(ForwardRefTypes.begin()->second.second,
96 "use of undefined type named '" +
97 ForwardRefTypes.begin()->first + "'");
98 if (!ForwardRefTypeIDs.empty())
99 return Error(ForwardRefTypeIDs.begin()->second.second,
100 "use of undefined type '%" +
101 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
106 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Chris Lattnerdf986172009-01-02 07:01:27 +0000108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patel1c7eea62009-07-08 19:23:54 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Devang Patele4b27562009-08-28 23:24:31 +0000123 // Check debug info intrinsics.
124 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000125 return false;
126}
127
128//===----------------------------------------------------------------------===//
129// Top-Level Entities
130//===----------------------------------------------------------------------===//
131
132bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000133 while (1) {
134 switch (Lex.getKind()) {
135 default: return TokError("expected top-level entity");
136 case lltok::Eof: return false;
137 //case lltok::kw_define:
138 case lltok::kw_declare: if (ParseDeclare()) return true; break;
139 case lltok::kw_define: if (ParseDefine()) return true; break;
140 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
141 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
142 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
143 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000144 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000145 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
146 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000147 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000148 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000149 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000150 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000151
152 // The Global variable production with no name can have many different
153 // optional leading prefixes, the production is:
154 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
155 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000156 case lltok::kw_private : // OptionalLinkage
157 case lltok::kw_linker_private: // OptionalLinkage
158 case lltok::kw_internal: // OptionalLinkage
159 case lltok::kw_weak: // OptionalLinkage
160 case lltok::kw_weak_odr: // OptionalLinkage
161 case lltok::kw_linkonce: // OptionalLinkage
162 case lltok::kw_linkonce_odr: // OptionalLinkage
163 case lltok::kw_appending: // OptionalLinkage
164 case lltok::kw_dllexport: // OptionalLinkage
165 case lltok::kw_common: // OptionalLinkage
166 case lltok::kw_dllimport: // OptionalLinkage
167 case lltok::kw_extern_weak: // OptionalLinkage
168 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 unsigned Linkage, Visibility;
170 if (ParseOptionalLinkage(Linkage) ||
171 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000172 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000173 return true;
174 break;
175 }
176 case lltok::kw_default: // OptionalVisibility
177 case lltok::kw_hidden: // OptionalVisibility
178 case lltok::kw_protected: { // OptionalVisibility
179 unsigned Visibility;
180 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000181 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000182 return true;
183 break;
184 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000185
Chris Lattnerdf986172009-01-02 07:01:27 +0000186 case lltok::kw_thread_local: // OptionalThreadLocal
187 case lltok::kw_addrspace: // OptionalAddrSpace
188 case lltok::kw_constant: // GlobalType
189 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000190 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 break;
192 }
193 }
194}
195
196
197/// toplevelentity
198/// ::= 'module' 'asm' STRINGCONSTANT
199bool LLParser::ParseModuleAsm() {
200 assert(Lex.getKind() == lltok::kw_module);
201 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000202
203 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000204 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
205 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000206
Chris Lattnerdf986172009-01-02 07:01:27 +0000207 const std::string &AsmSoFar = M->getModuleInlineAsm();
208 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000209 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000210 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000211 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return false;
213}
214
215/// toplevelentity
216/// ::= 'target' 'triple' '=' STRINGCONSTANT
217/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
218bool LLParser::ParseTargetDefinition() {
219 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000220 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 switch (Lex.Lex()) {
222 default: return TokError("unknown target property");
223 case lltok::kw_triple:
224 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000225 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
226 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000228 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 return false;
230 case lltok::kw_datalayout:
231 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000232 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
233 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000234 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000235 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 return false;
237 }
238}
239
240/// toplevelentity
241/// ::= 'deplibs' '=' '[' ']'
242/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
243bool LLParser::ParseDepLibs() {
244 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000245 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000246 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
247 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
248 return true;
249
250 if (EatIfPresent(lltok::rsquare))
251 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000252
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 std::string Str;
254 if (ParseStringConstant(Str)) return true;
255 M->addLibrary(Str);
256
257 while (EatIfPresent(lltok::comma)) {
258 if (ParseStringConstant(Str)) return true;
259 M->addLibrary(Str);
260 }
261
262 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000263}
264
Dan Gohman3845e502009-08-12 23:32:33 +0000265/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000266/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000267/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000268bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000269 unsigned TypeID = NumberedTypes.size();
270
271 // Handle the LocalVarID form.
272 if (Lex.getKind() == lltok::LocalVarID) {
273 if (Lex.getUIntVal() != TypeID)
274 return Error(Lex.getLoc(), "type expected to be numbered '%" +
275 utostr(TypeID) + "'");
276 Lex.Lex(); // eat LocalVarID;
277
278 if (ParseToken(lltok::equal, "expected '=' after name"))
279 return true;
280 }
281
Chris Lattnerdf986172009-01-02 07:01:27 +0000282 assert(Lex.getKind() == lltok::kw_type);
283 LocTy TypeLoc = Lex.getLoc();
284 Lex.Lex(); // eat kw_type
285
Owen Anderson1d0be152009-08-13 21:58:54 +0000286 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000287 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000288
Chris Lattnerdf986172009-01-02 07:01:27 +0000289 // See if this type was previously referenced.
290 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
291 FI = ForwardRefTypeIDs.find(TypeID);
292 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000293 if (FI->second.first.get() == Ty)
294 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattnerdf986172009-01-02 07:01:27 +0000296 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
297 Ty = FI->second.first.get();
298 ForwardRefTypeIDs.erase(FI);
299 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300
Chris Lattnerdf986172009-01-02 07:01:27 +0000301 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302
Chris Lattnerdf986172009-01-02 07:01:27 +0000303 return false;
304}
305
306/// toplevelentity
307/// ::= LocalVar '=' 'type' type
308bool LLParser::ParseNamedType() {
309 std::string Name = Lex.getStrVal();
310 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000311 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000312
Owen Anderson1d0be152009-08-13 21:58:54 +0000313 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000315 if (ParseToken(lltok::equal, "expected '=' after name") ||
316 ParseToken(lltok::kw_type, "expected 'type' after name") ||
317 ParseType(Ty))
318 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000319
Chris Lattnerdf986172009-01-02 07:01:27 +0000320 // Set the type name, checking for conflicts as we do so.
321 bool AlreadyExists = M->addTypeName(Name, Ty);
322 if (!AlreadyExists) return false;
323
324 // See if this type is a forward reference. We need to eagerly resolve
325 // types to allow recursive type redefinitions below.
326 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
327 FI = ForwardRefTypes.find(Name);
328 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000329 if (FI->second.first.get() == Ty)
330 return Error(NameLoc, "self referential type is invalid");
331
Chris Lattnerdf986172009-01-02 07:01:27 +0000332 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
333 Ty = FI->second.first.get();
334 ForwardRefTypes.erase(FI);
335 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000336
Chris Lattnerdf986172009-01-02 07:01:27 +0000337 // Inserting a name that is already defined, get the existing name.
338 const Type *Existing = M->getTypeByName(Name);
339 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000340
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 // Otherwise, this is an attempt to redefine a type. That's okay if
342 // the redefinition is identical to the original.
343 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
344 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Chris Lattnerdf986172009-01-02 07:01:27 +0000346 // Any other kind of (non-equivalent) redefinition is an error.
347 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
348 Ty->getDescription() + "'");
349}
350
351
352/// toplevelentity
353/// ::= 'declare' FunctionHeader
354bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
356 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattnerdf986172009-01-02 07:01:27 +0000358 Function *F;
359 return ParseFunctionHeader(F, false);
360}
361
362/// toplevelentity
363/// ::= 'define' FunctionHeader '{' ...
364bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
366 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerdf986172009-01-02 07:01:27 +0000368 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000371}
372
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000373/// ParseGlobalType
374/// ::= 'constant'
375/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000376bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
378 IsConstant = true;
379 else if (Lex.getKind() == lltok::kw_global)
380 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000381 else {
382 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000383 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000384 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000385 Lex.Lex();
386 return false;
387}
388
Dan Gohman3845e502009-08-12 23:32:33 +0000389/// ParseUnnamedGlobal:
390/// OptionalVisibility ALIAS ...
391/// OptionalLinkage OptionalVisibility ... -> global variable
392/// GlobalID '=' OptionalVisibility ALIAS ...
393/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
394bool LLParser::ParseUnnamedGlobal() {
395 unsigned VarID = NumberedVals.size();
396 std::string Name;
397 LocTy NameLoc = Lex.getLoc();
398
399 // Handle the GlobalID form.
400 if (Lex.getKind() == lltok::GlobalID) {
401 if (Lex.getUIntVal() != VarID)
402 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
403 utostr(VarID) + "'");
404 Lex.Lex(); // eat GlobalID;
405
406 if (ParseToken(lltok::equal, "expected '=' after name"))
407 return true;
408 }
409
410 bool HasLinkage;
411 unsigned Linkage, Visibility;
412 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
413 ParseOptionalVisibility(Visibility))
414 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000415
Dan Gohman3845e502009-08-12 23:32:33 +0000416 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
417 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
418 return ParseAlias(Name, NameLoc, Visibility);
419}
420
Chris Lattnerdf986172009-01-02 07:01:27 +0000421/// ParseNamedGlobal:
422/// GlobalVar '=' OptionalVisibility ALIAS ...
423/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
424bool LLParser::ParseNamedGlobal() {
425 assert(Lex.getKind() == lltok::GlobalVar);
426 LocTy NameLoc = Lex.getLoc();
427 std::string Name = Lex.getStrVal();
428 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattnerdf986172009-01-02 07:01:27 +0000430 bool HasLinkage;
431 unsigned Linkage, Visibility;
432 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
433 ParseOptionalLinkage(Linkage, HasLinkage) ||
434 ParseOptionalVisibility(Visibility))
435 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000436
Chris Lattnerdf986172009-01-02 07:01:27 +0000437 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
438 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
439 return ParseAlias(Name, NameLoc, Visibility);
440}
441
Devang Patel256be962009-07-20 19:00:08 +0000442// MDString:
443// ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +0000444bool LLParser::ParseMDString(MetadataBase *&MDS) {
Devang Patel256be962009-07-20 19:00:08 +0000445 std::string Str;
446 if (ParseStringConstant(Str)) return true;
Owen Anderson647e3012009-07-31 21:35:40 +0000447 MDS = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000448 return false;
449}
450
451// MDNode:
452// ::= '!' MDNodeNumber
Devang Patel104cf9e2009-07-23 01:07:34 +0000453bool LLParser::ParseMDNode(MetadataBase *&Node) {
Devang Patel256be962009-07-20 19:00:08 +0000454 // !{ ..., !42, ... }
455 unsigned MID = 0;
456 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Devang Patel256be962009-07-20 19:00:08 +0000458 // Check existing MDNode.
Devang Patel104cf9e2009-07-23 01:07:34 +0000459 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000460 if (I != MetadataCache.end()) {
461 Node = I->second;
462 return false;
463 }
464
465 // Check known forward references.
Devang Patel104cf9e2009-07-23 01:07:34 +0000466 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000467 FI = ForwardRefMDNodes.find(MID);
468 if (FI != ForwardRefMDNodes.end()) {
469 Node = FI->second.first;
470 return false;
471 }
472
473 // Create MDNode forward reference
474 SmallVector<Value *, 1> Elts;
475 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Owen Anderson647e3012009-07-31 21:35:40 +0000476 Elts.push_back(MDString::get(Context, FwdRefName));
477 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000478 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
479 Node = FwdNode;
480 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000481}
Devang Patel256be962009-07-20 19:00:08 +0000482
Devang Pateleff2ab62009-07-29 00:34:02 +0000483///ParseNamedMetadata:
484/// !foo = !{ !1, !2 }
485bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000486 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000487 Lex.Lex();
488 std::string Name = Lex.getStrVal();
489
490 if (ParseToken(lltok::equal, "expected '=' here"))
491 return true;
492
493 if (Lex.getKind() != lltok::Metadata)
494 return TokError("Expected '!' here");
495 Lex.Lex();
496
497 if (Lex.getKind() != lltok::lbrace)
498 return TokError("Expected '{' here");
499 Lex.Lex();
500 SmallVector<MetadataBase *, 8> Elts;
501 do {
502 if (Lex.getKind() != lltok::Metadata)
503 return TokError("Expected '!' here");
504 Lex.Lex();
505 MetadataBase *N = 0;
506 if (ParseMDNode(N)) return true;
507 Elts.push_back(N);
508 } while (EatIfPresent(lltok::comma));
509
510 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
511 return true;
512
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000514 return false;
515}
516
Devang Patel923078c2009-07-01 19:21:12 +0000517/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000518/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000519bool LLParser::ParseStandaloneMetadata() {
520 assert(Lex.getKind() == lltok::Metadata);
521 Lex.Lex();
522 unsigned MetadataID = 0;
523 if (ParseUInt32(MetadataID))
524 return true;
525 if (MetadataCache.find(MetadataID) != MetadataCache.end())
526 return TokError("Metadata id is already used");
527 if (ParseToken(lltok::equal, "expected '=' here"))
528 return true;
529
530 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000531 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000532 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000533 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000534
Devang Patel104cf9e2009-07-23 01:07:34 +0000535 if (Lex.getKind() != lltok::Metadata)
536 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000537
Devang Patel104cf9e2009-07-23 01:07:34 +0000538 Lex.Lex();
539 if (Lex.getKind() != lltok::lbrace)
540 return TokError("Expected '{' here");
541
542 SmallVector<Value *, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000543 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000544 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000545 return true;
546
Owen Anderson647e3012009-07-31 21:35:40 +0000547 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000548 MetadataCache[MetadataID] = Init;
Devang Patel104cf9e2009-07-23 01:07:34 +0000549 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000550 FI = ForwardRefMDNodes.find(MetadataID);
551 if (FI != ForwardRefMDNodes.end()) {
Devang Patel104cf9e2009-07-23 01:07:34 +0000552 MDNode *FwdNode = cast<MDNode>(FI->second.first);
Devang Patel1c7eea62009-07-08 19:23:54 +0000553 FwdNode->replaceAllUsesWith(Init);
554 ForwardRefMDNodes.erase(FI);
555 }
556
Devang Patel923078c2009-07-01 19:21:12 +0000557 return false;
558}
559
Chris Lattnerdf986172009-01-02 07:01:27 +0000560/// ParseAlias:
561/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
562/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000563/// ::= TypeAndValue
564/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000565/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000566///
567/// Everything through visibility has already been parsed.
568///
569bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
570 unsigned Visibility) {
571 assert(Lex.getKind() == lltok::kw_alias);
572 Lex.Lex();
573 unsigned Linkage;
574 LocTy LinkageLoc = Lex.getLoc();
575 if (ParseOptionalLinkage(Linkage))
576 return true;
577
578 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000579 Linkage != GlobalValue::WeakAnyLinkage &&
580 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000581 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000582 Linkage != GlobalValue::PrivateLinkage &&
583 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000584 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000585
Chris Lattnerdf986172009-01-02 07:01:27 +0000586 Constant *Aliasee;
587 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000588 if (Lex.getKind() != lltok::kw_bitcast &&
589 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000590 if (ParseGlobalTypeAndValue(Aliasee)) return true;
591 } else {
592 // The bitcast dest type is not present, it is implied by the dest type.
593 ValID ID;
594 if (ParseValID(ID)) return true;
595 if (ID.Kind != ValID::t_Constant)
596 return Error(AliaseeLoc, "invalid aliasee");
597 Aliasee = ID.ConstantVal;
598 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000599
Chris Lattnerdf986172009-01-02 07:01:27 +0000600 if (!isa<PointerType>(Aliasee->getType()))
601 return Error(AliaseeLoc, "alias must have pointer type");
602
603 // Okay, create the alias but do not insert it into the module yet.
604 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
605 (GlobalValue::LinkageTypes)Linkage, Name,
606 Aliasee);
607 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Chris Lattnerdf986172009-01-02 07:01:27 +0000609 // See if this value already exists in the symbol table. If so, it is either
610 // a redefinition or a definition of a forward reference.
611 if (GlobalValue *Val =
612 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
613 // See if this was a redefinition. If so, there is no entry in
614 // ForwardRefVals.
615 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
616 I = ForwardRefVals.find(Name);
617 if (I == ForwardRefVals.end())
618 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
619
620 // Otherwise, this was a definition of forward ref. Verify that types
621 // agree.
622 if (Val->getType() != GA->getType())
623 return Error(NameLoc,
624 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000625
Chris Lattnerdf986172009-01-02 07:01:27 +0000626 // If they agree, just RAUW the old value with the alias and remove the
627 // forward ref info.
628 Val->replaceAllUsesWith(GA);
629 Val->eraseFromParent();
630 ForwardRefVals.erase(I);
631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000632
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 // Insert into the module, we know its name won't collide now.
634 M->getAliasList().push_back(GA);
635 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000636
Chris Lattnerdf986172009-01-02 07:01:27 +0000637 return false;
638}
639
640/// ParseGlobal
641/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
642/// OptionalAddrSpace GlobalType Type Const
643/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
644/// OptionalAddrSpace GlobalType Type Const
645///
646/// Everything through visibility has been parsed already.
647///
648bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
649 unsigned Linkage, bool HasLinkage,
650 unsigned Visibility) {
651 unsigned AddrSpace;
652 bool ThreadLocal, IsConstant;
653 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000654
Owen Anderson1d0be152009-08-13 21:58:54 +0000655 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000656 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
657 ParseOptionalAddrSpace(AddrSpace) ||
658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
660 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000661
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 // If the linkage is specified and is external, then no initializer is
663 // present.
664 Constant *Init = 0;
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000666 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
669 return true;
670 }
671
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000672 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000673 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 GlobalVariable *GV = 0;
676
677 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000678 if (!Name.empty()) {
679 if ((GV = M->getGlobalVariable(Name, true)) &&
680 !ForwardRefVals.erase(Name))
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 } else {
683 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
684 I = ForwardRefValIDs.find(NumberedVals.size());
685 if (I != ForwardRefValIDs.end()) {
686 GV = cast<GlobalVariable>(I->second.first);
687 ForwardRefValIDs.erase(I);
688 }
689 }
690
691 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000692 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000693 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 } else {
695 if (GV->getType()->getElementType() != Ty)
696 return Error(TyLoc,
697 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Chris Lattnerdf986172009-01-02 07:01:27 +0000699 // Move the forward-reference to the correct spot in the module.
700 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
701 }
702
703 if (Name.empty())
704 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000705
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 // Set the parsed properties on the global.
707 if (Init)
708 GV->setInitializer(Init);
709 GV->setConstant(IsConstant);
710 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
711 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
712 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000713
Chris Lattnerdf986172009-01-02 07:01:27 +0000714 // Parse attributes on the global.
715 while (Lex.getKind() == lltok::comma) {
716 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 if (Lex.getKind() == lltok::kw_section) {
719 Lex.Lex();
720 GV->setSection(Lex.getStrVal());
721 if (ParseToken(lltok::StringConstant, "expected global section string"))
722 return true;
723 } else if (Lex.getKind() == lltok::kw_align) {
724 unsigned Alignment;
725 if (ParseOptionalAlignment(Alignment)) return true;
726 GV->setAlignment(Alignment);
727 } else {
728 TokError("unknown global variable property!");
729 }
730 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731
Chris Lattnerdf986172009-01-02 07:01:27 +0000732 return false;
733}
734
735
736//===----------------------------------------------------------------------===//
737// GlobalValue Reference/Resolution Routines.
738//===----------------------------------------------------------------------===//
739
740/// GetGlobalVal - Get a value with the specified name or ID, creating a
741/// forward reference record if needed. This can return null if the value
742/// exists but does not have the right type.
743GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
744 LocTy Loc) {
745 const PointerType *PTy = dyn_cast<PointerType>(Ty);
746 if (PTy == 0) {
747 Error(Loc, "global variable reference must have pointer type");
748 return 0;
749 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattnerdf986172009-01-02 07:01:27 +0000751 // Look this name up in the normal function symbol table.
752 GlobalValue *Val =
753 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000754
Chris Lattnerdf986172009-01-02 07:01:27 +0000755 // If this is a forward reference for the value, see if we already created a
756 // forward ref record.
757 if (Val == 0) {
758 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
759 I = ForwardRefVals.find(Name);
760 if (I != ForwardRefVals.end())
761 Val = I->second.first;
762 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000763
Chris Lattnerdf986172009-01-02 07:01:27 +0000764 // If we have the value in the symbol table or fwd-ref table, return it.
765 if (Val) {
766 if (Val->getType() == Ty) return Val;
767 Error(Loc, "'@" + Name + "' defined with type '" +
768 Val->getType()->getDescription() + "'");
769 return 0;
770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000771
Chris Lattnerdf986172009-01-02 07:01:27 +0000772 // Otherwise, create a new forward reference for this value and remember it.
773 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000774 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
775 // Function types can return opaque but functions can't.
776 if (isa<OpaqueType>(FT->getReturnType())) {
777 Error(Loc, "function may not return opaque type");
778 return 0;
779 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000781 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000782 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000783 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
784 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000786
Chris Lattnerdf986172009-01-02 07:01:27 +0000787 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
788 return FwdVal;
789}
790
791GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
792 const PointerType *PTy = dyn_cast<PointerType>(Ty);
793 if (PTy == 0) {
794 Error(Loc, "global variable reference must have pointer type");
795 return 0;
796 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Chris Lattnerdf986172009-01-02 07:01:27 +0000798 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000799
Chris Lattnerdf986172009-01-02 07:01:27 +0000800 // If this is a forward reference for the value, see if we already created a
801 // forward ref record.
802 if (Val == 0) {
803 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
804 I = ForwardRefValIDs.find(ID);
805 if (I != ForwardRefValIDs.end())
806 Val = I->second.first;
807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000808
Chris Lattnerdf986172009-01-02 07:01:27 +0000809 // If we have the value in the symbol table or fwd-ref table, return it.
810 if (Val) {
811 if (Val->getType() == Ty) return Val;
812 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
813 Val->getType()->getDescription() + "'");
814 return 0;
815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000816
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 // Otherwise, create a new forward reference for this value and remember it.
818 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000819 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
820 // Function types can return opaque but functions can't.
821 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000822 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000823 return 0;
824 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000825 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000826 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000827 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
828 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Chris Lattnerdf986172009-01-02 07:01:27 +0000831 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
832 return FwdVal;
833}
834
835
836//===----------------------------------------------------------------------===//
837// Helper Routines.
838//===----------------------------------------------------------------------===//
839
840/// ParseToken - If the current token has the specified kind, eat it and return
841/// success. Otherwise, emit the specified error and return failure.
842bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
843 if (Lex.getKind() != T)
844 return TokError(ErrMsg);
845 Lex.Lex();
846 return false;
847}
848
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000849/// ParseStringConstant
850/// ::= StringConstant
851bool LLParser::ParseStringConstant(std::string &Result) {
852 if (Lex.getKind() != lltok::StringConstant)
853 return TokError("expected string constant");
854 Result = Lex.getStrVal();
855 Lex.Lex();
856 return false;
857}
858
859/// ParseUInt32
860/// ::= uint32
861bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000862 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
863 return TokError("expected integer");
864 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
865 if (Val64 != unsigned(Val64))
866 return TokError("expected 32-bit integer (too large)");
867 Val = Val64;
868 Lex.Lex();
869 return false;
870}
871
872
873/// ParseOptionalAddrSpace
874/// := /*empty*/
875/// := 'addrspace' '(' uint32 ')'
876bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
877 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000878 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000879 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000880 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000881 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000882 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883}
Chris Lattnerdf986172009-01-02 07:01:27 +0000884
885/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
886/// indicates what kind of attribute list this is: 0: function arg, 1: result,
887/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000888/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000889bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
890 Attrs = Attribute::None;
891 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000892
Chris Lattnerdf986172009-01-02 07:01:27 +0000893 while (1) {
894 switch (Lex.getKind()) {
895 case lltok::kw_sext:
896 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000897 // Treat these as signext/zeroext if they occur in the argument list after
898 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
899 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
900 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000901 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000902 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000903 if (Lex.getKind() == lltok::kw_sext)
904 Attrs |= Attribute::SExt;
905 else
906 Attrs |= Attribute::ZExt;
907 break;
908 }
909 // FALL THROUGH.
910 default: // End of attributes.
911 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
912 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000913
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000914 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000916
Chris Lattnerdf986172009-01-02 07:01:27 +0000917 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000918 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
919 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
920 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
921 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
922 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
923 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
924 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
925 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000926
Devang Patel578efa92009-06-05 21:57:13 +0000927 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
928 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
929 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
930 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
931 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000932 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000933 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
934 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
935 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
936 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
937 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
938 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000939 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000940
Chris Lattnerdf986172009-01-02 07:01:27 +0000941 case lltok::kw_align: {
942 unsigned Alignment;
943 if (ParseOptionalAlignment(Alignment))
944 return true;
945 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
946 continue;
947 }
948 }
949 Lex.Lex();
950 }
951}
952
953/// ParseOptionalLinkage
954/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000955/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000956/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000957/// ::= 'internal'
958/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000959/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000960/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000961/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000962/// ::= 'appending'
963/// ::= 'dllexport'
964/// ::= 'common'
965/// ::= 'dllimport'
966/// ::= 'extern_weak'
967/// ::= 'external'
968bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
969 HasLinkage = false;
970 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000971 default: Res=GlobalValue::ExternalLinkage; return false;
972 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
973 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
974 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
975 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
976 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
977 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
978 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000979 case lltok::kw_available_externally:
980 Res = GlobalValue::AvailableExternallyLinkage;
981 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000982 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
983 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
984 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
985 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
986 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
987 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000988 }
989 Lex.Lex();
990 HasLinkage = true;
991 return false;
992}
993
994/// ParseOptionalVisibility
995/// ::= /*empty*/
996/// ::= 'default'
997/// ::= 'hidden'
998/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +0000999///
Chris Lattnerdf986172009-01-02 07:01:27 +00001000bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1001 switch (Lex.getKind()) {
1002 default: Res = GlobalValue::DefaultVisibility; return false;
1003 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1004 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1005 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1006 }
1007 Lex.Lex();
1008 return false;
1009}
1010
1011/// ParseOptionalCallingConv
1012/// ::= /*empty*/
1013/// ::= 'ccc'
1014/// ::= 'fastcc'
1015/// ::= 'coldcc'
1016/// ::= 'x86_stdcallcc'
1017/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001018/// ::= 'arm_apcscc'
1019/// ::= 'arm_aapcscc'
1020/// ::= 'arm_aapcs_vfpcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001021/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001022///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001023bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001024 switch (Lex.getKind()) {
1025 default: CC = CallingConv::C; return false;
1026 case lltok::kw_ccc: CC = CallingConv::C; break;
1027 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1028 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1029 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1030 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001031 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1032 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1033 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001034 case lltok::kw_cc: {
1035 unsigned ArbitraryCC;
1036 Lex.Lex();
1037 if (ParseUInt32(ArbitraryCC)) {
1038 return true;
1039 } else
1040 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1041 return false;
1042 }
1043 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001044 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001045
Chris Lattnerdf986172009-01-02 07:01:27 +00001046 Lex.Lex();
1047 return false;
1048}
1049
Devang Patel0475c912009-09-29 00:01:14 +00001050/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001051/// ::= /* empty */
Devang Patel0475c912009-09-29 00:01:14 +00001052/// ::= !dbg !42
1053bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001054 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001055 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001056
Chris Lattner52e20312009-10-19 05:31:10 +00001057 std::string Name = Lex.getStrVal();
1058 Lex.Lex();
1059
Devang Patelf633a062009-09-17 23:04:48 +00001060 if (Lex.getKind() != lltok::Metadata)
1061 return TokError("Expected '!' here");
1062 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001063
Devang Patelf633a062009-09-17 23:04:48 +00001064 MetadataBase *Node;
1065 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001066
Devang Patele30e6782009-09-28 21:41:20 +00001067 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001068 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1069 if (!MDK)
Devang Pateld9723e92009-10-20 22:50:27 +00001070 MDK = TheMetadata.registerMDKind(Name.c_str());
Devang Patel0475c912009-09-29 00:01:14 +00001071 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001072
Devang Patelf633a062009-09-17 23:04:48 +00001073 return false;
1074}
1075
Chris Lattnerdf986172009-01-02 07:01:27 +00001076/// ParseOptionalAlignment
1077/// ::= /* empty */
1078/// ::= 'align' 4
1079bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1080 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001081 if (!EatIfPresent(lltok::kw_align))
1082 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001083 LocTy AlignLoc = Lex.getLoc();
1084 if (ParseUInt32(Alignment)) return true;
1085 if (!isPowerOf2_32(Alignment))
1086 return Error(AlignLoc, "alignment is not a power of two");
1087 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001088}
1089
Devang Patelf633a062009-09-17 23:04:48 +00001090/// ParseOptionalInfo
1091/// ::= OptionalInfo (',' OptionalInfo)+
1092bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1093
1094 // FIXME: Handle customized metadata info attached with an instruction.
1095 do {
Devang Patel0475c912009-09-29 00:01:14 +00001096 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1097 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001098 } else if (Lex.getKind() == lltok::kw_align) {
1099 if (ParseOptionalAlignment(Alignment)) return true;
1100 } else
1101 return true;
1102 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001103
Devang Patelf633a062009-09-17 23:04:48 +00001104 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001105}
1106
Devang Patelf633a062009-09-17 23:04:48 +00001107
Chris Lattnerdf986172009-01-02 07:01:27 +00001108/// ParseIndexList
1109/// ::= (',' uint32)+
1110bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1111 if (Lex.getKind() != lltok::comma)
1112 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001114 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001115 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001116 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 Indices.push_back(Idx);
1118 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001119
Chris Lattnerdf986172009-01-02 07:01:27 +00001120 return false;
1121}
1122
1123//===----------------------------------------------------------------------===//
1124// Type Parsing.
1125//===----------------------------------------------------------------------===//
1126
1127/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001128bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1129 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001130 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001131
Chris Lattnerdf986172009-01-02 07:01:27 +00001132 // Verify no unresolved uprefs.
1133 if (!UpRefs.empty())
1134 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001135
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001136 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001137 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001138
Chris Lattnerdf986172009-01-02 07:01:27 +00001139 return false;
1140}
1141
1142/// HandleUpRefs - Every time we finish a new layer of types, this function is
1143/// called. It loops through the UpRefs vector, which is a list of the
1144/// currently active types. For each type, if the up-reference is contained in
1145/// the newly completed type, we decrement the level count. When the level
1146/// count reaches zero, the up-referenced type is the type that is passed in:
1147/// thus we can complete the cycle.
1148///
1149PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1150 // If Ty isn't abstract, or if there are no up-references in it, then there is
1151 // nothing to resolve here.
1152 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001153
Chris Lattnerdf986172009-01-02 07:01:27 +00001154 PATypeHolder Ty(ty);
1155#if 0
1156 errs() << "Type '" << Ty->getDescription()
1157 << "' newly formed. Resolving upreferences.\n"
1158 << UpRefs.size() << " upreferences active!\n";
1159#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001160
Chris Lattnerdf986172009-01-02 07:01:27 +00001161 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1162 // to zero), we resolve them all together before we resolve them to Ty. At
1163 // the end of the loop, if there is anything to resolve to Ty, it will be in
1164 // this variable.
1165 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001166
Chris Lattnerdf986172009-01-02 07:01:27 +00001167 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1168 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1169 bool ContainsType =
1170 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1171 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001172
Chris Lattnerdf986172009-01-02 07:01:27 +00001173#if 0
1174 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1175 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1176 << (ContainsType ? "true" : "false")
1177 << " level=" << UpRefs[i].NestingLevel << "\n";
1178#endif
1179 if (!ContainsType)
1180 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 // Decrement level of upreference
1183 unsigned Level = --UpRefs[i].NestingLevel;
1184 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001185
Chris Lattnerdf986172009-01-02 07:01:27 +00001186 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1187 if (Level != 0)
1188 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001189
Chris Lattnerdf986172009-01-02 07:01:27 +00001190#if 0
1191 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1192#endif
1193 if (!TypeToResolve)
1194 TypeToResolve = UpRefs[i].UpRefTy;
1195 else
1196 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1197 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1198 --i; // Do not skip the next element.
1199 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001200
Chris Lattnerdf986172009-01-02 07:01:27 +00001201 if (TypeToResolve)
1202 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001203
Chris Lattnerdf986172009-01-02 07:01:27 +00001204 return Ty;
1205}
1206
1207
1208/// ParseTypeRec - The recursive function used to process the internal
1209/// implementation details of types.
1210bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1211 switch (Lex.getKind()) {
1212 default:
1213 return TokError("expected type");
1214 case lltok::Type:
1215 // TypeRec ::= 'float' | 'void' (etc)
1216 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001217 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001218 break;
1219 case lltok::kw_opaque:
1220 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001221 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 Lex.Lex();
1223 break;
1224 case lltok::lbrace:
1225 // TypeRec ::= '{' ... '}'
1226 if (ParseStructType(Result, false))
1227 return true;
1228 break;
1229 case lltok::lsquare:
1230 // TypeRec ::= '[' ... ']'
1231 Lex.Lex(); // eat the lsquare.
1232 if (ParseArrayVectorType(Result, false))
1233 return true;
1234 break;
1235 case lltok::less: // Either vector or packed struct.
1236 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001237 Lex.Lex();
1238 if (Lex.getKind() == lltok::lbrace) {
1239 if (ParseStructType(Result, true) ||
1240 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 } else if (ParseArrayVectorType(Result, true))
1243 return true;
1244 break;
1245 case lltok::LocalVar:
1246 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1247 // TypeRec ::= %foo
1248 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1249 Result = T;
1250 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001251 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001252 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1253 std::make_pair(Result,
1254 Lex.getLoc())));
1255 M->addTypeName(Lex.getStrVal(), Result.get());
1256 }
1257 Lex.Lex();
1258 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattnerdf986172009-01-02 07:01:27 +00001260 case lltok::LocalVarID:
1261 // TypeRec ::= %4
1262 if (Lex.getUIntVal() < NumberedTypes.size())
1263 Result = NumberedTypes[Lex.getUIntVal()];
1264 else {
1265 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1266 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1267 if (I != ForwardRefTypeIDs.end())
1268 Result = I->second.first;
1269 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001270 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1272 std::make_pair(Result,
1273 Lex.getLoc())));
1274 }
1275 }
1276 Lex.Lex();
1277 break;
1278 case lltok::backslash: {
1279 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001281 unsigned Val;
1282 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001283 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1285 Result = OT;
1286 break;
1287 }
1288 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
1290 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001291 while (1) {
1292 switch (Lex.getKind()) {
1293 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001295
1296 // TypeRec ::= TypeRec '*'
1297 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001298 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001299 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001300 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001301 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001302 if (!PointerType::isValidElementType(Result.get()))
1303 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001304 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 Lex.Lex();
1306 break;
1307
1308 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1309 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001310 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001312 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001313 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001314 if (!PointerType::isValidElementType(Result.get()))
1315 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 unsigned AddrSpace;
1317 if (ParseOptionalAddrSpace(AddrSpace) ||
1318 ParseToken(lltok::star, "expected '*' in address space"))
1319 return true;
1320
Owen Andersondebcb012009-07-29 22:17:13 +00001321 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001322 break;
1323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001324
Chris Lattnerdf986172009-01-02 07:01:27 +00001325 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1326 case lltok::lparen:
1327 if (ParseFunctionType(Result))
1328 return true;
1329 break;
1330 }
1331 }
1332}
1333
1334/// ParseParameterList
1335/// ::= '(' ')'
1336/// ::= '(' Arg (',' Arg)* ')'
1337/// Arg
1338/// ::= Type OptionalAttributes Value OptionalAttributes
1339bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1340 PerFunctionState &PFS) {
1341 if (ParseToken(lltok::lparen, "expected '(' in call"))
1342 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001343
Chris Lattnerdf986172009-01-02 07:01:27 +00001344 while (Lex.getKind() != lltok::rparen) {
1345 // If this isn't the first argument, we need a comma.
1346 if (!ArgList.empty() &&
1347 ParseToken(lltok::comma, "expected ',' in argument list"))
1348 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001349
Chris Lattnerdf986172009-01-02 07:01:27 +00001350 // Parse the argument.
1351 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001352 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 unsigned ArgAttrs1, ArgAttrs2;
1354 Value *V;
1355 if (ParseType(ArgTy, ArgLoc) ||
1356 ParseOptionalAttrs(ArgAttrs1, 0) ||
1357 ParseValue(ArgTy, V, PFS) ||
1358 // FIXME: Should not allow attributes after the argument, remove this in
1359 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001360 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 return true;
1362 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1363 }
1364
1365 Lex.Lex(); // Lex the ')'.
1366 return false;
1367}
1368
1369
1370
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001371/// ParseArgumentList - Parse the argument list for a function type or function
1372/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001373/// ::= '(' ArgTypeListI ')'
1374/// ArgTypeListI
1375/// ::= /*empty*/
1376/// ::= '...'
1377/// ::= ArgTypeList ',' '...'
1378/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001379///
Chris Lattnerdf986172009-01-02 07:01:27 +00001380bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001381 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001382 isVarArg = false;
1383 assert(Lex.getKind() == lltok::lparen);
1384 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001385
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 if (Lex.getKind() == lltok::rparen) {
1387 // empty
1388 } else if (Lex.getKind() == lltok::dotdotdot) {
1389 isVarArg = true;
1390 Lex.Lex();
1391 } else {
1392 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001393 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001395 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001396
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001397 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1398 // types (such as a function returning a pointer to itself). If parsing a
1399 // function prototype, we require fully resolved types.
1400 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001401 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001403 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001404 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001405
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 if (Lex.getKind() == lltok::LocalVar ||
1407 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1408 Name = Lex.getStrVal();
1409 Lex.Lex();
1410 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001411
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001412 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001413 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001414
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001417 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001419 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 break;
1422 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001423
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 // Otherwise must be an argument type.
1425 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001426 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001427 ParseOptionalAttrs(Attrs, 0)) return true;
1428
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001429 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001430 return Error(TypeLoc, "argument can not have void type");
1431
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 if (Lex.getKind() == lltok::LocalVar ||
1433 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1434 Name = Lex.getStrVal();
1435 Lex.Lex();
1436 } else {
1437 Name = "";
1438 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001439
1440 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1441 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001442
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1444 }
1445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001447 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001448}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001449
Chris Lattnerdf986172009-01-02 07:01:27 +00001450/// ParseFunctionType
1451/// ::= Type ArgumentList OptionalAttrs
1452bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1453 assert(Lex.getKind() == lltok::lparen);
1454
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001455 if (!FunctionType::isValidReturnType(Result))
1456 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001457
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 std::vector<ArgInfo> ArgList;
1459 bool isVarArg;
1460 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001461 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 // FIXME: Allow, but ignore attributes on function types!
1463 // FIXME: Remove in LLVM 3.0
1464 ParseOptionalAttrs(Attrs, 2))
1465 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001466
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 // Reject names on the arguments lists.
1468 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1469 if (!ArgList[i].Name.empty())
1470 return Error(ArgList[i].Loc, "argument name invalid in function type");
1471 if (!ArgList[i].Attrs != 0) {
1472 // Allow but ignore attributes on function types; this permits
1473 // auto-upgrade.
1474 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1475 }
1476 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001477
Chris Lattnerdf986172009-01-02 07:01:27 +00001478 std::vector<const Type*> ArgListTy;
1479 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1480 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001481
Owen Andersondebcb012009-07-29 22:17:13 +00001482 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001483 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001484 return false;
1485}
1486
1487/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1488/// TypeRec
1489/// ::= '{' '}'
1490/// ::= '{' TypeRec (',' TypeRec)* '}'
1491/// ::= '<' '{' '}' '>'
1492/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1493bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1494 assert(Lex.getKind() == lltok::lbrace);
1495 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001496
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001497 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001498 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 return false;
1500 }
1501
1502 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001503 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 if (ParseTypeRec(Result)) return true;
1505 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001507 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001508 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001509 if (!StructType::isValidElementType(Result))
1510 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001511
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001512 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001513 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001514 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001515
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001516 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001517 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001518 if (!StructType::isValidElementType(Result))
1519 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001520
Chris Lattnerdf986172009-01-02 07:01:27 +00001521 ParamsList.push_back(Result);
1522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001524 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1525 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattnerdf986172009-01-02 07:01:27 +00001527 std::vector<const Type*> ParamsListTy;
1528 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1529 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001530 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 return false;
1532}
1533
1534/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1535/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001537/// ::= '[' APSINTVAL 'x' Types ']'
1538/// ::= '<' APSINTVAL 'x' Types '>'
1539bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1540 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1541 Lex.getAPSIntVal().getBitWidth() > 64)
1542 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnerdf986172009-01-02 07:01:27 +00001544 LocTy SizeLoc = Lex.getLoc();
1545 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001546 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001547
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1549 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001550
1551 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001552 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001554
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001555 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001556 return Error(TypeLoc, "array and vector element type cannot be void");
1557
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001558 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1559 "expected end of sequential type"))
1560 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561
Chris Lattnerdf986172009-01-02 07:01:27 +00001562 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001563 if (Size == 0)
1564 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001565 if ((unsigned)Size != Size)
1566 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001567 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001568 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001569 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001571 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001573 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001574 }
1575 return false;
1576}
1577
1578//===----------------------------------------------------------------------===//
1579// Function Semantic Analysis.
1580//===----------------------------------------------------------------------===//
1581
1582LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1583 : P(p), F(f) {
1584
1585 // Insert unnamed arguments into the NumberedVals list.
1586 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1587 AI != E; ++AI)
1588 if (!AI->hasName())
1589 NumberedVals.push_back(AI);
1590}
1591
1592LLParser::PerFunctionState::~PerFunctionState() {
1593 // If there were any forward referenced non-basicblock values, delete them.
1594 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1595 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1596 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001597 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001598 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 delete I->second.first;
1600 I->second.first = 0;
1601 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1604 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1605 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001606 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001607 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001608 delete I->second.first;
1609 I->second.first = 0;
1610 }
1611}
1612
1613bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1614 if (!ForwardRefVals.empty())
1615 return P.Error(ForwardRefVals.begin()->second.second,
1616 "use of undefined value '%" + ForwardRefVals.begin()->first +
1617 "'");
1618 if (!ForwardRefValIDs.empty())
1619 return P.Error(ForwardRefValIDs.begin()->second.second,
1620 "use of undefined value '%" +
1621 utostr(ForwardRefValIDs.begin()->first) + "'");
1622 return false;
1623}
1624
1625
1626/// GetVal - Get a value with the specified name or ID, creating a
1627/// forward reference record if needed. This can return null if the value
1628/// exists but does not have the right type.
1629Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1630 const Type *Ty, LocTy Loc) {
1631 // Look this name up in the normal function symbol table.
1632 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 // If this is a forward reference for the value, see if we already created a
1635 // forward ref record.
1636 if (Val == 0) {
1637 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638 I = ForwardRefVals.find(Name);
1639 if (I != ForwardRefVals.end())
1640 Val = I->second.first;
1641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattnerdf986172009-01-02 07:01:27 +00001643 // If we have the value in the symbol table or fwd-ref table, return it.
1644 if (Val) {
1645 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001646 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001647 P.Error(Loc, "'%" + Name + "' is not a basic block");
1648 else
1649 P.Error(Loc, "'%" + Name + "' defined with type '" +
1650 Val->getType()->getDescription() + "'");
1651 return 0;
1652 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001653
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001655 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1656 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001657 P.Error(Loc, "invalid use of a non-first-class type");
1658 return 0;
1659 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattnerdf986172009-01-02 07:01:27 +00001661 // Otherwise, create a new forward reference for this value and remember it.
1662 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001663 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001664 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001665 else
1666 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattnerdf986172009-01-02 07:01:27 +00001668 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1669 return FwdVal;
1670}
1671
1672Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1673 LocTy Loc) {
1674 // Look this name up in the normal function symbol table.
1675 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676
Chris Lattnerdf986172009-01-02 07:01:27 +00001677 // If this is a forward reference for the value, see if we already created a
1678 // forward ref record.
1679 if (Val == 0) {
1680 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1681 I = ForwardRefValIDs.find(ID);
1682 if (I != ForwardRefValIDs.end())
1683 Val = I->second.first;
1684 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Chris Lattnerdf986172009-01-02 07:01:27 +00001686 // If we have the value in the symbol table or fwd-ref table, return it.
1687 if (Val) {
1688 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001689 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001690 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1691 else
1692 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1693 Val->getType()->getDescription() + "'");
1694 return 0;
1695 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Owen Anderson1d0be152009-08-13 21:58:54 +00001697 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1698 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001699 P.Error(Loc, "invalid use of a non-first-class type");
1700 return 0;
1701 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnerdf986172009-01-02 07:01:27 +00001703 // Otherwise, create a new forward reference for this value and remember it.
1704 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001705 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001706 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001707 else
1708 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1711 return FwdVal;
1712}
1713
1714/// SetInstName - After an instruction is parsed and inserted into its
1715/// basic block, this installs its name.
1716bool LLParser::PerFunctionState::SetInstName(int NameID,
1717 const std::string &NameStr,
1718 LocTy NameLoc, Instruction *Inst) {
1719 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001720 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 if (NameID != -1 || !NameStr.empty())
1722 return P.Error(NameLoc, "instructions returning void cannot have a name");
1723 return false;
1724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001725
Chris Lattnerdf986172009-01-02 07:01:27 +00001726 // If this was a numbered instruction, verify that the instruction is the
1727 // expected value and resolve any forward references.
1728 if (NameStr.empty()) {
1729 // If neither a name nor an ID was specified, just use the next ID.
1730 if (NameID == -1)
1731 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001732
Chris Lattnerdf986172009-01-02 07:01:27 +00001733 if (unsigned(NameID) != NumberedVals.size())
1734 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1735 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001736
Chris Lattnerdf986172009-01-02 07:01:27 +00001737 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1738 ForwardRefValIDs.find(NameID);
1739 if (FI != ForwardRefValIDs.end()) {
1740 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001741 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001742 FI->second.first->getType()->getDescription() + "'");
1743 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001744 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001745 ForwardRefValIDs.erase(FI);
1746 }
1747
1748 NumberedVals.push_back(Inst);
1749 return false;
1750 }
1751
1752 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1753 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1754 FI = ForwardRefVals.find(NameStr);
1755 if (FI != ForwardRefVals.end()) {
1756 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001757 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 FI->second.first->getType()->getDescription() + "'");
1759 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001760 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 ForwardRefVals.erase(FI);
1762 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001763
Chris Lattnerdf986172009-01-02 07:01:27 +00001764 // Set the name on the instruction.
1765 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001766
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001768 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 NameStr + "'");
1770 return false;
1771}
1772
1773/// GetBB - Get a basic block with the specified name or ID, creating a
1774/// forward reference record if needed.
1775BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1776 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001777 return cast_or_null<BasicBlock>(GetVal(Name,
1778 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001779}
1780
1781BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001782 return cast_or_null<BasicBlock>(GetVal(ID,
1783 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001784}
1785
1786/// DefineBB - Define the specified basic block, which is either named or
1787/// unnamed. If there is an error, this returns null otherwise it returns
1788/// the block being defined.
1789BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1790 LocTy Loc) {
1791 BasicBlock *BB;
1792 if (Name.empty())
1793 BB = GetBB(NumberedVals.size(), Loc);
1794 else
1795 BB = GetBB(Name, Loc);
1796 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 // Move the block to the end of the function. Forward ref'd blocks are
1799 // inserted wherever they happen to be referenced.
1800 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001801
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 // Remove the block from forward ref sets.
1803 if (Name.empty()) {
1804 ForwardRefValIDs.erase(NumberedVals.size());
1805 NumberedVals.push_back(BB);
1806 } else {
1807 // BB forward references are already in the function symbol table.
1808 ForwardRefVals.erase(Name);
1809 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001810
Chris Lattnerdf986172009-01-02 07:01:27 +00001811 return BB;
1812}
1813
1814//===----------------------------------------------------------------------===//
1815// Constants.
1816//===----------------------------------------------------------------------===//
1817
1818/// ParseValID - Parse an abstract value that doesn't necessarily have a
1819/// type implied. For example, if we parse "4" we don't know what integer type
1820/// it has. The value will later be combined with its type and checked for
1821/// sanity.
1822bool LLParser::ParseValID(ValID &ID) {
1823 ID.Loc = Lex.getLoc();
1824 switch (Lex.getKind()) {
1825 default: return TokError("expected value token");
1826 case lltok::GlobalID: // @42
1827 ID.UIntVal = Lex.getUIntVal();
1828 ID.Kind = ValID::t_GlobalID;
1829 break;
1830 case lltok::GlobalVar: // @foo
1831 ID.StrVal = Lex.getStrVal();
1832 ID.Kind = ValID::t_GlobalName;
1833 break;
1834 case lltok::LocalVarID: // %42
1835 ID.UIntVal = Lex.getUIntVal();
1836 ID.Kind = ValID::t_LocalID;
1837 break;
1838 case lltok::LocalVar: // %foo
1839 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1840 ID.StrVal = Lex.getStrVal();
1841 ID.Kind = ValID::t_LocalName;
1842 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001843 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001844 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001845 Lex.Lex();
1846 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001847 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001848 if (ParseMDNodeVector(Elts) ||
1849 ParseToken(lltok::rbrace, "expected end of metadata node"))
1850 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001851
Owen Anderson647e3012009-07-31 21:35:40 +00001852 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001853 return false;
1854 }
1855
Devang Patel923078c2009-07-01 19:21:12 +00001856 // Standalone metadata reference
1857 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001858 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001859 return false;
Devang Patel256be962009-07-20 19:00:08 +00001860
Nick Lewycky21cc4462009-04-04 07:22:01 +00001861 // MDString:
1862 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001863 if (ParseMDString(ID.MetadataVal)) return true;
1864 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001865 return false;
1866 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 ID.Kind = ValID::t_APSInt;
1870 break;
1871 case lltok::APFloat:
1872 ID.APFloatVal = Lex.getAPFloatVal();
1873 ID.Kind = ValID::t_APFloat;
1874 break;
1875 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001876 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001877 ID.Kind = ValID::t_Constant;
1878 break;
1879 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001880 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001881 ID.Kind = ValID::t_Constant;
1882 break;
1883 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1884 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1885 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886
Chris Lattnerdf986172009-01-02 07:01:27 +00001887 case lltok::lbrace: {
1888 // ValID ::= '{' ConstVector '}'
1889 Lex.Lex();
1890 SmallVector<Constant*, 16> Elts;
1891 if (ParseGlobalValueVector(Elts) ||
1892 ParseToken(lltok::rbrace, "expected end of struct constant"))
1893 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001895 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1896 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 ID.Kind = ValID::t_Constant;
1898 return false;
1899 }
1900 case lltok::less: {
1901 // ValID ::= '<' ConstVector '>' --> Vector.
1902 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1903 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001904 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001905
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 SmallVector<Constant*, 16> Elts;
1907 LocTy FirstEltLoc = Lex.getLoc();
1908 if (ParseGlobalValueVector(Elts) ||
1909 (isPackedStruct &&
1910 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1911 ParseToken(lltok::greater, "expected end of constant"))
1912 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001915 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001916 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001917 ID.Kind = ValID::t_Constant;
1918 return false;
1919 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 if (Elts.empty())
1922 return Error(ID.Loc, "constant vector must not be empty");
1923
1924 if (!Elts[0]->getType()->isInteger() &&
1925 !Elts[0]->getType()->isFloatingPoint())
1926 return Error(FirstEltLoc,
1927 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 // Verify that all the vector elements have the same type.
1930 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1931 if (Elts[i]->getType() != Elts[0]->getType())
1932 return Error(FirstEltLoc,
1933 "vector element #" + utostr(i) +
1934 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001935
Owen Andersonaf7ec972009-07-28 21:19:26 +00001936 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001937 ID.Kind = ValID::t_Constant;
1938 return false;
1939 }
1940 case lltok::lsquare: { // Array Constant
1941 Lex.Lex();
1942 SmallVector<Constant*, 16> Elts;
1943 LocTy FirstEltLoc = Lex.getLoc();
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rsquare, "expected end of array constant"))
1946 return true;
1947
1948 // Handle empty element.
1949 if (Elts.empty()) {
1950 // Use undef instead of an array because it's inconvenient to determine
1951 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001952 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001953 return false;
1954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Owen Andersondebcb012009-07-29 22:17:13 +00001960 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001961
Chris Lattnerdf986172009-01-02 07:01:27 +00001962 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001963 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 if (Elts[i]->getType() != Elts[0]->getType())
1965 return Error(FirstEltLoc,
1966 "array element #" + utostr(i) +
1967 " is not of type '" +Elts[0]->getType()->getDescription());
1968 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001969
Owen Anderson1fd70962009-07-28 18:32:17 +00001970 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 ID.Kind = ValID::t_Constant;
1972 return false;
1973 }
1974 case lltok::kw_c: // c "foo"
1975 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001976 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001977 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1978 ID.Kind = ValID::t_Constant;
1979 return false;
1980
1981 case lltok::kw_asm: {
Dale Johannesen43602982009-10-13 20:46:56 +00001982 // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT
1983 bool HasSideEffect, MsAsm;
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 Lex.Lex();
1985 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen43602982009-10-13 20:46:56 +00001986 ParseOptionalToken(lltok::kw_msasm, MsAsm) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001987 ParseStringConstant(ID.StrVal) ||
1988 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 ParseToken(lltok::StringConstant, "expected constraint string"))
1990 return true;
1991 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen43602982009-10-13 20:46:56 +00001992 ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001993 ID.Kind = ValID::t_InlineAsm;
1994 return false;
1995 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Chris Lattnerdf986172009-01-02 07:01:27 +00001997 case lltok::kw_trunc:
1998 case lltok::kw_zext:
1999 case lltok::kw_sext:
2000 case lltok::kw_fptrunc:
2001 case lltok::kw_fpext:
2002 case lltok::kw_bitcast:
2003 case lltok::kw_uitofp:
2004 case lltok::kw_sitofp:
2005 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002006 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002010 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 Constant *SrcVal;
2012 Lex.Lex();
2013 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2014 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002015 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 ParseType(DestTy) ||
2017 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2018 return true;
2019 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2020 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2021 SrcVal->getType()->getDescription() + "' to '" +
2022 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002023 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002024 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002025 ID.Kind = ValID::t_Constant;
2026 return false;
2027 }
2028 case lltok::kw_extractvalue: {
2029 Lex.Lex();
2030 Constant *Val;
2031 SmallVector<unsigned, 4> Indices;
2032 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2033 ParseGlobalTypeAndValue(Val) ||
2034 ParseIndexList(Indices) ||
2035 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2036 return true;
2037 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2038 return Error(ID.Loc, "extractvalue operand must be array or struct");
2039 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2040 Indices.end()))
2041 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002042 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002043 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002044 ID.Kind = ValID::t_Constant;
2045 return false;
2046 }
2047 case lltok::kw_insertvalue: {
2048 Lex.Lex();
2049 Constant *Val0, *Val1;
2050 SmallVector<unsigned, 4> Indices;
2051 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2052 ParseGlobalTypeAndValue(Val0) ||
2053 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2054 ParseGlobalTypeAndValue(Val1) ||
2055 ParseIndexList(Indices) ||
2056 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2057 return true;
2058 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2059 return Error(ID.Loc, "extractvalue operand must be array or struct");
2060 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2061 Indices.end()))
2062 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002063 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002064 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 ID.Kind = ValID::t_Constant;
2066 return false;
2067 }
2068 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002069 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 unsigned PredVal, Opc = Lex.getUIntVal();
2071 Constant *Val0, *Val1;
2072 Lex.Lex();
2073 if (ParseCmpPredicate(PredVal, Opc) ||
2074 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2075 ParseGlobalTypeAndValue(Val0) ||
2076 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2077 ParseGlobalTypeAndValue(Val1) ||
2078 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2079 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 if (Val0->getType() != Val1->getType())
2082 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002083
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002085
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 if (Opc == Instruction::FCmp) {
2087 if (!Val0->getType()->isFPOrFPVector())
2088 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002089 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002090 } else {
2091 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 if (!Val0->getType()->isIntOrIntVector() &&
2093 !isa<PointerType>(Val0->getType()))
2094 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002095 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002096 }
2097 ID.Kind = ValID::t_Constant;
2098 return false;
2099 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002100
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 // Binary Operators.
2102 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002103 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002105 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002107 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 case lltok::kw_udiv:
2109 case lltok::kw_sdiv:
2110 case lltok::kw_fdiv:
2111 case lltok::kw_urem:
2112 case lltok::kw_srem:
2113 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002114 bool NUW = false;
2115 bool NSW = false;
2116 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 unsigned Opc = Lex.getUIntVal();
2118 Constant *Val0, *Val1;
2119 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002120 LocTy ModifierLoc = Lex.getLoc();
2121 if (Opc == Instruction::Add ||
2122 Opc == Instruction::Sub ||
2123 Opc == Instruction::Mul) {
2124 if (EatIfPresent(lltok::kw_nuw))
2125 NUW = true;
2126 if (EatIfPresent(lltok::kw_nsw)) {
2127 NSW = true;
2128 if (EatIfPresent(lltok::kw_nuw))
2129 NUW = true;
2130 }
2131 } else if (Opc == Instruction::SDiv) {
2132 if (EatIfPresent(lltok::kw_exact))
2133 Exact = true;
2134 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2136 ParseGlobalTypeAndValue(Val0) ||
2137 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2138 ParseGlobalTypeAndValue(Val1) ||
2139 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2140 return true;
2141 if (Val0->getType() != Val1->getType())
2142 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002143 if (!Val0->getType()->isIntOrIntVector()) {
2144 if (NUW)
2145 return Error(ModifierLoc, "nuw only applies to integer operations");
2146 if (NSW)
2147 return Error(ModifierLoc, "nsw only applies to integer operations");
2148 }
2149 // API compatibility: Accept either integer or floating-point types with
2150 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 if (!Val0->getType()->isIntOrIntVector() &&
2152 !Val0->getType()->isFPOrFPVector())
2153 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002154 unsigned Flags = 0;
2155 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2156 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2157 if (Exact) Flags |= SDivOperator::IsExact;
2158 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002159 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 ID.Kind = ValID::t_Constant;
2161 return false;
2162 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163
Chris Lattnerdf986172009-01-02 07:01:27 +00002164 // Logical Operations
2165 case lltok::kw_shl:
2166 case lltok::kw_lshr:
2167 case lltok::kw_ashr:
2168 case lltok::kw_and:
2169 case lltok::kw_or:
2170 case lltok::kw_xor: {
2171 unsigned Opc = Lex.getUIntVal();
2172 Constant *Val0, *Val1;
2173 Lex.Lex();
2174 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2175 ParseGlobalTypeAndValue(Val0) ||
2176 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2177 ParseGlobalTypeAndValue(Val1) ||
2178 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2179 return true;
2180 if (Val0->getType() != Val1->getType())
2181 return Error(ID.Loc, "operands of constexpr must have same type");
2182 if (!Val0->getType()->isIntOrIntVector())
2183 return Error(ID.Loc,
2184 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002185 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002186 ID.Kind = ValID::t_Constant;
2187 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002188 }
2189
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 case lltok::kw_getelementptr:
2191 case lltok::kw_shufflevector:
2192 case lltok::kw_insertelement:
2193 case lltok::kw_extractelement:
2194 case lltok::kw_select: {
2195 unsigned Opc = Lex.getUIntVal();
2196 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002197 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002198 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002199 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002200 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2202 ParseGlobalValueVector(Elts) ||
2203 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2204 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 if (Opc == Instruction::GetElementPtr) {
2207 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2208 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002209
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002211 (Value**)(Elts.data() + 1),
2212 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002213 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002214 ID.ConstantVal = InBounds ?
2215 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2216 Elts.data() + 1,
2217 Elts.size() - 1) :
2218 ConstantExpr::getGetElementPtr(Elts[0],
2219 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 } else if (Opc == Instruction::Select) {
2221 if (Elts.size() != 3)
2222 return Error(ID.Loc, "expected three operands to select");
2223 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2224 Elts[2]))
2225 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002226 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 } else if (Opc == Instruction::ShuffleVector) {
2228 if (Elts.size() != 3)
2229 return Error(ID.Loc, "expected three operands to shufflevector");
2230 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2231 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002232 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002233 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 } else if (Opc == Instruction::ExtractElement) {
2235 if (Elts.size() != 2)
2236 return Error(ID.Loc, "expected two operands to extractelement");
2237 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2238 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002239 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 } else {
2241 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2242 if (Elts.size() != 3)
2243 return Error(ID.Loc, "expected three operands to insertelement");
2244 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2245 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002246 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002248 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 ID.Kind = ValID::t_Constant;
2251 return false;
2252 }
2253 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002254
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 Lex.Lex();
2256 return false;
2257}
2258
2259/// ParseGlobalValue - Parse a global value with the specified type.
2260bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2261 V = 0;
2262 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002263 return ParseValID(ID) ||
2264 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002265}
2266
2267/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2268/// constant.
2269bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2270 Constant *&V) {
2271 if (isa<FunctionType>(Ty))
2272 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002273
Chris Lattnerdf986172009-01-02 07:01:27 +00002274 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002275 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002276 case ValID::t_Metadata:
2277 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 case ValID::t_LocalID:
2279 case ValID::t_LocalName:
2280 return Error(ID.Loc, "invalid use of function-local name");
2281 case ValID::t_InlineAsm:
2282 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2283 case ValID::t_GlobalName:
2284 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2285 return V == 0;
2286 case ValID::t_GlobalID:
2287 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2288 return V == 0;
2289 case ValID::t_APSInt:
2290 if (!isa<IntegerType>(Ty))
2291 return Error(ID.Loc, "integer constant must have integer type");
2292 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002293 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 return false;
2295 case ValID::t_APFloat:
2296 if (!Ty->isFloatingPoint() ||
2297 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2298 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002299
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 // The lexer has no type info, so builds all float and double FP constants
2301 // as double. Fix this here. Long double does not need this.
2302 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002303 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002304 bool Ignored;
2305 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2306 &Ignored);
2307 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002308 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Chris Lattner959873d2009-01-05 18:24:23 +00002310 if (V->getType() != Ty)
2311 return Error(ID.Loc, "floating point constant does not have type '" +
2312 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002313
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 return false;
2315 case ValID::t_Null:
2316 if (!isa<PointerType>(Ty))
2317 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002318 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002319 return false;
2320 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002321 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002322 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002323 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002324 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002325 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002326 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002327 case ValID::t_EmptyArray:
2328 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2329 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002330 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002331 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002332 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002333 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002334 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002336 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 return false;
2338 case ValID::t_Constant:
2339 if (ID.ConstantVal->getType() != Ty)
2340 return Error(ID.Loc, "constant expression type mismatch");
2341 V = ID.ConstantVal;
2342 return false;
2343 }
2344}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345
Chris Lattnerdf986172009-01-02 07:01:27 +00002346bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002347 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002348 return ParseType(Type) ||
2349 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002350}
Chris Lattnerdf986172009-01-02 07:01:27 +00002351
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002352/// ParseGlobalValueVector
2353/// ::= /*empty*/
2354/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002355bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2356 // Empty list.
2357 if (Lex.getKind() == lltok::rbrace ||
2358 Lex.getKind() == lltok::rsquare ||
2359 Lex.getKind() == lltok::greater ||
2360 Lex.getKind() == lltok::rparen)
2361 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002362
Chris Lattnerdf986172009-01-02 07:01:27 +00002363 Constant *C;
2364 if (ParseGlobalTypeAndValue(C)) return true;
2365 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002366
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002367 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002368 if (ParseGlobalTypeAndValue(C)) return true;
2369 Elts.push_back(C);
2370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002371
Chris Lattnerdf986172009-01-02 07:01:27 +00002372 return false;
2373}
2374
2375
2376//===----------------------------------------------------------------------===//
2377// Function Parsing.
2378//===----------------------------------------------------------------------===//
2379
2380bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2381 PerFunctionState &PFS) {
2382 if (ID.Kind == ValID::t_LocalID)
2383 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2384 else if (ID.Kind == ValID::t_LocalName)
2385 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002386 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2388 const FunctionType *FTy =
2389 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2390 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2391 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002392 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002393 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002394 } else if (ID.Kind == ValID::t_Metadata) {
2395 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002396 } else {
2397 Constant *C;
2398 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2399 V = C;
2400 return false;
2401 }
2402
2403 return V == 0;
2404}
2405
2406bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2407 V = 0;
2408 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002409 return ParseValID(ID) ||
2410 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002411}
2412
2413bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002414 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002415 return ParseType(T) ||
2416 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002417}
2418
2419/// FunctionHeader
2420/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2421/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2422/// OptionalAlign OptGC
2423bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2424 // Parse the linkage.
2425 LocTy LinkageLoc = Lex.getLoc();
2426 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002427
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002428 unsigned Visibility, RetAttrs;
2429 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002430 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002431 LocTy RetTypeLoc = Lex.getLoc();
2432 if (ParseOptionalLinkage(Linkage) ||
2433 ParseOptionalVisibility(Visibility) ||
2434 ParseOptionalCallingConv(CC) ||
2435 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002436 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 return true;
2438
2439 // Verify that the linkage is ok.
2440 switch ((GlobalValue::LinkageTypes)Linkage) {
2441 case GlobalValue::ExternalLinkage:
2442 break; // always ok.
2443 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002444 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 if (isDefine)
2446 return Error(LinkageLoc, "invalid linkage for function definition");
2447 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002448 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002449 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002451 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002452 case GlobalValue::LinkOnceAnyLinkage:
2453 case GlobalValue::LinkOnceODRLinkage:
2454 case GlobalValue::WeakAnyLinkage:
2455 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002456 case GlobalValue::DLLExportLinkage:
2457 if (!isDefine)
2458 return Error(LinkageLoc, "invalid linkage for function declaration");
2459 break;
2460 case GlobalValue::AppendingLinkage:
2461 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002462 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002463 return Error(LinkageLoc, "invalid function linkage type");
2464 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002465
Chris Lattner99bb3152009-01-05 08:00:30 +00002466 if (!FunctionType::isValidReturnType(RetType) ||
2467 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002469
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002471
2472 std::string FunctionName;
2473 if (Lex.getKind() == lltok::GlobalVar) {
2474 FunctionName = Lex.getStrVal();
2475 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2476 unsigned NameID = Lex.getUIntVal();
2477
2478 if (NameID != NumberedVals.size())
2479 return TokError("function expected to be numbered '%" +
2480 utostr(NumberedVals.size()) + "'");
2481 } else {
2482 return TokError("expected function name");
2483 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002484
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002485 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002487 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002488 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002489
Chris Lattnerdf986172009-01-02 07:01:27 +00002490 std::vector<ArgInfo> ArgList;
2491 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002492 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002493 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002495 std::string GC;
2496
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002497 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002498 ParseOptionalAttrs(FuncAttrs, 2) ||
2499 (EatIfPresent(lltok::kw_section) &&
2500 ParseStringConstant(Section)) ||
2501 ParseOptionalAlignment(Alignment) ||
2502 (EatIfPresent(lltok::kw_gc) &&
2503 ParseStringConstant(GC)))
2504 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002505
2506 // If the alignment was parsed as an attribute, move to the alignment field.
2507 if (FuncAttrs & Attribute::Alignment) {
2508 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2509 FuncAttrs &= ~Attribute::Alignment;
2510 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002511
Chris Lattnerdf986172009-01-02 07:01:27 +00002512 // Okay, if we got here, the function is syntactically valid. Convert types
2513 // and do semantic checks.
2514 std::vector<const Type*> ParamTypeList;
2515 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002516 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002517 // attributes.
2518 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2519 if (FuncAttrs & ObsoleteFuncAttrs) {
2520 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2521 FuncAttrs &= ~ObsoleteFuncAttrs;
2522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002523
Chris Lattnerdf986172009-01-02 07:01:27 +00002524 if (RetAttrs != Attribute::None)
2525 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002526
Chris Lattnerdf986172009-01-02 07:01:27 +00002527 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2528 ParamTypeList.push_back(ArgList[i].Type);
2529 if (ArgList[i].Attrs != Attribute::None)
2530 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2531 }
2532
2533 if (FuncAttrs != Attribute::None)
2534 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2535
2536 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002537
Chris Lattnera9a9e072009-03-09 04:49:14 +00002538 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002539 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2541
Owen Andersonfba933c2009-07-01 23:57:11 +00002542 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002543 FunctionType::get(RetType, ParamTypeList, isVarArg);
2544 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002545
2546 Fn = 0;
2547 if (!FunctionName.empty()) {
2548 // If this was a definition of a forward reference, remove the definition
2549 // from the forward reference table and fill in the forward ref.
2550 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2551 ForwardRefVals.find(FunctionName);
2552 if (FRVI != ForwardRefVals.end()) {
2553 Fn = M->getFunction(FunctionName);
2554 ForwardRefVals.erase(FRVI);
2555 } else if ((Fn = M->getFunction(FunctionName))) {
2556 // If this function already exists in the symbol table, then it is
2557 // multiply defined. We accept a few cases for old backwards compat.
2558 // FIXME: Remove this stuff for LLVM 3.0.
2559 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2560 (!Fn->isDeclaration() && isDefine)) {
2561 // If the redefinition has different type or different attributes,
2562 // reject it. If both have bodies, reject it.
2563 return Error(NameLoc, "invalid redefinition of function '" +
2564 FunctionName + "'");
2565 } else if (Fn->isDeclaration()) {
2566 // Make sure to strip off any argument names so we can't get conflicts.
2567 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2568 AI != AE; ++AI)
2569 AI->setName("");
2570 }
2571 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Dan Gohman41905542009-08-29 23:37:49 +00002573 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002574 // If this is a definition of a forward referenced function, make sure the
2575 // types agree.
2576 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2577 = ForwardRefValIDs.find(NumberedVals.size());
2578 if (I != ForwardRefValIDs.end()) {
2579 Fn = cast<Function>(I->second.first);
2580 if (Fn->getType() != PFT)
2581 return Error(NameLoc, "type of definition and forward reference of '@" +
2582 utostr(NumberedVals.size()) +"' disagree");
2583 ForwardRefValIDs.erase(I);
2584 }
2585 }
2586
2587 if (Fn == 0)
2588 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2589 else // Move the forward-reference to the correct spot in the module.
2590 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2591
2592 if (FunctionName.empty())
2593 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002594
Chris Lattnerdf986172009-01-02 07:01:27 +00002595 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2596 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2597 Fn->setCallingConv(CC);
2598 Fn->setAttributes(PAL);
2599 Fn->setAlignment(Alignment);
2600 Fn->setSection(Section);
2601 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002602
Chris Lattnerdf986172009-01-02 07:01:27 +00002603 // Add all of the arguments we parsed to the function.
2604 Function::arg_iterator ArgIt = Fn->arg_begin();
2605 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2606 // If the argument has a name, insert it into the argument symbol table.
2607 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002608
Chris Lattnerdf986172009-01-02 07:01:27 +00002609 // Set the name, if it conflicted, it will be auto-renamed.
2610 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 if (ArgIt->getNameStr() != ArgList[i].Name)
2613 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2614 ArgList[i].Name + "'");
2615 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002616
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 return false;
2618}
2619
2620
2621/// ParseFunctionBody
2622/// ::= '{' BasicBlock+ '}'
2623/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2624///
2625bool LLParser::ParseFunctionBody(Function &Fn) {
2626 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2627 return TokError("expected '{' in function body");
2628 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnerdf986172009-01-02 07:01:27 +00002630 PerFunctionState PFS(*this, Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002631
Chris Lattnerdf986172009-01-02 07:01:27 +00002632 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2633 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002634
Chris Lattnerdf986172009-01-02 07:01:27 +00002635 // Eat the }.
2636 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Chris Lattnerdf986172009-01-02 07:01:27 +00002638 // Verify function is ok.
2639 return PFS.VerifyFunctionComplete();
2640}
2641
2642/// ParseBasicBlock
2643/// ::= LabelStr? Instruction*
2644bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2645 // If this basic block starts out with a name, remember it.
2646 std::string Name;
2647 LocTy NameLoc = Lex.getLoc();
2648 if (Lex.getKind() == lltok::LabelStr) {
2649 Name = Lex.getStrVal();
2650 Lex.Lex();
2651 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002652
Chris Lattnerdf986172009-01-02 07:01:27 +00002653 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2654 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002655
Chris Lattnerdf986172009-01-02 07:01:27 +00002656 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002657
Chris Lattnerdf986172009-01-02 07:01:27 +00002658 // Parse the instructions in this block until we get a terminator.
2659 Instruction *Inst;
2660 do {
2661 // This instruction may have three possibilities for a name: a) none
2662 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2663 LocTy NameLoc = Lex.getLoc();
2664 int NameID = -1;
2665 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002666
Chris Lattnerdf986172009-01-02 07:01:27 +00002667 if (Lex.getKind() == lltok::LocalVarID) {
2668 NameID = Lex.getUIntVal();
2669 Lex.Lex();
2670 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2671 return true;
2672 } else if (Lex.getKind() == lltok::LocalVar ||
2673 // FIXME: REMOVE IN LLVM 3.0
2674 Lex.getKind() == lltok::StringConstant) {
2675 NameStr = Lex.getStrVal();
2676 Lex.Lex();
2677 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2678 return true;
2679 }
Devang Patelf633a062009-09-17 23:04:48 +00002680
Chris Lattnerdf986172009-01-02 07:01:27 +00002681 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002682 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002683 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002684
2685 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002686 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002687 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002689 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002690 MDsOnInst.clear();
2691
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 BB->getInstList().push_back(Inst);
2693
2694 // Set the name on the instruction.
2695 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2696 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 return false;
2699}
2700
2701//===----------------------------------------------------------------------===//
2702// Instruction Parsing.
2703//===----------------------------------------------------------------------===//
2704
2705/// ParseInstruction - Parse one of the many different instructions.
2706///
2707bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2708 PerFunctionState &PFS) {
2709 lltok::Kind Token = Lex.getKind();
2710 if (Token == lltok::Eof)
2711 return TokError("found end of file when expecting more instructions");
2712 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002713 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002714 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002715
Chris Lattnerdf986172009-01-02 07:01:27 +00002716 switch (Token) {
2717 default: return Error(Loc, "expected instruction opcode");
2718 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002719 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2720 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2722 case lltok::kw_br: return ParseBr(Inst, PFS);
2723 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2724 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2725 // Binary Operators.
2726 case lltok::kw_add:
2727 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002728 case lltok::kw_mul: {
2729 bool NUW = false;
2730 bool NSW = false;
2731 LocTy ModifierLoc = Lex.getLoc();
2732 if (EatIfPresent(lltok::kw_nuw))
2733 NUW = true;
2734 if (EatIfPresent(lltok::kw_nsw)) {
2735 NSW = true;
2736 if (EatIfPresent(lltok::kw_nuw))
2737 NUW = true;
2738 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002739 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002740 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2741 if (!Result) {
2742 if (!Inst->getType()->isIntOrIntVector()) {
2743 if (NUW)
2744 return Error(ModifierLoc, "nuw only applies to integer operations");
2745 if (NSW)
2746 return Error(ModifierLoc, "nsw only applies to integer operations");
2747 }
2748 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002749 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002750 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002751 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002752 }
2753 return Result;
2754 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002755 case lltok::kw_fadd:
2756 case lltok::kw_fsub:
2757 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2758
Dan Gohman59858cf2009-07-27 16:11:46 +00002759 case lltok::kw_sdiv: {
2760 bool Exact = false;
2761 if (EatIfPresent(lltok::kw_exact))
2762 Exact = true;
2763 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2764 if (!Result)
2765 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002766 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002767 return Result;
2768 }
2769
Chris Lattnerdf986172009-01-02 07:01:27 +00002770 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002772 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002773 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002774 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002775 case lltok::kw_shl:
2776 case lltok::kw_lshr:
2777 case lltok::kw_ashr:
2778 case lltok::kw_and:
2779 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002780 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002781 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002782 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002783 // Casts.
2784 case lltok::kw_trunc:
2785 case lltok::kw_zext:
2786 case lltok::kw_sext:
2787 case lltok::kw_fptrunc:
2788 case lltok::kw_fpext:
2789 case lltok::kw_bitcast:
2790 case lltok::kw_uitofp:
2791 case lltok::kw_sitofp:
2792 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002793 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002795 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 // Other.
2797 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002798 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002799 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2800 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2801 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2802 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2803 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2804 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2805 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002806 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2807 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 case lltok::kw_free: return ParseFree(Inst, PFS);
2809 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2810 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2811 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002812 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002814 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002816 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002817 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002818 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2819 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2820 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2821 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2822 }
2823}
2824
2825/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2826bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002827 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 switch (Lex.getKind()) {
2829 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2830 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2831 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2832 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2833 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2834 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2835 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2836 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2837 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2838 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2839 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2840 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2841 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2842 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2843 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2844 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2845 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2846 }
2847 } else {
2848 switch (Lex.getKind()) {
2849 default: TokError("expected icmp predicate (e.g. 'eq')");
2850 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2851 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2852 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2853 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2854 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2855 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2856 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2857 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2858 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2859 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2860 }
2861 }
2862 Lex.Lex();
2863 return false;
2864}
2865
2866//===----------------------------------------------------------------------===//
2867// Terminator Instructions.
2868//===----------------------------------------------------------------------===//
2869
2870/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002871/// ::= 'ret' void (',' !dbg, !1)
2872/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2873/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002874/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002875bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2876 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002877 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002878 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002880 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002881 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 return false;
2883 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 Value *RV;
2886 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002887
Devang Patelf633a062009-09-17 23:04:48 +00002888 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002889 // Parse optional custom metadata, e.g. !dbg
2890 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2891 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002892 } else {
2893 // The normal case is one return value.
2894 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2895 // of 'ret {i32,i32} {i32 1, i32 2}'
2896 SmallVector<Value*, 8> RVs;
2897 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002898
Devang Patelf633a062009-09-17 23:04:48 +00002899 do {
Devang Patel0475c912009-09-29 00:01:14 +00002900 // If optional custom metadata, e.g. !dbg is seen then this is the
2901 // end of MRV.
2902 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002903 break;
2904 if (ParseTypeAndValue(RV, PFS)) return true;
2905 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00002906 } while (EatIfPresent(lltok::comma));
2907
2908 RV = UndefValue::get(PFS.getFunction().getReturnType());
2909 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002910 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2911 BB->getInstList().push_back(I);
2912 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00002913 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002914 }
2915 }
Devang Patelf633a062009-09-17 23:04:48 +00002916
Owen Anderson1d0be152009-08-13 21:58:54 +00002917 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 return false;
2919}
2920
2921
2922/// ParseBr
2923/// ::= 'br' TypeAndValue
2924/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2925bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2926 LocTy Loc, Loc2;
2927 Value *Op0, *Op1, *Op2;
2928 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002929
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2931 Inst = BranchInst::Create(BB);
2932 return false;
2933 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002934
Owen Anderson1d0be152009-08-13 21:58:54 +00002935 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002936 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2939 ParseTypeAndValue(Op1, Loc, PFS) ||
2940 ParseToken(lltok::comma, "expected ',' after true destination") ||
2941 ParseTypeAndValue(Op2, Loc2, PFS))
2942 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002943
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 if (!isa<BasicBlock>(Op1))
2945 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002946 if (!isa<BasicBlock>(Op2))
2947 return Error(Loc2, "true destination of branch must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002948
Chris Lattnerdf986172009-01-02 07:01:27 +00002949 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2950 return false;
2951}
2952
2953/// ParseSwitch
2954/// Instruction
2955/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2956/// JumpTable
2957/// ::= (TypeAndValue ',' TypeAndValue)*
2958bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2959 LocTy CondLoc, BBLoc;
2960 Value *Cond, *DefaultBB;
2961 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2962 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2963 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2964 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2965 return true;
2966
2967 if (!isa<IntegerType>(Cond->getType()))
2968 return Error(CondLoc, "switch condition must have integer type");
2969 if (!isa<BasicBlock>(DefaultBB))
2970 return Error(BBLoc, "default destination must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002971
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 // Parse the jump table pairs.
2973 SmallPtrSet<Value*, 32> SeenCases;
2974 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2975 while (Lex.getKind() != lltok::rsquare) {
2976 Value *Constant, *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2979 ParseToken(lltok::comma, "expected ',' after case value") ||
2980 ParseTypeAndValue(DestBB, BBLoc, PFS))
2981 return true;
2982
2983 if (!SeenCases.insert(Constant))
2984 return Error(CondLoc, "duplicate case value in switch");
2985 if (!isa<ConstantInt>(Constant))
2986 return Error(CondLoc, "case value is not a constant integer");
2987 if (!isa<BasicBlock>(DestBB))
2988 return Error(BBLoc, "case destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002989
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2991 cast<BasicBlock>(DestBB)));
2992 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002993
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002995
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2997 Table.size());
2998 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2999 SI->addCase(Table[i].first, Table[i].second);
3000 Inst = SI;
3001 return false;
3002}
3003
3004/// ParseInvoke
3005/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3006/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3007bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3008 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003009 unsigned RetAttrs, FnAttrs;
3010 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003011 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003012 LocTy RetTypeLoc;
3013 ValID CalleeID;
3014 SmallVector<ParamInfo, 16> ArgList;
3015
3016 Value *NormalBB, *UnwindBB;
3017 if (ParseOptionalCallingConv(CC) ||
3018 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003019 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003020 ParseValID(CalleeID) ||
3021 ParseParameterList(ArgList, PFS) ||
3022 ParseOptionalAttrs(FnAttrs, 2) ||
3023 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3024 ParseTypeAndValue(NormalBB, PFS) ||
3025 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3026 ParseTypeAndValue(UnwindBB, PFS))
3027 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003028
Chris Lattnerdf986172009-01-02 07:01:27 +00003029 if (!isa<BasicBlock>(NormalBB))
3030 return Error(CallLoc, "normal destination is not a basic block");
3031 if (!isa<BasicBlock>(UnwindBB))
3032 return Error(CallLoc, "unwind destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003033
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 // If RetType is a non-function pointer type, then this is the short syntax
3035 // for the call, which means that RetType is just the return type. Infer the
3036 // rest of the function argument types from the arguments that are present.
3037 const PointerType *PFTy = 0;
3038 const FunctionType *Ty = 0;
3039 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3040 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3041 // Pull out the types of all of the arguments...
3042 std::vector<const Type*> ParamTypes;
3043 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3044 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003045
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 if (!FunctionType::isValidReturnType(RetType))
3047 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003048
Owen Andersondebcb012009-07-29 22:17:13 +00003049 Ty = FunctionType::get(RetType, ParamTypes, false);
3050 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003051 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003052
Chris Lattnerdf986172009-01-02 07:01:27 +00003053 // Look up the callee.
3054 Value *Callee;
3055 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003056
Chris Lattnerdf986172009-01-02 07:01:27 +00003057 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3058 // function attributes.
3059 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3060 if (FnAttrs & ObsoleteFuncAttrs) {
3061 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3062 FnAttrs &= ~ObsoleteFuncAttrs;
3063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003064
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 // Set up the Attributes for the function.
3066 SmallVector<AttributeWithIndex, 8> Attrs;
3067 if (RetAttrs != Attribute::None)
3068 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003069
Chris Lattnerdf986172009-01-02 07:01:27 +00003070 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003071
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 // Loop through FunctionType's arguments and ensure they are specified
3073 // correctly. Also, gather any parameter attributes.
3074 FunctionType::param_iterator I = Ty->param_begin();
3075 FunctionType::param_iterator E = Ty->param_end();
3076 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3077 const Type *ExpectedTy = 0;
3078 if (I != E) {
3079 ExpectedTy = *I++;
3080 } else if (!Ty->isVarArg()) {
3081 return Error(ArgList[i].Loc, "too many arguments specified");
3082 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003083
Chris Lattnerdf986172009-01-02 07:01:27 +00003084 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3085 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3086 ExpectedTy->getDescription() + "'");
3087 Args.push_back(ArgList[i].V);
3088 if (ArgList[i].Attrs != Attribute::None)
3089 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003091
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 if (I != E)
3093 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003094
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 if (FnAttrs != Attribute::None)
3096 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003097
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 // Finish off the Attributes and check them
3099 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003100
Chris Lattnerdf986172009-01-02 07:01:27 +00003101 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3102 cast<BasicBlock>(UnwindBB),
3103 Args.begin(), Args.end());
3104 II->setCallingConv(CC);
3105 II->setAttributes(PAL);
3106 Inst = II;
3107 return false;
3108}
3109
3110
3111
3112//===----------------------------------------------------------------------===//
3113// Binary Operators.
3114//===----------------------------------------------------------------------===//
3115
3116/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003117/// ::= ArithmeticOps TypeAndValue ',' Value
3118///
3119/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3120/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003121bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003122 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 LocTy Loc; Value *LHS, *RHS;
3124 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3125 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3126 ParseValue(LHS->getType(), RHS, PFS))
3127 return true;
3128
Chris Lattnere914b592009-01-05 08:24:46 +00003129 bool Valid;
3130 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003131 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003132 case 0: // int or FP.
3133 Valid = LHS->getType()->isIntOrIntVector() ||
3134 LHS->getType()->isFPOrFPVector();
3135 break;
3136 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3137 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3138 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003139
Chris Lattnere914b592009-01-05 08:24:46 +00003140 if (!Valid)
3141 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003142
Chris Lattnerdf986172009-01-02 07:01:27 +00003143 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3144 return false;
3145}
3146
3147/// ParseLogical
3148/// ::= ArithmeticOps TypeAndValue ',' Value {
3149bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3150 unsigned Opc) {
3151 LocTy Loc; Value *LHS, *RHS;
3152 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3154 ParseValue(LHS->getType(), RHS, PFS))
3155 return true;
3156
3157 if (!LHS->getType()->isIntOrIntVector())
3158 return Error(Loc,"instruction requires integer or integer vector operands");
3159
3160 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3161 return false;
3162}
3163
3164
3165/// ParseCompare
3166/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3167/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003168bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3169 unsigned Opc) {
3170 // Parse the integer/fp comparison predicate.
3171 LocTy Loc;
3172 unsigned Pred;
3173 Value *LHS, *RHS;
3174 if (ParseCmpPredicate(Pred, Opc) ||
3175 ParseTypeAndValue(LHS, Loc, PFS) ||
3176 ParseToken(lltok::comma, "expected ',' after compare value") ||
3177 ParseValue(LHS->getType(), RHS, PFS))
3178 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003179
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 if (Opc == Instruction::FCmp) {
3181 if (!LHS->getType()->isFPOrFPVector())
3182 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003183 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003184 } else {
3185 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (!LHS->getType()->isIntOrIntVector() &&
3187 !isa<PointerType>(LHS->getType()))
3188 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003189 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003190 }
3191 return false;
3192}
3193
3194//===----------------------------------------------------------------------===//
3195// Other Instructions.
3196//===----------------------------------------------------------------------===//
3197
3198
3199/// ParseCast
3200/// ::= CastOpc TypeAndValue 'to' Type
3201bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3202 unsigned Opc) {
3203 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003204 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 if (ParseTypeAndValue(Op, Loc, PFS) ||
3206 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3207 ParseType(DestTy))
3208 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003210 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3211 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 return Error(Loc, "invalid cast opcode for cast from '" +
3213 Op->getType()->getDescription() + "' to '" +
3214 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003215 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003216 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3217 return false;
3218}
3219
3220/// ParseSelect
3221/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3222bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3223 LocTy Loc;
3224 Value *Op0, *Op1, *Op2;
3225 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3226 ParseToken(lltok::comma, "expected ',' after select condition") ||
3227 ParseTypeAndValue(Op1, PFS) ||
3228 ParseToken(lltok::comma, "expected ',' after select value") ||
3229 ParseTypeAndValue(Op2, PFS))
3230 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3233 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 Inst = SelectInst::Create(Op0, Op1, Op2);
3236 return false;
3237}
3238
Chris Lattner0088a5c2009-01-05 08:18:44 +00003239/// ParseVA_Arg
3240/// ::= 'va_arg' TypeAndValue ',' Type
3241bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003243 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003244 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 if (ParseTypeAndValue(Op, PFS) ||
3246 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003247 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Chris Lattner0088a5c2009-01-05 08:18:44 +00003250 if (!EltTy->isFirstClassType())
3251 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003252
3253 Inst = new VAArgInst(Op, EltTy);
3254 return false;
3255}
3256
3257/// ParseExtractElement
3258/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3259bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3260 LocTy Loc;
3261 Value *Op0, *Op1;
3262 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3263 ParseToken(lltok::comma, "expected ',' after extract value") ||
3264 ParseTypeAndValue(Op1, PFS))
3265 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003266
Chris Lattnerdf986172009-01-02 07:01:27 +00003267 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3268 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Eric Christophera3500da2009-07-25 02:28:41 +00003270 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 return false;
3272}
3273
3274/// ParseInsertElement
3275/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3276bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3277 LocTy Loc;
3278 Value *Op0, *Op1, *Op2;
3279 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3280 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3281 ParseTypeAndValue(Op1, PFS) ||
3282 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3283 ParseTypeAndValue(Op2, PFS))
3284 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003285
Chris Lattnerdf986172009-01-02 07:01:27 +00003286 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003287 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003288
Chris Lattnerdf986172009-01-02 07:01:27 +00003289 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3290 return false;
3291}
3292
3293/// ParseShuffleVector
3294/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3295bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3296 LocTy Loc;
3297 Value *Op0, *Op1, *Op2;
3298 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3299 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3300 ParseTypeAndValue(Op1, PFS) ||
3301 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3302 ParseTypeAndValue(Op2, PFS))
3303 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003304
Chris Lattnerdf986172009-01-02 07:01:27 +00003305 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3306 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3309 return false;
3310}
3311
3312/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003313/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003314bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003315 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 Value *Op0, *Op1;
3317 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003318
Chris Lattnerdf986172009-01-02 07:01:27 +00003319 if (ParseType(Ty) ||
3320 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3321 ParseValue(Ty, Op0, PFS) ||
3322 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003323 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003324 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3325 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003326
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3328 while (1) {
3329 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003330
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003331 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003332 break;
3333
Devang Patela43d46f2009-10-16 18:45:49 +00003334 if (Lex.getKind() == lltok::NamedOrCustomMD)
3335 break;
3336
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003337 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 ParseValue(Ty, Op0, PFS) ||
3339 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003340 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3342 return true;
3343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003344
Devang Patela43d46f2009-10-16 18:45:49 +00003345 if (Lex.getKind() == lltok::NamedOrCustomMD)
3346 if (ParseOptionalCustomMetadata()) return true;
3347
Chris Lattnerdf986172009-01-02 07:01:27 +00003348 if (!Ty->isFirstClassType())
3349 return Error(TypeLoc, "phi node must have first class type");
3350
3351 PHINode *PN = PHINode::Create(Ty);
3352 PN->reserveOperandSpace(PHIVals.size());
3353 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3354 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3355 Inst = PN;
3356 return false;
3357}
3358
3359/// ParseCall
3360/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3361/// ParameterList OptionalAttrs
3362bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3363 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003364 unsigned RetAttrs, FnAttrs;
3365 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003366 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003367 LocTy RetTypeLoc;
3368 ValID CalleeID;
3369 SmallVector<ParamInfo, 16> ArgList;
3370 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003371
Chris Lattnerdf986172009-01-02 07:01:27 +00003372 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3373 ParseOptionalCallingConv(CC) ||
3374 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003375 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 ParseValID(CalleeID) ||
3377 ParseParameterList(ArgList, PFS) ||
3378 ParseOptionalAttrs(FnAttrs, 2))
3379 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003380
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 // If RetType is a non-function pointer type, then this is the short syntax
3382 // for the call, which means that RetType is just the return type. Infer the
3383 // rest of the function argument types from the arguments that are present.
3384 const PointerType *PFTy = 0;
3385 const FunctionType *Ty = 0;
3386 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3387 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3388 // Pull out the types of all of the arguments...
3389 std::vector<const Type*> ParamTypes;
3390 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3391 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003392
Chris Lattnerdf986172009-01-02 07:01:27 +00003393 if (!FunctionType::isValidReturnType(RetType))
3394 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003395
Owen Andersondebcb012009-07-29 22:17:13 +00003396 Ty = FunctionType::get(RetType, ParamTypes, false);
3397 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003399
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 // Look up the callee.
3401 Value *Callee;
3402 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003403
Chris Lattnerdf986172009-01-02 07:01:27 +00003404 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3405 // function attributes.
3406 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3407 if (FnAttrs & ObsoleteFuncAttrs) {
3408 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3409 FnAttrs &= ~ObsoleteFuncAttrs;
3410 }
3411
3412 // Set up the Attributes for the function.
3413 SmallVector<AttributeWithIndex, 8> Attrs;
3414 if (RetAttrs != Attribute::None)
3415 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003416
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 // Loop through FunctionType's arguments and ensure they are specified
3420 // correctly. Also, gather any parameter attributes.
3421 FunctionType::param_iterator I = Ty->param_begin();
3422 FunctionType::param_iterator E = Ty->param_end();
3423 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3424 const Type *ExpectedTy = 0;
3425 if (I != E) {
3426 ExpectedTy = *I++;
3427 } else if (!Ty->isVarArg()) {
3428 return Error(ArgList[i].Loc, "too many arguments specified");
3429 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003430
Chris Lattnerdf986172009-01-02 07:01:27 +00003431 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3432 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3433 ExpectedTy->getDescription() + "'");
3434 Args.push_back(ArgList[i].V);
3435 if (ArgList[i].Attrs != Attribute::None)
3436 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003438
Chris Lattnerdf986172009-01-02 07:01:27 +00003439 if (I != E)
3440 return Error(CallLoc, "not enough parameters specified for call");
3441
3442 if (FnAttrs != Attribute::None)
3443 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3444
3445 // Finish off the Attributes and check them
3446 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003447
Chris Lattnerdf986172009-01-02 07:01:27 +00003448 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3449 CI->setTailCall(isTail);
3450 CI->setCallingConv(CC);
3451 CI->setAttributes(PAL);
3452 Inst = CI;
3453 return false;
3454}
3455
3456//===----------------------------------------------------------------------===//
3457// Memory Instructions.
3458//===----------------------------------------------------------------------===//
3459
3460/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003461/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3462/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003463bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003464 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003465 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003466 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003467 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003469 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003470
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003471 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003472 if (Lex.getKind() == lltok::kw_align
3473 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003474 if (ParseOptionalInfo(Alignment)) return true;
3475 } else {
3476 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3477 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003478 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003479 }
3480 }
3481
Owen Anderson1d0be152009-08-13 21:58:54 +00003482 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 return Error(SizeLoc, "element count must be i32");
3484
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003485 if (isAlloca)
Owen Anderson50dead02009-07-15 23:53:25 +00003486 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003487 else {
3488 // Autoupgrade old malloc instruction to malloc call.
3489 const Type* IntPtrTy = Type::getInt32Ty(Context);
3490 const Type* Int8PtrTy = PointerType::getUnqual(Type::getInt8Ty(Context));
3491 if (!MallocF)
3492 // Prototype malloc as "void *autoupgrade_malloc(int32)".
3493 MallocF = cast<Function>(M->getOrInsertFunction("autoupgrade_malloc",
3494 Int8PtrTy, IntPtrTy, NULL));
3495 // "autoupgrade_malloc" updated to "malloc" in ValidateEndOfModule().
3496
3497 Inst = cast<Instruction>(CallInst::CreateMalloc(BB, IntPtrTy, Ty,
3498 Size, MallocF));
3499 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 return false;
3501}
3502
3503/// ParseFree
3504/// ::= 'free' TypeAndValue
3505bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3506 Value *Val; LocTy Loc;
3507 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3508 if (!isa<PointerType>(Val->getType()))
3509 return Error(Loc, "operand to free must be a pointer");
3510 Inst = new FreeInst(Val);
3511 return false;
3512}
3513
3514/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003515/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003516bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3517 bool isVolatile) {
3518 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003519 unsigned Alignment = 0;
3520 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003521
Devang Patelf633a062009-09-17 23:04:48 +00003522 if (EatIfPresent(lltok::comma))
3523 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003524
3525 if (!isa<PointerType>(Val->getType()) ||
3526 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3527 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003528
Chris Lattnerdf986172009-01-02 07:01:27 +00003529 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3530 return false;
3531}
3532
3533/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003534/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003535bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3536 bool isVolatile) {
3537 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003538 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003539 if (ParseTypeAndValue(Val, Loc, PFS) ||
3540 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003541 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003543
3544 if (EatIfPresent(lltok::comma))
3545 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003546
Chris Lattnerdf986172009-01-02 07:01:27 +00003547 if (!isa<PointerType>(Ptr->getType()))
3548 return Error(PtrLoc, "store operand must be a pointer");
3549 if (!Val->getType()->isFirstClassType())
3550 return Error(Loc, "store operand must be a first class value");
3551 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3552 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003553
Chris Lattnerdf986172009-01-02 07:01:27 +00003554 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3555 return false;
3556}
3557
3558/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003559/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003560/// FIXME: Remove support for getresult in LLVM 3.0
3561bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3562 Value *Val; LocTy ValLoc, EltLoc;
3563 unsigned Element;
3564 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3565 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003566 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003568
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3570 return Error(ValLoc, "getresult inst requires an aggregate operand");
3571 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3572 return Error(EltLoc, "invalid getresult index for value");
3573 Inst = ExtractValueInst::Create(Val, Element);
3574 return false;
3575}
3576
3577/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003578/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003579bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3580 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003581
Dan Gohmandcb40a32009-07-29 15:58:36 +00003582 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003583
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003584 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003585
Chris Lattnerdf986172009-01-02 07:01:27 +00003586 if (!isa<PointerType>(Ptr->getType()))
3587 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003588
Chris Lattnerdf986172009-01-02 07:01:27 +00003589 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003590 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003591 if (Lex.getKind() == lltok::NamedOrCustomMD)
3592 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003593 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003594 if (!isa<IntegerType>(Val->getType()))
3595 return Error(EltLoc, "getelementptr index must be an integer");
3596 Indices.push_back(Val);
3597 }
Devang Patel6225d642009-10-13 18:49:55 +00003598 if (Lex.getKind() == lltok::NamedOrCustomMD)
3599 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003600
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3602 Indices.begin(), Indices.end()))
3603 return Error(Loc, "invalid getelementptr indices");
3604 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003605 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003606 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 return false;
3608}
3609
3610/// ParseExtractValue
3611/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3612bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3613 Value *Val; LocTy Loc;
3614 SmallVector<unsigned, 4> Indices;
3615 if (ParseTypeAndValue(Val, Loc, PFS) ||
3616 ParseIndexList(Indices))
3617 return true;
3618
3619 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3620 return Error(Loc, "extractvalue operand must be array or struct");
3621
3622 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3623 Indices.end()))
3624 return Error(Loc, "invalid indices for extractvalue");
3625 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3626 return false;
3627}
3628
3629/// ParseInsertValue
3630/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3631bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3632 Value *Val0, *Val1; LocTy Loc0, Loc1;
3633 SmallVector<unsigned, 4> Indices;
3634 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3635 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3636 ParseTypeAndValue(Val1, Loc1, PFS) ||
3637 ParseIndexList(Indices))
3638 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003639
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3641 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003642
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3644 Indices.end()))
3645 return Error(Loc0, "invalid indices for insertvalue");
3646 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3647 return false;
3648}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003649
3650//===----------------------------------------------------------------------===//
3651// Embedded metadata.
3652//===----------------------------------------------------------------------===//
3653
3654/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003655/// ::= Element (',' Element)*
3656/// Element
3657/// ::= 'null' | TypeAndValue
3658bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003659 assert(Lex.getKind() == lltok::lbrace);
3660 Lex.Lex();
3661 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003662 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003663 if (Lex.getKind() == lltok::kw_null) {
3664 Lex.Lex();
3665 V = 0;
3666 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003667 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003668 if (ParseType(Ty)) return true;
3669 if (Lex.getKind() == lltok::Metadata) {
3670 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003671 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003672 if (!ParseMDNode(Node))
3673 V = Node;
3674 else {
3675 MetadataBase *MDS = 0;
3676 if (ParseMDString(MDS)) return true;
3677 V = MDS;
3678 }
3679 } else {
3680 Constant *C;
3681 if (ParseGlobalValue(Ty, C)) return true;
3682 V = C;
3683 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003684 }
3685 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003686 } while (EatIfPresent(lltok::comma));
3687
3688 return false;
3689}