blob: d6cda3ccf042f1c150657766b48ec63737a9302e [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() {
Devang Patelf633a062009-09-17 23:04:48 +00001054
Devang Patel0475c912009-09-29 00:01:14 +00001055 std::string Name;
1056 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1057 Name = Lex.getStrVal();
1058 Lex.Lex();
1059 } else
Devang Patelf633a062009-09-17 23:04:48 +00001060 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001061
Devang Patelf633a062009-09-17 23:04:48 +00001062 if (Lex.getKind() != lltok::Metadata)
1063 return TokError("Expected '!' here");
1064 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001065
Devang Patelf633a062009-09-17 23:04:48 +00001066 MetadataBase *Node;
1067 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001068
Devang Patele30e6782009-09-28 21:41:20 +00001069 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patel0475c912009-09-29 00:01:14 +00001070 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1071 if (!MDK)
1072 MDK = TheMetadata.RegisterMDKind(Name.c_str());
1073 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001074
Devang Patelf633a062009-09-17 23:04:48 +00001075 return false;
1076}
1077
Chris Lattnerdf986172009-01-02 07:01:27 +00001078/// ParseOptionalAlignment
1079/// ::= /* empty */
1080/// ::= 'align' 4
1081bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1082 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001083 if (!EatIfPresent(lltok::kw_align))
1084 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001085 LocTy AlignLoc = Lex.getLoc();
1086 if (ParseUInt32(Alignment)) return true;
1087 if (!isPowerOf2_32(Alignment))
1088 return Error(AlignLoc, "alignment is not a power of two");
1089 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001090}
1091
Devang Patelf633a062009-09-17 23:04:48 +00001092/// ParseOptionalInfo
1093/// ::= OptionalInfo (',' OptionalInfo)+
1094bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1095
1096 // FIXME: Handle customized metadata info attached with an instruction.
1097 do {
Devang Patel0475c912009-09-29 00:01:14 +00001098 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1099 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001100 } else if (Lex.getKind() == lltok::kw_align) {
1101 if (ParseOptionalAlignment(Alignment)) return true;
1102 } else
1103 return true;
1104 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001105
Devang Patelf633a062009-09-17 23:04:48 +00001106 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001107}
1108
Devang Patelf633a062009-09-17 23:04:48 +00001109
Chris Lattnerdf986172009-01-02 07:01:27 +00001110/// ParseIndexList
1111/// ::= (',' uint32)+
1112bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1113 if (Lex.getKind() != lltok::comma)
1114 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001116 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001117 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001118 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001119 Indices.push_back(Idx);
1120 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001121
Chris Lattnerdf986172009-01-02 07:01:27 +00001122 return false;
1123}
1124
1125//===----------------------------------------------------------------------===//
1126// Type Parsing.
1127//===----------------------------------------------------------------------===//
1128
1129/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001130bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1131 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001132 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001133
Chris Lattnerdf986172009-01-02 07:01:27 +00001134 // Verify no unresolved uprefs.
1135 if (!UpRefs.empty())
1136 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001137
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001138 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001139 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 return false;
1142}
1143
1144/// HandleUpRefs - Every time we finish a new layer of types, this function is
1145/// called. It loops through the UpRefs vector, which is a list of the
1146/// currently active types. For each type, if the up-reference is contained in
1147/// the newly completed type, we decrement the level count. When the level
1148/// count reaches zero, the up-referenced type is the type that is passed in:
1149/// thus we can complete the cycle.
1150///
1151PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1152 // If Ty isn't abstract, or if there are no up-references in it, then there is
1153 // nothing to resolve here.
1154 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001155
Chris Lattnerdf986172009-01-02 07:01:27 +00001156 PATypeHolder Ty(ty);
1157#if 0
1158 errs() << "Type '" << Ty->getDescription()
1159 << "' newly formed. Resolving upreferences.\n"
1160 << UpRefs.size() << " upreferences active!\n";
1161#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001162
Chris Lattnerdf986172009-01-02 07:01:27 +00001163 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1164 // to zero), we resolve them all together before we resolve them to Ty. At
1165 // the end of the loop, if there is anything to resolve to Ty, it will be in
1166 // this variable.
1167 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168
Chris Lattnerdf986172009-01-02 07:01:27 +00001169 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1170 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1171 bool ContainsType =
1172 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1173 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001174
Chris Lattnerdf986172009-01-02 07:01:27 +00001175#if 0
1176 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1177 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1178 << (ContainsType ? "true" : "false")
1179 << " level=" << UpRefs[i].NestingLevel << "\n";
1180#endif
1181 if (!ContainsType)
1182 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001183
Chris Lattnerdf986172009-01-02 07:01:27 +00001184 // Decrement level of upreference
1185 unsigned Level = --UpRefs[i].NestingLevel;
1186 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1189 if (Level != 0)
1190 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001191
Chris Lattnerdf986172009-01-02 07:01:27 +00001192#if 0
1193 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1194#endif
1195 if (!TypeToResolve)
1196 TypeToResolve = UpRefs[i].UpRefTy;
1197 else
1198 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1199 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1200 --i; // Do not skip the next element.
1201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattnerdf986172009-01-02 07:01:27 +00001203 if (TypeToResolve)
1204 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001205
Chris Lattnerdf986172009-01-02 07:01:27 +00001206 return Ty;
1207}
1208
1209
1210/// ParseTypeRec - The recursive function used to process the internal
1211/// implementation details of types.
1212bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1213 switch (Lex.getKind()) {
1214 default:
1215 return TokError("expected type");
1216 case lltok::Type:
1217 // TypeRec ::= 'float' | 'void' (etc)
1218 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001220 break;
1221 case lltok::kw_opaque:
1222 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001223 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001224 Lex.Lex();
1225 break;
1226 case lltok::lbrace:
1227 // TypeRec ::= '{' ... '}'
1228 if (ParseStructType(Result, false))
1229 return true;
1230 break;
1231 case lltok::lsquare:
1232 // TypeRec ::= '[' ... ']'
1233 Lex.Lex(); // eat the lsquare.
1234 if (ParseArrayVectorType(Result, false))
1235 return true;
1236 break;
1237 case lltok::less: // Either vector or packed struct.
1238 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001239 Lex.Lex();
1240 if (Lex.getKind() == lltok::lbrace) {
1241 if (ParseStructType(Result, true) ||
1242 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 } else if (ParseArrayVectorType(Result, true))
1245 return true;
1246 break;
1247 case lltok::LocalVar:
1248 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1249 // TypeRec ::= %foo
1250 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1251 Result = T;
1252 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001253 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1255 std::make_pair(Result,
1256 Lex.getLoc())));
1257 M->addTypeName(Lex.getStrVal(), Result.get());
1258 }
1259 Lex.Lex();
1260 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001261
Chris Lattnerdf986172009-01-02 07:01:27 +00001262 case lltok::LocalVarID:
1263 // TypeRec ::= %4
1264 if (Lex.getUIntVal() < NumberedTypes.size())
1265 Result = NumberedTypes[Lex.getUIntVal()];
1266 else {
1267 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1268 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1269 if (I != ForwardRefTypeIDs.end())
1270 Result = I->second.first;
1271 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001272 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001273 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1274 std::make_pair(Result,
1275 Lex.getLoc())));
1276 }
1277 }
1278 Lex.Lex();
1279 break;
1280 case lltok::backslash: {
1281 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001282 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001283 unsigned Val;
1284 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001285 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1287 Result = OT;
1288 break;
1289 }
1290 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
1292 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 while (1) {
1294 switch (Lex.getKind()) {
1295 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001297
1298 // TypeRec ::= TypeRec '*'
1299 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001300 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001302 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001303 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001304 if (!PointerType::isValidElementType(Result.get()))
1305 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001306 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001307 Lex.Lex();
1308 break;
1309
1310 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1311 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001312 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001314 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001315 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001316 if (!PointerType::isValidElementType(Result.get()))
1317 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001318 unsigned AddrSpace;
1319 if (ParseOptionalAddrSpace(AddrSpace) ||
1320 ParseToken(lltok::star, "expected '*' in address space"))
1321 return true;
1322
Owen Andersondebcb012009-07-29 22:17:13 +00001323 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 break;
1325 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001326
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1328 case lltok::lparen:
1329 if (ParseFunctionType(Result))
1330 return true;
1331 break;
1332 }
1333 }
1334}
1335
1336/// ParseParameterList
1337/// ::= '(' ')'
1338/// ::= '(' Arg (',' Arg)* ')'
1339/// Arg
1340/// ::= Type OptionalAttributes Value OptionalAttributes
1341bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1342 PerFunctionState &PFS) {
1343 if (ParseToken(lltok::lparen, "expected '(' in call"))
1344 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 while (Lex.getKind() != lltok::rparen) {
1347 // If this isn't the first argument, we need a comma.
1348 if (!ArgList.empty() &&
1349 ParseToken(lltok::comma, "expected ',' in argument list"))
1350 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001351
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 // Parse the argument.
1353 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001354 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 unsigned ArgAttrs1, ArgAttrs2;
1356 Value *V;
1357 if (ParseType(ArgTy, ArgLoc) ||
1358 ParseOptionalAttrs(ArgAttrs1, 0) ||
1359 ParseValue(ArgTy, V, PFS) ||
1360 // FIXME: Should not allow attributes after the argument, remove this in
1361 // LLVM 3.0.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +00001362 ParseOptionalAttrs(ArgAttrs2, 3))
Chris Lattnerdf986172009-01-02 07:01:27 +00001363 return true;
1364 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1365 }
1366
1367 Lex.Lex(); // Lex the ')'.
1368 return false;
1369}
1370
1371
1372
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001373/// ParseArgumentList - Parse the argument list for a function type or function
1374/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001375/// ::= '(' ArgTypeListI ')'
1376/// ArgTypeListI
1377/// ::= /*empty*/
1378/// ::= '...'
1379/// ::= ArgTypeList ',' '...'
1380/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001381///
Chris Lattnerdf986172009-01-02 07:01:27 +00001382bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001383 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001384 isVarArg = false;
1385 assert(Lex.getKind() == lltok::lparen);
1386 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 if (Lex.getKind() == lltok::rparen) {
1389 // empty
1390 } else if (Lex.getKind() == lltok::dotdotdot) {
1391 isVarArg = true;
1392 Lex.Lex();
1393 } else {
1394 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001395 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001397 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001398
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001399 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1400 // types (such as a function returning a pointer to itself). If parsing a
1401 // function prototype, we require fully resolved types.
1402 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001403 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001405 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001406 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001407
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 if (Lex.getKind() == lltok::LocalVar ||
1409 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1410 Name = Lex.getStrVal();
1411 Lex.Lex();
1412 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001413
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001414 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001415 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416
Chris Lattnerdf986172009-01-02 07:01:27 +00001417 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001418
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001419 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001421 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001422 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001423 break;
1424 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001425
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 // Otherwise must be an argument type.
1427 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001428 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001429 ParseOptionalAttrs(Attrs, 0)) return true;
1430
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001431 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001432 return Error(TypeLoc, "argument can not have void type");
1433
Chris Lattnerdf986172009-01-02 07:01:27 +00001434 if (Lex.getKind() == lltok::LocalVar ||
1435 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1436 Name = Lex.getStrVal();
1437 Lex.Lex();
1438 } else {
1439 Name = "";
1440 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001441
1442 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1443 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001444
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1446 }
1447 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001449 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001450}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001451
Chris Lattnerdf986172009-01-02 07:01:27 +00001452/// ParseFunctionType
1453/// ::= Type ArgumentList OptionalAttrs
1454bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1455 assert(Lex.getKind() == lltok::lparen);
1456
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001457 if (!FunctionType::isValidReturnType(Result))
1458 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 std::vector<ArgInfo> ArgList;
1461 bool isVarArg;
1462 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001463 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001464 // FIXME: Allow, but ignore attributes on function types!
1465 // FIXME: Remove in LLVM 3.0
1466 ParseOptionalAttrs(Attrs, 2))
1467 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001468
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 // Reject names on the arguments lists.
1470 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1471 if (!ArgList[i].Name.empty())
1472 return Error(ArgList[i].Loc, "argument name invalid in function type");
1473 if (!ArgList[i].Attrs != 0) {
1474 // Allow but ignore attributes on function types; this permits
1475 // auto-upgrade.
1476 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1477 }
1478 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattnerdf986172009-01-02 07:01:27 +00001480 std::vector<const Type*> ArgListTy;
1481 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1482 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001483
Owen Andersondebcb012009-07-29 22:17:13 +00001484 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001485 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001486 return false;
1487}
1488
1489/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1490/// TypeRec
1491/// ::= '{' '}'
1492/// ::= '{' TypeRec (',' TypeRec)* '}'
1493/// ::= '<' '{' '}' '>'
1494/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1495bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1496 assert(Lex.getKind() == lltok::lbrace);
1497 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001498
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001499 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001500 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 return false;
1502 }
1503
1504 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001505 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001506 if (ParseTypeRec(Result)) return true;
1507 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001508
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001509 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001510 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001511 if (!StructType::isValidElementType(Result))
1512 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001513
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001514 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001515 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001516 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001518 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001519 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001520 if (!StructType::isValidElementType(Result))
1521 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnerdf986172009-01-02 07:01:27 +00001523 ParamsList.push_back(Result);
1524 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001526 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1527 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001528
Chris Lattnerdf986172009-01-02 07:01:27 +00001529 std::vector<const Type*> ParamsListTy;
1530 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1531 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001532 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001533 return false;
1534}
1535
1536/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1537/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001539/// ::= '[' APSINTVAL 'x' Types ']'
1540/// ::= '<' APSINTVAL 'x' Types '>'
1541bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1542 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1543 Lex.getAPSIntVal().getBitWidth() > 64)
1544 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 LocTy SizeLoc = Lex.getLoc();
1547 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001548 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001550 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1551 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001552
1553 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001554 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001555 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001557 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001558 return Error(TypeLoc, "array and vector element type cannot be void");
1559
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001560 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1561 "expected end of sequential type"))
1562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnerdf986172009-01-02 07:01:27 +00001564 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001565 if (Size == 0)
1566 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001567 if ((unsigned)Size != Size)
1568 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001569 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001570 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001571 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001573 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001574 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001575 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001576 }
1577 return false;
1578}
1579
1580//===----------------------------------------------------------------------===//
1581// Function Semantic Analysis.
1582//===----------------------------------------------------------------------===//
1583
1584LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1585 : P(p), F(f) {
1586
1587 // Insert unnamed arguments into the NumberedVals list.
1588 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1589 AI != E; ++AI)
1590 if (!AI->hasName())
1591 NumberedVals.push_back(AI);
1592}
1593
1594LLParser::PerFunctionState::~PerFunctionState() {
1595 // If there were any forward referenced non-basicblock values, delete them.
1596 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1597 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1598 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001599 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001600 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001601 delete I->second.first;
1602 I->second.first = 0;
1603 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1606 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1607 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001608 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001609 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 delete I->second.first;
1611 I->second.first = 0;
1612 }
1613}
1614
1615bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1616 if (!ForwardRefVals.empty())
1617 return P.Error(ForwardRefVals.begin()->second.second,
1618 "use of undefined value '%" + ForwardRefVals.begin()->first +
1619 "'");
1620 if (!ForwardRefValIDs.empty())
1621 return P.Error(ForwardRefValIDs.begin()->second.second,
1622 "use of undefined value '%" +
1623 utostr(ForwardRefValIDs.begin()->first) + "'");
1624 return false;
1625}
1626
1627
1628/// GetVal - Get a value with the specified name or ID, creating a
1629/// forward reference record if needed. This can return null if the value
1630/// exists but does not have the right type.
1631Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1632 const Type *Ty, LocTy Loc) {
1633 // Look this name up in the normal function symbol table.
1634 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattnerdf986172009-01-02 07:01:27 +00001636 // If this is a forward reference for the value, see if we already created a
1637 // forward ref record.
1638 if (Val == 0) {
1639 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1640 I = ForwardRefVals.find(Name);
1641 if (I != ForwardRefVals.end())
1642 Val = I->second.first;
1643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattnerdf986172009-01-02 07:01:27 +00001645 // If we have the value in the symbol table or fwd-ref table, return it.
1646 if (Val) {
1647 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001648 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001649 P.Error(Loc, "'%" + Name + "' is not a basic block");
1650 else
1651 P.Error(Loc, "'%" + Name + "' defined with type '" +
1652 Val->getType()->getDescription() + "'");
1653 return 0;
1654 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnerdf986172009-01-02 07:01:27 +00001656 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001657 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1658 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001659 P.Error(Loc, "invalid use of a non-first-class type");
1660 return 0;
1661 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001662
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 // Otherwise, create a new forward reference for this value and remember it.
1664 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001665 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001666 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001667 else
1668 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001669
Chris Lattnerdf986172009-01-02 07:01:27 +00001670 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1671 return FwdVal;
1672}
1673
1674Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1675 LocTy Loc) {
1676 // Look this name up in the normal function symbol table.
1677 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001678
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 // If this is a forward reference for the value, see if we already created a
1680 // forward ref record.
1681 if (Val == 0) {
1682 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1683 I = ForwardRefValIDs.find(ID);
1684 if (I != ForwardRefValIDs.end())
1685 Val = I->second.first;
1686 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001687
Chris Lattnerdf986172009-01-02 07:01:27 +00001688 // If we have the value in the symbol table or fwd-ref table, return it.
1689 if (Val) {
1690 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001691 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1693 else
1694 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1695 Val->getType()->getDescription() + "'");
1696 return 0;
1697 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Owen Anderson1d0be152009-08-13 21:58:54 +00001699 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1700 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 P.Error(Loc, "invalid use of a non-first-class type");
1702 return 0;
1703 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001704
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 // Otherwise, create a new forward reference for this value and remember it.
1706 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001707 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001708 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 else
1710 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Chris Lattnerdf986172009-01-02 07:01:27 +00001712 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1713 return FwdVal;
1714}
1715
1716/// SetInstName - After an instruction is parsed and inserted into its
1717/// basic block, this installs its name.
1718bool LLParser::PerFunctionState::SetInstName(int NameID,
1719 const std::string &NameStr,
1720 LocTy NameLoc, Instruction *Inst) {
1721 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001722 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 if (NameID != -1 || !NameStr.empty())
1724 return P.Error(NameLoc, "instructions returning void cannot have a name");
1725 return false;
1726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001727
Chris Lattnerdf986172009-01-02 07:01:27 +00001728 // If this was a numbered instruction, verify that the instruction is the
1729 // expected value and resolve any forward references.
1730 if (NameStr.empty()) {
1731 // If neither a name nor an ID was specified, just use the next ID.
1732 if (NameID == -1)
1733 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001734
Chris Lattnerdf986172009-01-02 07:01:27 +00001735 if (unsigned(NameID) != NumberedVals.size())
1736 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1737 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001738
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1740 ForwardRefValIDs.find(NameID);
1741 if (FI != ForwardRefValIDs.end()) {
1742 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001743 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001744 FI->second.first->getType()->getDescription() + "'");
1745 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001746 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 ForwardRefValIDs.erase(FI);
1748 }
1749
1750 NumberedVals.push_back(Inst);
1751 return false;
1752 }
1753
1754 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1755 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1756 FI = ForwardRefVals.find(NameStr);
1757 if (FI != ForwardRefVals.end()) {
1758 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001759 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 FI->second.first->getType()->getDescription() + "'");
1761 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001762 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 ForwardRefVals.erase(FI);
1764 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001765
Chris Lattnerdf986172009-01-02 07:01:27 +00001766 // Set the name on the instruction.
1767 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001768
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001770 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001771 NameStr + "'");
1772 return false;
1773}
1774
1775/// GetBB - Get a basic block with the specified name or ID, creating a
1776/// forward reference record if needed.
1777BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1778 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001779 return cast_or_null<BasicBlock>(GetVal(Name,
1780 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001781}
1782
1783BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001784 return cast_or_null<BasicBlock>(GetVal(ID,
1785 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001786}
1787
1788/// DefineBB - Define the specified basic block, which is either named or
1789/// unnamed. If there is an error, this returns null otherwise it returns
1790/// the block being defined.
1791BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1792 LocTy Loc) {
1793 BasicBlock *BB;
1794 if (Name.empty())
1795 BB = GetBB(NumberedVals.size(), Loc);
1796 else
1797 BB = GetBB(Name, Loc);
1798 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001799
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 // Move the block to the end of the function. Forward ref'd blocks are
1801 // inserted wherever they happen to be referenced.
1802 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001803
Chris Lattnerdf986172009-01-02 07:01:27 +00001804 // Remove the block from forward ref sets.
1805 if (Name.empty()) {
1806 ForwardRefValIDs.erase(NumberedVals.size());
1807 NumberedVals.push_back(BB);
1808 } else {
1809 // BB forward references are already in the function symbol table.
1810 ForwardRefVals.erase(Name);
1811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001812
Chris Lattnerdf986172009-01-02 07:01:27 +00001813 return BB;
1814}
1815
1816//===----------------------------------------------------------------------===//
1817// Constants.
1818//===----------------------------------------------------------------------===//
1819
1820/// ParseValID - Parse an abstract value that doesn't necessarily have a
1821/// type implied. For example, if we parse "4" we don't know what integer type
1822/// it has. The value will later be combined with its type and checked for
1823/// sanity.
1824bool LLParser::ParseValID(ValID &ID) {
1825 ID.Loc = Lex.getLoc();
1826 switch (Lex.getKind()) {
1827 default: return TokError("expected value token");
1828 case lltok::GlobalID: // @42
1829 ID.UIntVal = Lex.getUIntVal();
1830 ID.Kind = ValID::t_GlobalID;
1831 break;
1832 case lltok::GlobalVar: // @foo
1833 ID.StrVal = Lex.getStrVal();
1834 ID.Kind = ValID::t_GlobalName;
1835 break;
1836 case lltok::LocalVarID: // %42
1837 ID.UIntVal = Lex.getUIntVal();
1838 ID.Kind = ValID::t_LocalID;
1839 break;
1840 case lltok::LocalVar: // %foo
1841 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1842 ID.StrVal = Lex.getStrVal();
1843 ID.Kind = ValID::t_LocalName;
1844 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001845 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001846 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001847 Lex.Lex();
1848 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001849 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001850 if (ParseMDNodeVector(Elts) ||
1851 ParseToken(lltok::rbrace, "expected end of metadata node"))
1852 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001853
Owen Anderson647e3012009-07-31 21:35:40 +00001854 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001855 return false;
1856 }
1857
Devang Patel923078c2009-07-01 19:21:12 +00001858 // Standalone metadata reference
1859 // !{ ..., !42, ... }
Devang Patel104cf9e2009-07-23 01:07:34 +00001860 if (!ParseMDNode(ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001861 return false;
Devang Patel256be962009-07-20 19:00:08 +00001862
Nick Lewycky21cc4462009-04-04 07:22:01 +00001863 // MDString:
1864 // ::= '!' STRINGCONSTANT
Devang Patele54abc92009-07-22 17:43:22 +00001865 if (ParseMDString(ID.MetadataVal)) return true;
1866 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001867 return false;
1868 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001871 ID.Kind = ValID::t_APSInt;
1872 break;
1873 case lltok::APFloat:
1874 ID.APFloatVal = Lex.getAPFloatVal();
1875 ID.Kind = ValID::t_APFloat;
1876 break;
1877 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001878 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 ID.Kind = ValID::t_Constant;
1880 break;
1881 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001882 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001883 ID.Kind = ValID::t_Constant;
1884 break;
1885 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1886 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1887 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888
Chris Lattnerdf986172009-01-02 07:01:27 +00001889 case lltok::lbrace: {
1890 // ValID ::= '{' ConstVector '}'
1891 Lex.Lex();
1892 SmallVector<Constant*, 16> Elts;
1893 if (ParseGlobalValueVector(Elts) ||
1894 ParseToken(lltok::rbrace, "expected end of struct constant"))
1895 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001897 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1898 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001899 ID.Kind = ValID::t_Constant;
1900 return false;
1901 }
1902 case lltok::less: {
1903 // ValID ::= '<' ConstVector '>' --> Vector.
1904 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1905 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001906 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907
Chris Lattnerdf986172009-01-02 07:01:27 +00001908 SmallVector<Constant*, 16> Elts;
1909 LocTy FirstEltLoc = Lex.getLoc();
1910 if (ParseGlobalValueVector(Elts) ||
1911 (isPackedStruct &&
1912 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1913 ParseToken(lltok::greater, "expected end of constant"))
1914 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001917 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001918 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 ID.Kind = ValID::t_Constant;
1920 return false;
1921 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001922
Chris Lattnerdf986172009-01-02 07:01:27 +00001923 if (Elts.empty())
1924 return Error(ID.Loc, "constant vector must not be empty");
1925
1926 if (!Elts[0]->getType()->isInteger() &&
1927 !Elts[0]->getType()->isFloatingPoint())
1928 return Error(FirstEltLoc,
1929 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 // Verify that all the vector elements have the same type.
1932 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1933 if (Elts[i]->getType() != Elts[0]->getType())
1934 return Error(FirstEltLoc,
1935 "vector element #" + utostr(i) +
1936 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937
Owen Andersonaf7ec972009-07-28 21:19:26 +00001938 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 ID.Kind = ValID::t_Constant;
1940 return false;
1941 }
1942 case lltok::lsquare: { // Array Constant
1943 Lex.Lex();
1944 SmallVector<Constant*, 16> Elts;
1945 LocTy FirstEltLoc = Lex.getLoc();
1946 if (ParseGlobalValueVector(Elts) ||
1947 ParseToken(lltok::rsquare, "expected end of array constant"))
1948 return true;
1949
1950 // Handle empty element.
1951 if (Elts.empty()) {
1952 // Use undef instead of an array because it's inconvenient to determine
1953 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001954 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001955 return false;
1956 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00001960 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001961
Owen Andersondebcb012009-07-29 22:17:13 +00001962 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001963
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00001965 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 if (Elts[i]->getType() != Elts[0]->getType())
1967 return Error(FirstEltLoc,
1968 "array element #" + utostr(i) +
1969 " is not of type '" +Elts[0]->getType()->getDescription());
1970 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001971
Owen Anderson1fd70962009-07-28 18:32:17 +00001972 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 ID.Kind = ValID::t_Constant;
1974 return false;
1975 }
1976 case lltok::kw_c: // c "foo"
1977 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00001978 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1980 ID.Kind = ValID::t_Constant;
1981 return false;
1982
1983 case lltok::kw_asm: {
Dale Johannesen43602982009-10-13 20:46:56 +00001984 // ValID ::= 'asm' SideEffect? MsAsm? STRINGCONSTANT ',' STRINGCONSTANT
1985 bool HasSideEffect, MsAsm;
Chris Lattnerdf986172009-01-02 07:01:27 +00001986 Lex.Lex();
1987 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen43602982009-10-13 20:46:56 +00001988 ParseOptionalToken(lltok::kw_msasm, MsAsm) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001989 ParseStringConstant(ID.StrVal) ||
1990 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001991 ParseToken(lltok::StringConstant, "expected constraint string"))
1992 return true;
1993 ID.StrVal2 = Lex.getStrVal();
Dale Johannesen43602982009-10-13 20:46:56 +00001994 ID.UIntVal = HasSideEffect | ((unsigned)MsAsm<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00001995 ID.Kind = ValID::t_InlineAsm;
1996 return false;
1997 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001998
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 case lltok::kw_trunc:
2000 case lltok::kw_zext:
2001 case lltok::kw_sext:
2002 case lltok::kw_fptrunc:
2003 case lltok::kw_fpext:
2004 case lltok::kw_bitcast:
2005 case lltok::kw_uitofp:
2006 case lltok::kw_sitofp:
2007 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002012 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002013 Constant *SrcVal;
2014 Lex.Lex();
2015 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2016 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002017 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002018 ParseType(DestTy) ||
2019 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2020 return true;
2021 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2022 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2023 SrcVal->getType()->getDescription() + "' to '" +
2024 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002025 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002026 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002027 ID.Kind = ValID::t_Constant;
2028 return false;
2029 }
2030 case lltok::kw_extractvalue: {
2031 Lex.Lex();
2032 Constant *Val;
2033 SmallVector<unsigned, 4> Indices;
2034 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2035 ParseGlobalTypeAndValue(Val) ||
2036 ParseIndexList(Indices) ||
2037 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2038 return true;
2039 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2040 return Error(ID.Loc, "extractvalue operand must be array or struct");
2041 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2042 Indices.end()))
2043 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002044 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002045 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002046 ID.Kind = ValID::t_Constant;
2047 return false;
2048 }
2049 case lltok::kw_insertvalue: {
2050 Lex.Lex();
2051 Constant *Val0, *Val1;
2052 SmallVector<unsigned, 4> Indices;
2053 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2054 ParseGlobalTypeAndValue(Val0) ||
2055 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2056 ParseGlobalTypeAndValue(Val1) ||
2057 ParseIndexList(Indices) ||
2058 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2059 return true;
2060 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2061 return Error(ID.Loc, "extractvalue operand must be array or struct");
2062 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2063 Indices.end()))
2064 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002065 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002066 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 ID.Kind = ValID::t_Constant;
2068 return false;
2069 }
2070 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002071 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 unsigned PredVal, Opc = Lex.getUIntVal();
2073 Constant *Val0, *Val1;
2074 Lex.Lex();
2075 if (ParseCmpPredicate(PredVal, Opc) ||
2076 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2077 ParseGlobalTypeAndValue(Val0) ||
2078 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2079 ParseGlobalTypeAndValue(Val1) ||
2080 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2081 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082
Chris Lattnerdf986172009-01-02 07:01:27 +00002083 if (Val0->getType() != Val1->getType())
2084 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002085
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002087
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 if (Opc == Instruction::FCmp) {
2089 if (!Val0->getType()->isFPOrFPVector())
2090 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002091 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002092 } else {
2093 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002094 if (!Val0->getType()->isIntOrIntVector() &&
2095 !isa<PointerType>(Val0->getType()))
2096 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002097 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002098 }
2099 ID.Kind = ValID::t_Constant;
2100 return false;
2101 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002102
Chris Lattnerdf986172009-01-02 07:01:27 +00002103 // Binary Operators.
2104 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002105 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002107 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002108 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002109 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002110 case lltok::kw_udiv:
2111 case lltok::kw_sdiv:
2112 case lltok::kw_fdiv:
2113 case lltok::kw_urem:
2114 case lltok::kw_srem:
2115 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002116 bool NUW = false;
2117 bool NSW = false;
2118 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 unsigned Opc = Lex.getUIntVal();
2120 Constant *Val0, *Val1;
2121 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002122 LocTy ModifierLoc = Lex.getLoc();
2123 if (Opc == Instruction::Add ||
2124 Opc == Instruction::Sub ||
2125 Opc == Instruction::Mul) {
2126 if (EatIfPresent(lltok::kw_nuw))
2127 NUW = true;
2128 if (EatIfPresent(lltok::kw_nsw)) {
2129 NSW = true;
2130 if (EatIfPresent(lltok::kw_nuw))
2131 NUW = true;
2132 }
2133 } else if (Opc == Instruction::SDiv) {
2134 if (EatIfPresent(lltok::kw_exact))
2135 Exact = true;
2136 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2138 ParseGlobalTypeAndValue(Val0) ||
2139 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2140 ParseGlobalTypeAndValue(Val1) ||
2141 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2142 return true;
2143 if (Val0->getType() != Val1->getType())
2144 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002145 if (!Val0->getType()->isIntOrIntVector()) {
2146 if (NUW)
2147 return Error(ModifierLoc, "nuw only applies to integer operations");
2148 if (NSW)
2149 return Error(ModifierLoc, "nsw only applies to integer operations");
2150 }
2151 // API compatibility: Accept either integer or floating-point types with
2152 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 if (!Val0->getType()->isIntOrIntVector() &&
2154 !Val0->getType()->isFPOrFPVector())
2155 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002156 unsigned Flags = 0;
2157 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2158 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2159 if (Exact) Flags |= SDivOperator::IsExact;
2160 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002161 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002162 ID.Kind = ValID::t_Constant;
2163 return false;
2164 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002165
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 // Logical Operations
2167 case lltok::kw_shl:
2168 case lltok::kw_lshr:
2169 case lltok::kw_ashr:
2170 case lltok::kw_and:
2171 case lltok::kw_or:
2172 case lltok::kw_xor: {
2173 unsigned Opc = Lex.getUIntVal();
2174 Constant *Val0, *Val1;
2175 Lex.Lex();
2176 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2177 ParseGlobalTypeAndValue(Val0) ||
2178 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2179 ParseGlobalTypeAndValue(Val1) ||
2180 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2181 return true;
2182 if (Val0->getType() != Val1->getType())
2183 return Error(ID.Loc, "operands of constexpr must have same type");
2184 if (!Val0->getType()->isIntOrIntVector())
2185 return Error(ID.Loc,
2186 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002187 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002188 ID.Kind = ValID::t_Constant;
2189 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190 }
2191
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 case lltok::kw_getelementptr:
2193 case lltok::kw_shufflevector:
2194 case lltok::kw_insertelement:
2195 case lltok::kw_extractelement:
2196 case lltok::kw_select: {
2197 unsigned Opc = Lex.getUIntVal();
2198 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002199 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002201 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002202 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2204 ParseGlobalValueVector(Elts) ||
2205 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2206 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002207
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 if (Opc == Instruction::GetElementPtr) {
2209 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2210 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211
Chris Lattnerdf986172009-01-02 07:01:27 +00002212 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002213 (Value**)(Elts.data() + 1),
2214 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002216 ID.ConstantVal = InBounds ?
2217 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2218 Elts.data() + 1,
2219 Elts.size() - 1) :
2220 ConstantExpr::getGetElementPtr(Elts[0],
2221 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 } else if (Opc == Instruction::Select) {
2223 if (Elts.size() != 3)
2224 return Error(ID.Loc, "expected three operands to select");
2225 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2226 Elts[2]))
2227 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002228 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 } else if (Opc == Instruction::ShuffleVector) {
2230 if (Elts.size() != 3)
2231 return Error(ID.Loc, "expected three operands to shufflevector");
2232 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2233 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002234 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002235 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002236 } else if (Opc == Instruction::ExtractElement) {
2237 if (Elts.size() != 2)
2238 return Error(ID.Loc, "expected two operands to extractelement");
2239 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2240 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002241 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002242 } else {
2243 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2244 if (Elts.size() != 3)
2245 return Error(ID.Loc, "expected three operands to insertelement");
2246 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2247 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002248 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002249 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 ID.Kind = ValID::t_Constant;
2253 return false;
2254 }
2255 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002256
Chris Lattnerdf986172009-01-02 07:01:27 +00002257 Lex.Lex();
2258 return false;
2259}
2260
2261/// ParseGlobalValue - Parse a global value with the specified type.
2262bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2263 V = 0;
2264 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002265 return ParseValID(ID) ||
2266 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002267}
2268
2269/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2270/// constant.
2271bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2272 Constant *&V) {
2273 if (isa<FunctionType>(Ty))
2274 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002275
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002277 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002278 case ValID::t_Metadata:
2279 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 case ValID::t_LocalID:
2281 case ValID::t_LocalName:
2282 return Error(ID.Loc, "invalid use of function-local name");
2283 case ValID::t_InlineAsm:
2284 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2285 case ValID::t_GlobalName:
2286 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2287 return V == 0;
2288 case ValID::t_GlobalID:
2289 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2290 return V == 0;
2291 case ValID::t_APSInt:
2292 if (!isa<IntegerType>(Ty))
2293 return Error(ID.Loc, "integer constant must have integer type");
2294 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002295 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 return false;
2297 case ValID::t_APFloat:
2298 if (!Ty->isFloatingPoint() ||
2299 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2300 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002301
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 // The lexer has no type info, so builds all float and double FP constants
2303 // as double. Fix this here. Long double does not need this.
2304 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002305 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 bool Ignored;
2307 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2308 &Ignored);
2309 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002310 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002311
Chris Lattner959873d2009-01-05 18:24:23 +00002312 if (V->getType() != Ty)
2313 return Error(ID.Loc, "floating point constant does not have type '" +
2314 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002315
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 return false;
2317 case ValID::t_Null:
2318 if (!isa<PointerType>(Ty))
2319 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002320 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 return false;
2322 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002323 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002324 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002325 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002326 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002327 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002329 case ValID::t_EmptyArray:
2330 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2331 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002332 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002333 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002334 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002335 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002336 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002338 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 return false;
2340 case ValID::t_Constant:
2341 if (ID.ConstantVal->getType() != Ty)
2342 return Error(ID.Loc, "constant expression type mismatch");
2343 V = ID.ConstantVal;
2344 return false;
2345 }
2346}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002347
Chris Lattnerdf986172009-01-02 07:01:27 +00002348bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002349 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 return ParseType(Type) ||
2351 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002352}
Chris Lattnerdf986172009-01-02 07:01:27 +00002353
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002354/// ParseGlobalValueVector
2355/// ::= /*empty*/
2356/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002357bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2358 // Empty list.
2359 if (Lex.getKind() == lltok::rbrace ||
2360 Lex.getKind() == lltok::rsquare ||
2361 Lex.getKind() == lltok::greater ||
2362 Lex.getKind() == lltok::rparen)
2363 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 Constant *C;
2366 if (ParseGlobalTypeAndValue(C)) return true;
2367 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002368
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002369 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 if (ParseGlobalTypeAndValue(C)) return true;
2371 Elts.push_back(C);
2372 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002373
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 return false;
2375}
2376
2377
2378//===----------------------------------------------------------------------===//
2379// Function Parsing.
2380//===----------------------------------------------------------------------===//
2381
2382bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2383 PerFunctionState &PFS) {
2384 if (ID.Kind == ValID::t_LocalID)
2385 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2386 else if (ID.Kind == ValID::t_LocalName)
2387 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002388 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002389 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2390 const FunctionType *FTy =
2391 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2392 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2393 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002394 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002396 } else if (ID.Kind == ValID::t_Metadata) {
2397 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002398 } else {
2399 Constant *C;
2400 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2401 V = C;
2402 return false;
2403 }
2404
2405 return V == 0;
2406}
2407
2408bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2409 V = 0;
2410 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002411 return ParseValID(ID) ||
2412 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002413}
2414
2415bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002416 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002417 return ParseType(T) ||
2418 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002419}
2420
2421/// FunctionHeader
2422/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2423/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2424/// OptionalAlign OptGC
2425bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2426 // Parse the linkage.
2427 LocTy LinkageLoc = Lex.getLoc();
2428 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002430 unsigned Visibility, RetAttrs;
2431 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002432 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002433 LocTy RetTypeLoc = Lex.getLoc();
2434 if (ParseOptionalLinkage(Linkage) ||
2435 ParseOptionalVisibility(Visibility) ||
2436 ParseOptionalCallingConv(CC) ||
2437 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002438 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 return true;
2440
2441 // Verify that the linkage is ok.
2442 switch ((GlobalValue::LinkageTypes)Linkage) {
2443 case GlobalValue::ExternalLinkage:
2444 break; // always ok.
2445 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002446 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002447 if (isDefine)
2448 return Error(LinkageLoc, "invalid linkage for function definition");
2449 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002450 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002451 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002452 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002453 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002454 case GlobalValue::LinkOnceAnyLinkage:
2455 case GlobalValue::LinkOnceODRLinkage:
2456 case GlobalValue::WeakAnyLinkage:
2457 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 case GlobalValue::DLLExportLinkage:
2459 if (!isDefine)
2460 return Error(LinkageLoc, "invalid linkage for function declaration");
2461 break;
2462 case GlobalValue::AppendingLinkage:
2463 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002464 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002465 return Error(LinkageLoc, "invalid function linkage type");
2466 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002467
Chris Lattner99bb3152009-01-05 08:00:30 +00002468 if (!FunctionType::isValidReturnType(RetType) ||
2469 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002470 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002471
Chris Lattnerdf986172009-01-02 07:01:27 +00002472 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002473
2474 std::string FunctionName;
2475 if (Lex.getKind() == lltok::GlobalVar) {
2476 FunctionName = Lex.getStrVal();
2477 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2478 unsigned NameID = Lex.getUIntVal();
2479
2480 if (NameID != NumberedVals.size())
2481 return TokError("function expected to be numbered '%" +
2482 utostr(NumberedVals.size()) + "'");
2483 } else {
2484 return TokError("expected function name");
2485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002487 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002488
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002489 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002490 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002491
Chris Lattnerdf986172009-01-02 07:01:27 +00002492 std::vector<ArgInfo> ArgList;
2493 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002494 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002495 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002496 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002497 std::string GC;
2498
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002499 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002500 ParseOptionalAttrs(FuncAttrs, 2) ||
2501 (EatIfPresent(lltok::kw_section) &&
2502 ParseStringConstant(Section)) ||
2503 ParseOptionalAlignment(Alignment) ||
2504 (EatIfPresent(lltok::kw_gc) &&
2505 ParseStringConstant(GC)))
2506 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002507
2508 // If the alignment was parsed as an attribute, move to the alignment field.
2509 if (FuncAttrs & Attribute::Alignment) {
2510 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2511 FuncAttrs &= ~Attribute::Alignment;
2512 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002513
Chris Lattnerdf986172009-01-02 07:01:27 +00002514 // Okay, if we got here, the function is syntactically valid. Convert types
2515 // and do semantic checks.
2516 std::vector<const Type*> ParamTypeList;
2517 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002518 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 // attributes.
2520 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2521 if (FuncAttrs & ObsoleteFuncAttrs) {
2522 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2523 FuncAttrs &= ~ObsoleteFuncAttrs;
2524 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002525
Chris Lattnerdf986172009-01-02 07:01:27 +00002526 if (RetAttrs != Attribute::None)
2527 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002528
Chris Lattnerdf986172009-01-02 07:01:27 +00002529 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2530 ParamTypeList.push_back(ArgList[i].Type);
2531 if (ArgList[i].Attrs != Attribute::None)
2532 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2533 }
2534
2535 if (FuncAttrs != Attribute::None)
2536 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2537
2538 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002539
Chris Lattnera9a9e072009-03-09 04:49:14 +00002540 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002541 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002542 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2543
Owen Andersonfba933c2009-07-01 23:57:11 +00002544 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002545 FunctionType::get(RetType, ParamTypeList, isVarArg);
2546 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002547
2548 Fn = 0;
2549 if (!FunctionName.empty()) {
2550 // If this was a definition of a forward reference, remove the definition
2551 // from the forward reference table and fill in the forward ref.
2552 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2553 ForwardRefVals.find(FunctionName);
2554 if (FRVI != ForwardRefVals.end()) {
2555 Fn = M->getFunction(FunctionName);
2556 ForwardRefVals.erase(FRVI);
2557 } else if ((Fn = M->getFunction(FunctionName))) {
2558 // If this function already exists in the symbol table, then it is
2559 // multiply defined. We accept a few cases for old backwards compat.
2560 // FIXME: Remove this stuff for LLVM 3.0.
2561 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2562 (!Fn->isDeclaration() && isDefine)) {
2563 // If the redefinition has different type or different attributes,
2564 // reject it. If both have bodies, reject it.
2565 return Error(NameLoc, "invalid redefinition of function '" +
2566 FunctionName + "'");
2567 } else if (Fn->isDeclaration()) {
2568 // Make sure to strip off any argument names so we can't get conflicts.
2569 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2570 AI != AE; ++AI)
2571 AI->setName("");
2572 }
2573 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002574
Dan Gohman41905542009-08-29 23:37:49 +00002575 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 // If this is a definition of a forward referenced function, make sure the
2577 // types agree.
2578 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2579 = ForwardRefValIDs.find(NumberedVals.size());
2580 if (I != ForwardRefValIDs.end()) {
2581 Fn = cast<Function>(I->second.first);
2582 if (Fn->getType() != PFT)
2583 return Error(NameLoc, "type of definition and forward reference of '@" +
2584 utostr(NumberedVals.size()) +"' disagree");
2585 ForwardRefValIDs.erase(I);
2586 }
2587 }
2588
2589 if (Fn == 0)
2590 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2591 else // Move the forward-reference to the correct spot in the module.
2592 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2593
2594 if (FunctionName.empty())
2595 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdf986172009-01-02 07:01:27 +00002597 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2598 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2599 Fn->setCallingConv(CC);
2600 Fn->setAttributes(PAL);
2601 Fn->setAlignment(Alignment);
2602 Fn->setSection(Section);
2603 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002604
Chris Lattnerdf986172009-01-02 07:01:27 +00002605 // Add all of the arguments we parsed to the function.
2606 Function::arg_iterator ArgIt = Fn->arg_begin();
2607 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2608 // If the argument has a name, insert it into the argument symbol table.
2609 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002610
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 // Set the name, if it conflicted, it will be auto-renamed.
2612 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002613
Chris Lattnerdf986172009-01-02 07:01:27 +00002614 if (ArgIt->getNameStr() != ArgList[i].Name)
2615 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2616 ArgList[i].Name + "'");
2617 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002618
Chris Lattnerdf986172009-01-02 07:01:27 +00002619 return false;
2620}
2621
2622
2623/// ParseFunctionBody
2624/// ::= '{' BasicBlock+ '}'
2625/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2626///
2627bool LLParser::ParseFunctionBody(Function &Fn) {
2628 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2629 return TokError("expected '{' in function body");
2630 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002631
Chris Lattnerdf986172009-01-02 07:01:27 +00002632 PerFunctionState PFS(*this, Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002633
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2635 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002636
Chris Lattnerdf986172009-01-02 07:01:27 +00002637 // Eat the }.
2638 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002639
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 // Verify function is ok.
2641 return PFS.VerifyFunctionComplete();
2642}
2643
2644/// ParseBasicBlock
2645/// ::= LabelStr? Instruction*
2646bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2647 // If this basic block starts out with a name, remember it.
2648 std::string Name;
2649 LocTy NameLoc = Lex.getLoc();
2650 if (Lex.getKind() == lltok::LabelStr) {
2651 Name = Lex.getStrVal();
2652 Lex.Lex();
2653 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002654
Chris Lattnerdf986172009-01-02 07:01:27 +00002655 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2656 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002657
Chris Lattnerdf986172009-01-02 07:01:27 +00002658 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002659
Chris Lattnerdf986172009-01-02 07:01:27 +00002660 // Parse the instructions in this block until we get a terminator.
2661 Instruction *Inst;
2662 do {
2663 // This instruction may have three possibilities for a name: a) none
2664 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2665 LocTy NameLoc = Lex.getLoc();
2666 int NameID = -1;
2667 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Chris Lattnerdf986172009-01-02 07:01:27 +00002669 if (Lex.getKind() == lltok::LocalVarID) {
2670 NameID = Lex.getUIntVal();
2671 Lex.Lex();
2672 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2673 return true;
2674 } else if (Lex.getKind() == lltok::LocalVar ||
2675 // FIXME: REMOVE IN LLVM 3.0
2676 Lex.getKind() == lltok::StringConstant) {
2677 NameStr = Lex.getStrVal();
2678 Lex.Lex();
2679 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2680 return true;
2681 }
Devang Patelf633a062009-09-17 23:04:48 +00002682
Chris Lattnerdf986172009-01-02 07:01:27 +00002683 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002684 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002685 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002686
2687 // Set metadata attached with this instruction.
Devang Patele30e6782009-09-28 21:41:20 +00002688 MetadataContext &TheMetadata = M->getContext().getMetadata();
Devang Patela2148402009-09-28 21:14:55 +00002689 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Devang Patel58a230a2009-09-29 20:30:57 +00002691 TheMetadata.addMD(MDI->first, MDI->second, Inst);
Devang Patelf633a062009-09-17 23:04:48 +00002692 MDsOnInst.clear();
2693
Chris Lattnerdf986172009-01-02 07:01:27 +00002694 BB->getInstList().push_back(Inst);
2695
2696 // Set the name on the instruction.
2697 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2698 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699
Chris Lattnerdf986172009-01-02 07:01:27 +00002700 return false;
2701}
2702
2703//===----------------------------------------------------------------------===//
2704// Instruction Parsing.
2705//===----------------------------------------------------------------------===//
2706
2707/// ParseInstruction - Parse one of the many different instructions.
2708///
2709bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2710 PerFunctionState &PFS) {
2711 lltok::Kind Token = Lex.getKind();
2712 if (Token == lltok::Eof)
2713 return TokError("found end of file when expecting more instructions");
2714 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002715 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002716 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 switch (Token) {
2719 default: return Error(Loc, "expected instruction opcode");
2720 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002721 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2722 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2724 case lltok::kw_br: return ParseBr(Inst, PFS);
2725 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2726 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2727 // Binary Operators.
2728 case lltok::kw_add:
2729 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002730 case lltok::kw_mul: {
2731 bool NUW = false;
2732 bool NSW = false;
2733 LocTy ModifierLoc = Lex.getLoc();
2734 if (EatIfPresent(lltok::kw_nuw))
2735 NUW = true;
2736 if (EatIfPresent(lltok::kw_nsw)) {
2737 NSW = true;
2738 if (EatIfPresent(lltok::kw_nuw))
2739 NUW = true;
2740 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002741 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002742 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2743 if (!Result) {
2744 if (!Inst->getType()->isIntOrIntVector()) {
2745 if (NUW)
2746 return Error(ModifierLoc, "nuw only applies to integer operations");
2747 if (NSW)
2748 return Error(ModifierLoc, "nsw only applies to integer operations");
2749 }
2750 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002751 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002752 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002753 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002754 }
2755 return Result;
2756 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002757 case lltok::kw_fadd:
2758 case lltok::kw_fsub:
2759 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2760
Dan Gohman59858cf2009-07-27 16:11:46 +00002761 case lltok::kw_sdiv: {
2762 bool Exact = false;
2763 if (EatIfPresent(lltok::kw_exact))
2764 Exact = true;
2765 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2766 if (!Result)
2767 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002768 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002769 return Result;
2770 }
2771
Chris Lattnerdf986172009-01-02 07:01:27 +00002772 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002773 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002774 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002775 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002776 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 case lltok::kw_shl:
2778 case lltok::kw_lshr:
2779 case lltok::kw_ashr:
2780 case lltok::kw_and:
2781 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002782 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002783 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002784 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002785 // Casts.
2786 case lltok::kw_trunc:
2787 case lltok::kw_zext:
2788 case lltok::kw_sext:
2789 case lltok::kw_fptrunc:
2790 case lltok::kw_fpext:
2791 case lltok::kw_bitcast:
2792 case lltok::kw_uitofp:
2793 case lltok::kw_sitofp:
2794 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002795 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002796 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002797 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Other.
2799 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002800 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002801 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2802 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2803 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2804 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2805 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2806 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2807 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002808 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2809 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 case lltok::kw_free: return ParseFree(Inst, PFS);
2811 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2812 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2813 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002814 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002816 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002817 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002818 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002820 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2821 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2822 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2823 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2824 }
2825}
2826
2827/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2828bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002829 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002830 switch (Lex.getKind()) {
2831 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2832 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2833 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2834 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2835 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2836 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2837 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2838 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2839 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2840 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2841 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2842 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2843 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2844 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2845 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2846 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2847 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2848 }
2849 } else {
2850 switch (Lex.getKind()) {
2851 default: TokError("expected icmp predicate (e.g. 'eq')");
2852 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2853 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2854 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2855 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2856 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2857 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2858 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2859 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2860 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2861 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2862 }
2863 }
2864 Lex.Lex();
2865 return false;
2866}
2867
2868//===----------------------------------------------------------------------===//
2869// Terminator Instructions.
2870//===----------------------------------------------------------------------===//
2871
2872/// ParseRet - Parse a return instruction.
Devang Patel0475c912009-09-29 00:01:14 +00002873/// ::= 'ret' void (',' !dbg, !1)
2874/// ::= 'ret' TypeAndValue (',' !dbg, !1)
2875/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
Devang Patelf633a062009-09-17 23:04:48 +00002876/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002877bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2878 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002879 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002880 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002881
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002882 if (Ty->isVoidTy()) {
Devang Patelf633a062009-09-17 23:04:48 +00002883 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002884 if (ParseOptionalCustomMetadata()) return true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002885 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002886 return false;
2887 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002888
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 Value *RV;
2890 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002891
Devang Patelf633a062009-09-17 23:04:48 +00002892 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002893 // Parse optional custom metadata, e.g. !dbg
2894 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2895 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002896 } else {
2897 // The normal case is one return value.
2898 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2899 // of 'ret {i32,i32} {i32 1, i32 2}'
2900 SmallVector<Value*, 8> RVs;
2901 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002902
Devang Patelf633a062009-09-17 23:04:48 +00002903 do {
Devang Patel0475c912009-09-29 00:01:14 +00002904 // If optional custom metadata, e.g. !dbg is seen then this is the
2905 // end of MRV.
2906 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907 break;
2908 if (ParseTypeAndValue(RV, PFS)) return true;
2909 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00002910 } while (EatIfPresent(lltok::comma));
2911
2912 RV = UndefValue::get(PFS.getFunction().getReturnType());
2913 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2915 BB->getInstList().push_back(I);
2916 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00002917 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 }
2919 }
Devang Patelf633a062009-09-17 23:04:48 +00002920 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002921 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002922
Owen Anderson1d0be152009-08-13 21:58:54 +00002923 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 return false;
2925}
2926
2927
2928/// ParseBr
2929/// ::= 'br' TypeAndValue
2930/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2931bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2932 LocTy Loc, Loc2;
2933 Value *Op0, *Op1, *Op2;
2934 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002935
Chris Lattnerdf986172009-01-02 07:01:27 +00002936 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2937 Inst = BranchInst::Create(BB);
2938 return false;
2939 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002940
Owen Anderson1d0be152009-08-13 21:58:54 +00002941 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00002942 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002943
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2945 ParseTypeAndValue(Op1, Loc, PFS) ||
2946 ParseToken(lltok::comma, "expected ',' after true destination") ||
2947 ParseTypeAndValue(Op2, Loc2, PFS))
2948 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002949
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 if (!isa<BasicBlock>(Op1))
2951 return Error(Loc, "true destination of branch must be a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00002952 if (!isa<BasicBlock>(Op2))
2953 return Error(Loc2, "true destination of branch must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002954
Chris Lattnerdf986172009-01-02 07:01:27 +00002955 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2956 return false;
2957}
2958
2959/// ParseSwitch
2960/// Instruction
2961/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2962/// JumpTable
2963/// ::= (TypeAndValue ',' TypeAndValue)*
2964bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2965 LocTy CondLoc, BBLoc;
2966 Value *Cond, *DefaultBB;
2967 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2968 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2969 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2970 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2971 return true;
2972
2973 if (!isa<IntegerType>(Cond->getType()))
2974 return Error(CondLoc, "switch condition must have integer type");
2975 if (!isa<BasicBlock>(DefaultBB))
2976 return Error(BBLoc, "default destination must be a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002977
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 // Parse the jump table pairs.
2979 SmallPtrSet<Value*, 32> SeenCases;
2980 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2981 while (Lex.getKind() != lltok::rsquare) {
2982 Value *Constant, *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002983
Chris Lattnerdf986172009-01-02 07:01:27 +00002984 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2985 ParseToken(lltok::comma, "expected ',' after case value") ||
2986 ParseTypeAndValue(DestBB, BBLoc, PFS))
2987 return true;
2988
2989 if (!SeenCases.insert(Constant))
2990 return Error(CondLoc, "duplicate case value in switch");
2991 if (!isa<ConstantInt>(Constant))
2992 return Error(CondLoc, "case value is not a constant integer");
2993 if (!isa<BasicBlock>(DestBB))
2994 return Error(BBLoc, "case destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002995
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2997 cast<BasicBlock>(DestBB)));
2998 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002999
Chris Lattnerdf986172009-01-02 07:01:27 +00003000 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003001
Chris Lattnerdf986172009-01-02 07:01:27 +00003002 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
3003 Table.size());
3004 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3005 SI->addCase(Table[i].first, Table[i].second);
3006 Inst = SI;
3007 return false;
3008}
3009
3010/// ParseInvoke
3011/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3012/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3013bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3014 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003015 unsigned RetAttrs, FnAttrs;
3016 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003017 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003018 LocTy RetTypeLoc;
3019 ValID CalleeID;
3020 SmallVector<ParamInfo, 16> ArgList;
3021
3022 Value *NormalBB, *UnwindBB;
3023 if (ParseOptionalCallingConv(CC) ||
3024 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003025 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 ParseValID(CalleeID) ||
3027 ParseParameterList(ArgList, PFS) ||
3028 ParseOptionalAttrs(FnAttrs, 2) ||
3029 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3030 ParseTypeAndValue(NormalBB, PFS) ||
3031 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3032 ParseTypeAndValue(UnwindBB, PFS))
3033 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003034
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 if (!isa<BasicBlock>(NormalBB))
3036 return Error(CallLoc, "normal destination is not a basic block");
3037 if (!isa<BasicBlock>(UnwindBB))
3038 return Error(CallLoc, "unwind destination is not a basic block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003039
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 // If RetType is a non-function pointer type, then this is the short syntax
3041 // for the call, which means that RetType is just the return type. Infer the
3042 // rest of the function argument types from the arguments that are present.
3043 const PointerType *PFTy = 0;
3044 const FunctionType *Ty = 0;
3045 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3046 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3047 // Pull out the types of all of the arguments...
3048 std::vector<const Type*> ParamTypes;
3049 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3050 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003051
Chris Lattnerdf986172009-01-02 07:01:27 +00003052 if (!FunctionType::isValidReturnType(RetType))
3053 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003054
Owen Andersondebcb012009-07-29 22:17:13 +00003055 Ty = FunctionType::get(RetType, ParamTypes, false);
3056 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003057 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003058
Chris Lattnerdf986172009-01-02 07:01:27 +00003059 // Look up the callee.
3060 Value *Callee;
3061 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003062
Chris Lattnerdf986172009-01-02 07:01:27 +00003063 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3064 // function attributes.
3065 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3066 if (FnAttrs & ObsoleteFuncAttrs) {
3067 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3068 FnAttrs &= ~ObsoleteFuncAttrs;
3069 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003070
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 // Set up the Attributes for the function.
3072 SmallVector<AttributeWithIndex, 8> Attrs;
3073 if (RetAttrs != Attribute::None)
3074 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003075
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003077
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 // Loop through FunctionType's arguments and ensure they are specified
3079 // correctly. Also, gather any parameter attributes.
3080 FunctionType::param_iterator I = Ty->param_begin();
3081 FunctionType::param_iterator E = Ty->param_end();
3082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3083 const Type *ExpectedTy = 0;
3084 if (I != E) {
3085 ExpectedTy = *I++;
3086 } else if (!Ty->isVarArg()) {
3087 return Error(ArgList[i].Loc, "too many arguments specified");
3088 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003089
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3091 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3092 ExpectedTy->getDescription() + "'");
3093 Args.push_back(ArgList[i].V);
3094 if (ArgList[i].Attrs != Attribute::None)
3095 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3096 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003097
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 if (I != E)
3099 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003100
Chris Lattnerdf986172009-01-02 07:01:27 +00003101 if (FnAttrs != Attribute::None)
3102 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 // Finish off the Attributes and check them
3105 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003106
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
3108 cast<BasicBlock>(UnwindBB),
3109 Args.begin(), Args.end());
3110 II->setCallingConv(CC);
3111 II->setAttributes(PAL);
3112 Inst = II;
3113 return false;
3114}
3115
3116
3117
3118//===----------------------------------------------------------------------===//
3119// Binary Operators.
3120//===----------------------------------------------------------------------===//
3121
3122/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003123/// ::= ArithmeticOps TypeAndValue ',' Value
3124///
3125/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3126/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003127bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003128 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003129 LocTy Loc; Value *LHS, *RHS;
3130 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3131 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3132 ParseValue(LHS->getType(), RHS, PFS))
3133 return true;
3134
Chris Lattnere914b592009-01-05 08:24:46 +00003135 bool Valid;
3136 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003137 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003138 case 0: // int or FP.
3139 Valid = LHS->getType()->isIntOrIntVector() ||
3140 LHS->getType()->isFPOrFPVector();
3141 break;
3142 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3143 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3144 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003145
Chris Lattnere914b592009-01-05 08:24:46 +00003146 if (!Valid)
3147 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3150 return false;
3151}
3152
3153/// ParseLogical
3154/// ::= ArithmeticOps TypeAndValue ',' Value {
3155bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3156 unsigned Opc) {
3157 LocTy Loc; Value *LHS, *RHS;
3158 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3159 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3160 ParseValue(LHS->getType(), RHS, PFS))
3161 return true;
3162
3163 if (!LHS->getType()->isIntOrIntVector())
3164 return Error(Loc,"instruction requires integer or integer vector operands");
3165
3166 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3167 return false;
3168}
3169
3170
3171/// ParseCompare
3172/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3173/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003174bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3175 unsigned Opc) {
3176 // Parse the integer/fp comparison predicate.
3177 LocTy Loc;
3178 unsigned Pred;
3179 Value *LHS, *RHS;
3180 if (ParseCmpPredicate(Pred, Opc) ||
3181 ParseTypeAndValue(LHS, Loc, PFS) ||
3182 ParseToken(lltok::comma, "expected ',' after compare value") ||
3183 ParseValue(LHS->getType(), RHS, PFS))
3184 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003185
Chris Lattnerdf986172009-01-02 07:01:27 +00003186 if (Opc == Instruction::FCmp) {
3187 if (!LHS->getType()->isFPOrFPVector())
3188 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003189 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003190 } else {
3191 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003192 if (!LHS->getType()->isIntOrIntVector() &&
3193 !isa<PointerType>(LHS->getType()))
3194 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003195 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 }
3197 return false;
3198}
3199
3200//===----------------------------------------------------------------------===//
3201// Other Instructions.
3202//===----------------------------------------------------------------------===//
3203
3204
3205/// ParseCast
3206/// ::= CastOpc TypeAndValue 'to' Type
3207bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3208 unsigned Opc) {
3209 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003210 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 if (ParseTypeAndValue(Op, Loc, PFS) ||
3212 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3213 ParseType(DestTy))
3214 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003215
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003216 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3217 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 return Error(Loc, "invalid cast opcode for cast from '" +
3219 Op->getType()->getDescription() + "' to '" +
3220 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003221 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003222 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3223 return false;
3224}
3225
3226/// ParseSelect
3227/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3228bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3229 LocTy Loc;
3230 Value *Op0, *Op1, *Op2;
3231 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3232 ParseToken(lltok::comma, "expected ',' after select condition") ||
3233 ParseTypeAndValue(Op1, PFS) ||
3234 ParseToken(lltok::comma, "expected ',' after select value") ||
3235 ParseTypeAndValue(Op2, PFS))
3236 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3239 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003240
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 Inst = SelectInst::Create(Op0, Op1, Op2);
3242 return false;
3243}
3244
Chris Lattner0088a5c2009-01-05 08:18:44 +00003245/// ParseVA_Arg
3246/// ::= 'va_arg' TypeAndValue ',' Type
3247bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003249 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003250 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003251 if (ParseTypeAndValue(Op, PFS) ||
3252 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003253 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003254 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003255
Chris Lattner0088a5c2009-01-05 08:18:44 +00003256 if (!EltTy->isFirstClassType())
3257 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003258
3259 Inst = new VAArgInst(Op, EltTy);
3260 return false;
3261}
3262
3263/// ParseExtractElement
3264/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3265bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3266 LocTy Loc;
3267 Value *Op0, *Op1;
3268 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3269 ParseToken(lltok::comma, "expected ',' after extract value") ||
3270 ParseTypeAndValue(Op1, PFS))
3271 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003272
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3274 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003275
Eric Christophera3500da2009-07-25 02:28:41 +00003276 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 return false;
3278}
3279
3280/// ParseInsertElement
3281/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3282bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3283 LocTy Loc;
3284 Value *Op0, *Op1, *Op2;
3285 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3286 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3287 ParseTypeAndValue(Op1, PFS) ||
3288 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3289 ParseTypeAndValue(Op2, PFS))
3290 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003291
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003293 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003294
Chris Lattnerdf986172009-01-02 07:01:27 +00003295 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3296 return false;
3297}
3298
3299/// ParseShuffleVector
3300/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3301bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3302 LocTy Loc;
3303 Value *Op0, *Op1, *Op2;
3304 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3305 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3306 ParseTypeAndValue(Op1, PFS) ||
3307 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3308 ParseTypeAndValue(Op2, PFS))
3309 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003310
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3312 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003313
Chris Lattnerdf986172009-01-02 07:01:27 +00003314 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3315 return false;
3316}
3317
3318/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003319/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003320bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003321 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 Value *Op0, *Op1;
3323 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003324
Chris Lattnerdf986172009-01-02 07:01:27 +00003325 if (ParseType(Ty) ||
3326 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3327 ParseValue(Ty, Op0, PFS) ||
3328 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003329 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003330 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3331 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3334 while (1) {
3335 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003336
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003337 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003338 break;
3339
Devang Patela43d46f2009-10-16 18:45:49 +00003340 if (Lex.getKind() == lltok::NamedOrCustomMD)
3341 break;
3342
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003343 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003344 ParseValue(Ty, Op0, PFS) ||
3345 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003346 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003347 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3348 return true;
3349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003350
Devang Patela43d46f2009-10-16 18:45:49 +00003351 if (Lex.getKind() == lltok::NamedOrCustomMD)
3352 if (ParseOptionalCustomMetadata()) return true;
3353
Chris Lattnerdf986172009-01-02 07:01:27 +00003354 if (!Ty->isFirstClassType())
3355 return Error(TypeLoc, "phi node must have first class type");
3356
3357 PHINode *PN = PHINode::Create(Ty);
3358 PN->reserveOperandSpace(PHIVals.size());
3359 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3360 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3361 Inst = PN;
3362 return false;
3363}
3364
3365/// ParseCall
3366/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3367/// ParameterList OptionalAttrs
3368bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3369 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003370 unsigned RetAttrs, FnAttrs;
3371 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003372 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 LocTy RetTypeLoc;
3374 ValID CalleeID;
3375 SmallVector<ParamInfo, 16> ArgList;
3376 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003377
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3379 ParseOptionalCallingConv(CC) ||
3380 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003381 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003382 ParseValID(CalleeID) ||
3383 ParseParameterList(ArgList, PFS) ||
3384 ParseOptionalAttrs(FnAttrs, 2))
3385 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003386
Chris Lattnerdf986172009-01-02 07:01:27 +00003387 // If RetType is a non-function pointer type, then this is the short syntax
3388 // for the call, which means that RetType is just the return type. Infer the
3389 // rest of the function argument types from the arguments that are present.
3390 const PointerType *PFTy = 0;
3391 const FunctionType *Ty = 0;
3392 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3393 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3394 // Pull out the types of all of the arguments...
3395 std::vector<const Type*> ParamTypes;
3396 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3397 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003398
Chris Lattnerdf986172009-01-02 07:01:27 +00003399 if (!FunctionType::isValidReturnType(RetType))
3400 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003401
Owen Andersondebcb012009-07-29 22:17:13 +00003402 Ty = FunctionType::get(RetType, ParamTypes, false);
3403 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003404 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003405
Chris Lattnerdf986172009-01-02 07:01:27 +00003406 // Look up the callee.
3407 Value *Callee;
3408 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3411 // function attributes.
3412 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3413 if (FnAttrs & ObsoleteFuncAttrs) {
3414 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3415 FnAttrs &= ~ObsoleteFuncAttrs;
3416 }
3417
3418 // Set up the Attributes for the function.
3419 SmallVector<AttributeWithIndex, 8> Attrs;
3420 if (RetAttrs != Attribute::None)
3421 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003422
Chris Lattnerdf986172009-01-02 07:01:27 +00003423 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003424
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 // Loop through FunctionType's arguments and ensure they are specified
3426 // correctly. Also, gather any parameter attributes.
3427 FunctionType::param_iterator I = Ty->param_begin();
3428 FunctionType::param_iterator E = Ty->param_end();
3429 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3430 const Type *ExpectedTy = 0;
3431 if (I != E) {
3432 ExpectedTy = *I++;
3433 } else if (!Ty->isVarArg()) {
3434 return Error(ArgList[i].Loc, "too many arguments specified");
3435 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003436
Chris Lattnerdf986172009-01-02 07:01:27 +00003437 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3438 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3439 ExpectedTy->getDescription() + "'");
3440 Args.push_back(ArgList[i].V);
3441 if (ArgList[i].Attrs != Attribute::None)
3442 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3443 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003444
Chris Lattnerdf986172009-01-02 07:01:27 +00003445 if (I != E)
3446 return Error(CallLoc, "not enough parameters specified for call");
3447
3448 if (FnAttrs != Attribute::None)
3449 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3450
3451 // Finish off the Attributes and check them
3452 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003453
Chris Lattnerdf986172009-01-02 07:01:27 +00003454 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3455 CI->setTailCall(isTail);
3456 CI->setCallingConv(CC);
3457 CI->setAttributes(PAL);
3458 Inst = CI;
3459 return false;
3460}
3461
3462//===----------------------------------------------------------------------===//
3463// Memory Instructions.
3464//===----------------------------------------------------------------------===//
3465
3466/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003467/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3468/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003469bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003470 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003471 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003472 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003473 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003475 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003476
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003477 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003478 if (Lex.getKind() == lltok::kw_align
3479 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003480 if (ParseOptionalInfo(Alignment)) return true;
3481 } else {
3482 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3483 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003484 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003485 }
3486 }
3487
Owen Anderson1d0be152009-08-13 21:58:54 +00003488 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003489 return Error(SizeLoc, "element count must be i32");
3490
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003491 if (isAlloca)
Owen Anderson50dead02009-07-15 23:53:25 +00003492 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003493 else {
3494 // Autoupgrade old malloc instruction to malloc call.
3495 const Type* IntPtrTy = Type::getInt32Ty(Context);
3496 const Type* Int8PtrTy = PointerType::getUnqual(Type::getInt8Ty(Context));
3497 if (!MallocF)
3498 // Prototype malloc as "void *autoupgrade_malloc(int32)".
3499 MallocF = cast<Function>(M->getOrInsertFunction("autoupgrade_malloc",
3500 Int8PtrTy, IntPtrTy, NULL));
3501 // "autoupgrade_malloc" updated to "malloc" in ValidateEndOfModule().
3502
3503 Inst = cast<Instruction>(CallInst::CreateMalloc(BB, IntPtrTy, Ty,
3504 Size, MallocF));
3505 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003506 return false;
3507}
3508
3509/// ParseFree
3510/// ::= 'free' TypeAndValue
3511bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3512 Value *Val; LocTy Loc;
3513 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3514 if (!isa<PointerType>(Val->getType()))
3515 return Error(Loc, "operand to free must be a pointer");
3516 Inst = new FreeInst(Val);
3517 return false;
3518}
3519
3520/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003521/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003522bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3523 bool isVolatile) {
3524 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003525 unsigned Alignment = 0;
3526 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003527
Devang Patelf633a062009-09-17 23:04:48 +00003528 if (EatIfPresent(lltok::comma))
3529 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003530
3531 if (!isa<PointerType>(Val->getType()) ||
3532 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3533 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003534
Chris Lattnerdf986172009-01-02 07:01:27 +00003535 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3536 return false;
3537}
3538
3539/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003540/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003541bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3542 bool isVolatile) {
3543 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003544 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 if (ParseTypeAndValue(Val, Loc, PFS) ||
3546 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003547 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003548 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003549
3550 if (EatIfPresent(lltok::comma))
3551 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003552
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 if (!isa<PointerType>(Ptr->getType()))
3554 return Error(PtrLoc, "store operand must be a pointer");
3555 if (!Val->getType()->isFirstClassType())
3556 return Error(Loc, "store operand must be a first class value");
3557 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3558 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3561 return false;
3562}
3563
3564/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003565/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003566/// FIXME: Remove support for getresult in LLVM 3.0
3567bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3568 Value *Val; LocTy ValLoc, EltLoc;
3569 unsigned Element;
3570 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3571 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003572 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003573 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003574
Chris Lattnerdf986172009-01-02 07:01:27 +00003575 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3576 return Error(ValLoc, "getresult inst requires an aggregate operand");
3577 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3578 return Error(EltLoc, "invalid getresult index for value");
3579 Inst = ExtractValueInst::Create(Val, Element);
3580 return false;
3581}
3582
3583/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003584/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003585bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3586 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003587
Dan Gohmandcb40a32009-07-29 15:58:36 +00003588 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003589
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003590 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003591
Chris Lattnerdf986172009-01-02 07:01:27 +00003592 if (!isa<PointerType>(Ptr->getType()))
3593 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003594
Chris Lattnerdf986172009-01-02 07:01:27 +00003595 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003596 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003597 if (Lex.getKind() == lltok::NamedOrCustomMD)
3598 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003599 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003600 if (!isa<IntegerType>(Val->getType()))
3601 return Error(EltLoc, "getelementptr index must be an integer");
3602 Indices.push_back(Val);
3603 }
Devang Patel6225d642009-10-13 18:49:55 +00003604 if (Lex.getKind() == lltok::NamedOrCustomMD)
3605 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003606
Chris Lattnerdf986172009-01-02 07:01:27 +00003607 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3608 Indices.begin(), Indices.end()))
3609 return Error(Loc, "invalid getelementptr indices");
3610 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003611 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003612 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 return false;
3614}
3615
3616/// ParseExtractValue
3617/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3618bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3619 Value *Val; LocTy Loc;
3620 SmallVector<unsigned, 4> Indices;
3621 if (ParseTypeAndValue(Val, Loc, PFS) ||
3622 ParseIndexList(Indices))
3623 return true;
3624
3625 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3626 return Error(Loc, "extractvalue operand must be array or struct");
3627
3628 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3629 Indices.end()))
3630 return Error(Loc, "invalid indices for extractvalue");
3631 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3632 return false;
3633}
3634
3635/// ParseInsertValue
3636/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3637bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3638 Value *Val0, *Val1; LocTy Loc0, Loc1;
3639 SmallVector<unsigned, 4> Indices;
3640 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3641 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3642 ParseTypeAndValue(Val1, Loc1, PFS) ||
3643 ParseIndexList(Indices))
3644 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003645
Chris Lattnerdf986172009-01-02 07:01:27 +00003646 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3647 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003648
Chris Lattnerdf986172009-01-02 07:01:27 +00003649 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3650 Indices.end()))
3651 return Error(Loc0, "invalid indices for insertvalue");
3652 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3653 return false;
3654}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003655
3656//===----------------------------------------------------------------------===//
3657// Embedded metadata.
3658//===----------------------------------------------------------------------===//
3659
3660/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003661/// ::= Element (',' Element)*
3662/// Element
3663/// ::= 'null' | TypeAndValue
3664bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003665 assert(Lex.getKind() == lltok::lbrace);
3666 Lex.Lex();
3667 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003668 Value *V = 0;
Nick Lewyckycb337992009-05-10 20:57:05 +00003669 if (Lex.getKind() == lltok::kw_null) {
3670 Lex.Lex();
3671 V = 0;
3672 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003673 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003674 if (ParseType(Ty)) return true;
3675 if (Lex.getKind() == lltok::Metadata) {
3676 Lex.Lex();
Devang Patel104cf9e2009-07-23 01:07:34 +00003677 MetadataBase *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003678 if (!ParseMDNode(Node))
3679 V = Node;
3680 else {
3681 MetadataBase *MDS = 0;
3682 if (ParseMDString(MDS)) return true;
3683 V = MDS;
3684 }
3685 } else {
3686 Constant *C;
3687 if (ParseGlobalValue(Ty, C)) return true;
3688 V = C;
3689 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003690 }
3691 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003692 } while (EatIfPresent(lltok::comma));
3693
3694 return false;
3695}