blob: d0cac3f03599ad2ace8f14453a0c3fcd0d807871 [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"
21#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000022#include "llvm/Operator.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000023#include "llvm/ValueSymbolTable.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/StringExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
Chris Lattner3ed88ef2009-01-02 08:05:26 +000030/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000031bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000032 // Prime the lexer.
33 Lex.Lex();
34
Chris Lattnerad7d1e22009-01-04 20:44:11 +000035 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000037}
38
39/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40/// module.
41bool LLParser::ValidateEndOfModule() {
Victor Hernandez68afa542009-10-21 19:11:40 +000042 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000043 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000044 if (MallocF) {
45 MallocF->setName("malloc");
46 // If setName() does not set the name to "malloc", then there is already a
47 // declaration of "malloc". In that case, iterate over all calls to MallocF
48 // and get them to call the declared "malloc" instead.
49 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000050 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000051 if (RealMallocF->getType() != MallocF->getType())
52 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
53 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000054 MallocF->eraseFromParent();
55 MallocF = NULL;
56 }
57 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000058
59
60 // If there are entries in ForwardRefBlockAddresses at this point, they are
61 // references after the function was defined. Resolve those now.
62 while (!ForwardRefBlockAddresses.empty()) {
63 // Okay, we are referencing an already-parsed function, resolve them now.
64 Function *TheFn = 0;
65 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
66 if (Fn.Kind == ValID::t_GlobalName)
67 TheFn = M->getFunction(Fn.StrVal);
68 else if (Fn.UIntVal < NumberedVals.size())
69 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
70
71 if (TheFn == 0)
72 return Error(Fn.Loc, "unknown function referenced by blockaddress");
73
74 // Resolve all these references.
75 if (ResolveForwardRefBlockAddresses(TheFn,
76 ForwardRefBlockAddresses.begin()->second,
77 0))
78 return true;
79
80 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
81 }
82
83
Chris Lattnerdf986172009-01-02 07:01:27 +000084 if (!ForwardRefTypes.empty())
85 return Error(ForwardRefTypes.begin()->second.second,
86 "use of undefined type named '" +
87 ForwardRefTypes.begin()->first + "'");
88 if (!ForwardRefTypeIDs.empty())
89 return Error(ForwardRefTypeIDs.begin()->second.second,
90 "use of undefined type '%" +
91 utostr(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000092
Chris Lattnerdf986172009-01-02 07:01:27 +000093 if (!ForwardRefVals.empty())
94 return Error(ForwardRefVals.begin()->second.second,
95 "use of undefined value '@" + ForwardRefVals.begin()->first +
96 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerdf986172009-01-02 07:01:27 +000098 if (!ForwardRefValIDs.empty())
99 return Error(ForwardRefValIDs.begin()->second.second,
100 "use of undefined value '@" +
101 utostr(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Devang Patel1c7eea62009-07-08 19:23:54 +0000103 if (!ForwardRefMDNodes.empty())
104 return Error(ForwardRefMDNodes.begin()->second.second,
105 "use of undefined metadata '!" +
106 utostr(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Devang Patel1c7eea62009-07-08 19:23:54 +0000108
Chris Lattnerdf986172009-01-02 07:01:27 +0000109 // Look for intrinsic functions and CallInst that need to be upgraded
110 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
111 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patele4b27562009-08-28 23:24:31 +0000113 // Check debug info intrinsics.
114 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000115 return false;
116}
117
Chris Lattner09d9ef42009-10-28 03:39:23 +0000118bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
119 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
120 PerFunctionState *PFS) {
121 // Loop over all the references, resolving them.
122 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
123 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000124 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000125 if (Refs[i].first.Kind == ValID::t_LocalName)
126 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000127 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000128 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
129 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
130 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000131 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000132 } else {
133 Res = dyn_cast_or_null<BasicBlock>(
134 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
135 }
136
Chris Lattnercdfc9402009-11-01 01:27:45 +0000137 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138 return Error(Refs[i].first.Loc,
139 "referenced value is not a basic block");
140
141 // Get the BlockAddress for this and update references to use it.
142 BlockAddress *BA = BlockAddress::get(TheFn, Res);
143 Refs[i].second->replaceAllUsesWith(BA);
144 Refs[i].second->eraseFromParent();
145 }
146 return false;
147}
148
149
Chris Lattnerdf986172009-01-02 07:01:27 +0000150//===----------------------------------------------------------------------===//
151// Top-Level Entities
152//===----------------------------------------------------------------------===//
153
154bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000155 while (1) {
156 switch (Lex.getKind()) {
157 default: return TokError("expected top-level entity");
158 case lltok::Eof: return false;
159 //case lltok::kw_define:
160 case lltok::kw_declare: if (ParseDeclare()) return true; break;
161 case lltok::kw_define: if (ParseDefine()) return true; break;
162 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
163 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
164 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
165 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000166 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
168 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000169 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000170 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Devang Patel923078c2009-07-01 19:21:12 +0000171 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
Devang Patel0475c912009-09-29 00:01:14 +0000172 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173
174 // The Global variable production with no name can have many different
175 // optional leading prefixes, the production is:
176 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
177 // OptionalAddrSpace ('constant'|'global') ...
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000178 case lltok::kw_private : // OptionalLinkage
179 case lltok::kw_linker_private: // OptionalLinkage
180 case lltok::kw_internal: // OptionalLinkage
181 case lltok::kw_weak: // OptionalLinkage
182 case lltok::kw_weak_odr: // OptionalLinkage
183 case lltok::kw_linkonce: // OptionalLinkage
184 case lltok::kw_linkonce_odr: // OptionalLinkage
185 case lltok::kw_appending: // OptionalLinkage
186 case lltok::kw_dllexport: // OptionalLinkage
187 case lltok::kw_common: // OptionalLinkage
188 case lltok::kw_dllimport: // OptionalLinkage
189 case lltok::kw_extern_weak: // OptionalLinkage
190 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000191 unsigned Linkage, Visibility;
192 if (ParseOptionalLinkage(Linkage) ||
193 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000194 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 return true;
196 break;
197 }
198 case lltok::kw_default: // OptionalVisibility
199 case lltok::kw_hidden: // OptionalVisibility
200 case lltok::kw_protected: { // OptionalVisibility
201 unsigned Visibility;
202 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000203 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000204 return true;
205 break;
206 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000207
Chris Lattnerdf986172009-01-02 07:01:27 +0000208 case lltok::kw_thread_local: // OptionalThreadLocal
209 case lltok::kw_addrspace: // OptionalAddrSpace
210 case lltok::kw_constant: // GlobalType
211 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000212 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000213 break;
214 }
215 }
216}
217
218
219/// toplevelentity
220/// ::= 'module' 'asm' STRINGCONSTANT
221bool LLParser::ParseModuleAsm() {
222 assert(Lex.getKind() == lltok::kw_module);
223 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000224
225 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000226 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
227 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000228
Chris Lattnerdf986172009-01-02 07:01:27 +0000229 const std::string &AsmSoFar = M->getModuleInlineAsm();
230 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000231 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000232 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000233 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000234 return false;
235}
236
237/// toplevelentity
238/// ::= 'target' 'triple' '=' STRINGCONSTANT
239/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
240bool LLParser::ParseTargetDefinition() {
241 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000242 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000243 switch (Lex.Lex()) {
244 default: return TokError("unknown target property");
245 case lltok::kw_triple:
246 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000247 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
248 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000249 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000250 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000251 return false;
252 case lltok::kw_datalayout:
253 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
255 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000256 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000257 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000258 return false;
259 }
260}
261
262/// toplevelentity
263/// ::= 'deplibs' '=' '[' ']'
264/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
265bool LLParser::ParseDepLibs() {
266 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000267 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000268 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
269 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
270 return true;
271
272 if (EatIfPresent(lltok::rsquare))
273 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000274
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000275 std::string Str;
276 if (ParseStringConstant(Str)) return true;
277 M->addLibrary(Str);
278
279 while (EatIfPresent(lltok::comma)) {
280 if (ParseStringConstant(Str)) return true;
281 M->addLibrary(Str);
282 }
283
284 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000285}
286
Dan Gohman3845e502009-08-12 23:32:33 +0000287/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000288/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000289/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000290bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000291 unsigned TypeID = NumberedTypes.size();
292
293 // Handle the LocalVarID form.
294 if (Lex.getKind() == lltok::LocalVarID) {
295 if (Lex.getUIntVal() != TypeID)
296 return Error(Lex.getLoc(), "type expected to be numbered '%" +
297 utostr(TypeID) + "'");
298 Lex.Lex(); // eat LocalVarID;
299
300 if (ParseToken(lltok::equal, "expected '=' after name"))
301 return true;
302 }
303
Chris Lattnerdf986172009-01-02 07:01:27 +0000304 assert(Lex.getKind() == lltok::kw_type);
305 LocTy TypeLoc = Lex.getLoc();
306 Lex.Lex(); // eat kw_type
307
Owen Anderson1d0be152009-08-13 21:58:54 +0000308 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000309 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerdf986172009-01-02 07:01:27 +0000311 // See if this type was previously referenced.
312 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
313 FI = ForwardRefTypeIDs.find(TypeID);
314 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000315 if (FI->second.first.get() == Ty)
316 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerdf986172009-01-02 07:01:27 +0000318 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
319 Ty = FI->second.first.get();
320 ForwardRefTypeIDs.erase(FI);
321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerdf986172009-01-02 07:01:27 +0000325 return false;
326}
327
328/// toplevelentity
329/// ::= LocalVar '=' 'type' type
330bool LLParser::ParseNamedType() {
331 std::string Name = Lex.getStrVal();
332 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000333 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000334
Owen Anderson1d0be152009-08-13 21:58:54 +0000335 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000336
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000337 if (ParseToken(lltok::equal, "expected '=' after name") ||
338 ParseToken(lltok::kw_type, "expected 'type' after name") ||
339 ParseType(Ty))
340 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000341
Chris Lattnerdf986172009-01-02 07:01:27 +0000342 // Set the type name, checking for conflicts as we do so.
343 bool AlreadyExists = M->addTypeName(Name, Ty);
344 if (!AlreadyExists) return false;
345
346 // See if this type is a forward reference. We need to eagerly resolve
347 // types to allow recursive type redefinitions below.
348 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
349 FI = ForwardRefTypes.find(Name);
350 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000351 if (FI->second.first.get() == Ty)
352 return Error(NameLoc, "self referential type is invalid");
353
Chris Lattnerdf986172009-01-02 07:01:27 +0000354 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
355 Ty = FI->second.first.get();
356 ForwardRefTypes.erase(FI);
357 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000358
Chris Lattnerdf986172009-01-02 07:01:27 +0000359 // Inserting a name that is already defined, get the existing name.
360 const Type *Existing = M->getTypeByName(Name);
361 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerdf986172009-01-02 07:01:27 +0000363 // Otherwise, this is an attempt to redefine a type. That's okay if
364 // the redefinition is identical to the original.
365 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
366 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerdf986172009-01-02 07:01:27 +0000368 // Any other kind of (non-equivalent) redefinition is an error.
369 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
370 Ty->getDescription() + "'");
371}
372
373
374/// toplevelentity
375/// ::= 'declare' FunctionHeader
376bool LLParser::ParseDeclare() {
377 assert(Lex.getKind() == lltok::kw_declare);
378 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Chris Lattnerdf986172009-01-02 07:01:27 +0000380 Function *F;
381 return ParseFunctionHeader(F, false);
382}
383
384/// toplevelentity
385/// ::= 'define' FunctionHeader '{' ...
386bool LLParser::ParseDefine() {
387 assert(Lex.getKind() == lltok::kw_define);
388 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000391 return ParseFunctionHeader(F, true) ||
392 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000393}
394
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000395/// ParseGlobalType
396/// ::= 'constant'
397/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000398bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
400 IsConstant = true;
401 else if (Lex.getKind() == lltok::kw_global)
402 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000403 else {
404 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000405 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000406 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000407 Lex.Lex();
408 return false;
409}
410
Dan Gohman3845e502009-08-12 23:32:33 +0000411/// ParseUnnamedGlobal:
412/// OptionalVisibility ALIAS ...
413/// OptionalLinkage OptionalVisibility ... -> global variable
414/// GlobalID '=' OptionalVisibility ALIAS ...
415/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
416bool LLParser::ParseUnnamedGlobal() {
417 unsigned VarID = NumberedVals.size();
418 std::string Name;
419 LocTy NameLoc = Lex.getLoc();
420
421 // Handle the GlobalID form.
422 if (Lex.getKind() == lltok::GlobalID) {
423 if (Lex.getUIntVal() != VarID)
424 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
425 utostr(VarID) + "'");
426 Lex.Lex(); // eat GlobalID;
427
428 if (ParseToken(lltok::equal, "expected '=' after name"))
429 return true;
430 }
431
432 bool HasLinkage;
433 unsigned Linkage, Visibility;
434 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
435 ParseOptionalVisibility(Visibility))
436 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Dan Gohman3845e502009-08-12 23:32:33 +0000438 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
439 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
440 return ParseAlias(Name, NameLoc, Visibility);
441}
442
Chris Lattnerdf986172009-01-02 07:01:27 +0000443/// ParseNamedGlobal:
444/// GlobalVar '=' OptionalVisibility ALIAS ...
445/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
446bool LLParser::ParseNamedGlobal() {
447 assert(Lex.getKind() == lltok::GlobalVar);
448 LocTy NameLoc = Lex.getLoc();
449 std::string Name = Lex.getStrVal();
450 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattnerdf986172009-01-02 07:01:27 +0000452 bool HasLinkage;
453 unsigned Linkage, Visibility;
454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattnerdf986172009-01-02 07:01:27 +0000459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
462}
463
Devang Patel256be962009-07-20 19:00:08 +0000464// MDString:
465// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000466bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000467 std::string Str;
468 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000469 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000470 return false;
471}
472
473// MDNode:
474// ::= '!' MDNodeNumber
Chris Lattner442ffa12009-12-29 21:53:55 +0000475bool LLParser::ParseMDNode(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000476 // !{ ..., !42, ... }
477 unsigned MID = 0;
Chris Lattnere80250e2009-12-29 21:43:58 +0000478 if (ParseUInt32(MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000479
Devang Patel256be962009-07-20 19:00:08 +0000480 // Check existing MDNode.
Chris Lattnere80250e2009-12-29 21:43:58 +0000481 std::map<unsigned, TrackingVH<MDNode> >::iterator I = MetadataCache.find(MID);
Devang Patel256be962009-07-20 19:00:08 +0000482 if (I != MetadataCache.end()) {
Chris Lattner442ffa12009-12-29 21:53:55 +0000483 Result = I->second;
Devang Patel256be962009-07-20 19:00:08 +0000484 return false;
485 }
486
487 // Check known forward references.
Chris Lattnere80250e2009-12-29 21:43:58 +0000488 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel256be962009-07-20 19:00:08 +0000489 FI = ForwardRefMDNodes.find(MID);
490 if (FI != ForwardRefMDNodes.end()) {
Chris Lattner442ffa12009-12-29 21:53:55 +0000491 Result = FI->second.first;
Devang Patel256be962009-07-20 19:00:08 +0000492 return false;
493 }
494
495 // Create MDNode forward reference
Devang Patel256be962009-07-20 19:00:08 +0000496 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Chris Lattnere80250e2009-12-29 21:43:58 +0000497 SmallVector<Value *, 1> Elts;
Owen Anderson647e3012009-07-31 21:35:40 +0000498 Elts.push_back(MDString::get(Context, FwdRefName));
499 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel256be962009-07-20 19:00:08 +0000500 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner442ffa12009-12-29 21:53:55 +0000501 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000502 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000503}
Devang Patel256be962009-07-20 19:00:08 +0000504
Devang Pateleff2ab62009-07-29 00:34:02 +0000505///ParseNamedMetadata:
506/// !foo = !{ !1, !2 }
507bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000508 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000509 Lex.Lex();
510 std::string Name = Lex.getStrVal();
511
512 if (ParseToken(lltok::equal, "expected '=' here"))
513 return true;
514
515 if (Lex.getKind() != lltok::Metadata)
516 return TokError("Expected '!' here");
517 Lex.Lex();
518
519 if (Lex.getKind() != lltok::lbrace)
520 return TokError("Expected '{' here");
521 Lex.Lex();
522 SmallVector<MetadataBase *, 8> Elts;
523 do {
Chris Lattner442ffa12009-12-29 21:53:55 +0000524 // FIXME: Eat if present.
Devang Pateleff2ab62009-07-29 00:34:02 +0000525 if (Lex.getKind() != lltok::Metadata)
526 return TokError("Expected '!' here");
527 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +0000528
529 // FIXME: Will crash on mdstrings etc.
530 MDNode *N = 0;
Devang Pateleff2ab62009-07-29 00:34:02 +0000531 if (ParseMDNode(N)) return true;
532 Elts.push_back(N);
533 } while (EatIfPresent(lltok::comma));
534
535 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
536 return true;
537
Owen Anderson1d0be152009-08-13 21:58:54 +0000538 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000539 return false;
540}
541
Devang Patel923078c2009-07-01 19:21:12 +0000542/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000543/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000544bool LLParser::ParseStandaloneMetadata() {
545 assert(Lex.getKind() == lltok::Metadata);
546 Lex.Lex();
547 unsigned MetadataID = 0;
548 if (ParseUInt32(MetadataID))
549 return true;
Chris Lattnere80250e2009-12-29 21:43:58 +0000550 if (MetadataCache.count(MetadataID))
Devang Patel923078c2009-07-01 19:21:12 +0000551 return TokError("Metadata id is already used");
552 if (ParseToken(lltok::equal, "expected '=' here"))
553 return true;
554
555 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel2214c942009-07-08 21:57:07 +0000557 if (ParseType(Ty, TyLoc))
Devang Patel923078c2009-07-01 19:21:12 +0000558 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000559
Devang Patel104cf9e2009-07-23 01:07:34 +0000560 if (Lex.getKind() != lltok::Metadata)
561 return TokError("Expected metadata here");
Devang Patel923078c2009-07-01 19:21:12 +0000562
Devang Patel104cf9e2009-07-23 01:07:34 +0000563 Lex.Lex();
564 if (Lex.getKind() != lltok::lbrace)
565 return TokError("Expected '{' here");
566
Chris Lattner442ffa12009-12-29 21:53:55 +0000567 // FIXME: This doesn't make sense here.
Devang Patel104cf9e2009-07-23 01:07:34 +0000568 SmallVector<Value *, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000569 if (ParseMDNodeVector(Elts)
Benjamin Kramer30d3b912009-07-27 09:06:52 +0000570 || ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000571 return true;
572
Owen Anderson647e3012009-07-31 21:35:40 +0000573 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000574 MetadataCache[MetadataID] = Init;
Chris Lattnere80250e2009-12-29 21:43:58 +0000575 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000576 FI = ForwardRefMDNodes.find(MetadataID);
577 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000578 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000579 ForwardRefMDNodes.erase(FI);
580 }
581
Devang Patel923078c2009-07-01 19:21:12 +0000582 return false;
583}
584
Victor Hernandez19715562009-12-03 23:40:58 +0000585/// ParseInlineMetadata:
586/// !{type %instr}
587/// !{...} MDNode
588/// !"foo" MDString
589bool LLParser::ParseInlineMetadata(Value *&V, PerFunctionState &PFS) {
590 assert(Lex.getKind() == lltok::Metadata && "Only for Metadata");
591 V = 0;
592
593 Lex.Lex();
594 if (Lex.getKind() == lltok::lbrace) {
595 Lex.Lex();
596 if (ParseTypeAndValue(V, PFS) ||
597 ParseToken(lltok::rbrace, "expected end of metadata node"))
598 return true;
599
600 Value *Vals[] = { V };
601 V = MDNode::get(Context, Vals, 1);
602 return false;
603 }
604
Chris Lattner442ffa12009-12-29 21:53:55 +0000605 // FIXME: This can't possibly work at all. r90497
606
Victor Hernandez19715562009-12-03 23:40:58 +0000607 // Standalone metadata reference
608 // !{ ..., !42, ... }
Chris Lattner442ffa12009-12-29 21:53:55 +0000609 if (!ParseMDNode((MDNode *&)V))
Victor Hernandez19715562009-12-03 23:40:58 +0000610 return false;
611
612 // MDString:
613 // '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000614 if (ParseMDString((MDString *&)V)) return true;
Victor Hernandez19715562009-12-03 23:40:58 +0000615 return false;
616}
617
Chris Lattnerdf986172009-01-02 07:01:27 +0000618/// ParseAlias:
619/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
620/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000621/// ::= TypeAndValue
622/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000623/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000624///
625/// Everything through visibility has already been parsed.
626///
627bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
628 unsigned Visibility) {
629 assert(Lex.getKind() == lltok::kw_alias);
630 Lex.Lex();
631 unsigned Linkage;
632 LocTy LinkageLoc = Lex.getLoc();
633 if (ParseOptionalLinkage(Linkage))
634 return true;
635
636 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000637 Linkage != GlobalValue::WeakAnyLinkage &&
638 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000639 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000640 Linkage != GlobalValue::PrivateLinkage &&
641 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000642 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000643
Chris Lattnerdf986172009-01-02 07:01:27 +0000644 Constant *Aliasee;
645 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000646 if (Lex.getKind() != lltok::kw_bitcast &&
647 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000648 if (ParseGlobalTypeAndValue(Aliasee)) return true;
649 } else {
650 // The bitcast dest type is not present, it is implied by the dest type.
651 ValID ID;
652 if (ParseValID(ID)) return true;
653 if (ID.Kind != ValID::t_Constant)
654 return Error(AliaseeLoc, "invalid aliasee");
655 Aliasee = ID.ConstantVal;
656 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 if (!isa<PointerType>(Aliasee->getType()))
659 return Error(AliaseeLoc, "alias must have pointer type");
660
661 // Okay, create the alias but do not insert it into the module yet.
662 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
663 (GlobalValue::LinkageTypes)Linkage, Name,
664 Aliasee);
665 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000666
Chris Lattnerdf986172009-01-02 07:01:27 +0000667 // See if this value already exists in the symbol table. If so, it is either
668 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000669 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 // See if this was a redefinition. If so, there is no entry in
671 // ForwardRefVals.
672 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
673 I = ForwardRefVals.find(Name);
674 if (I == ForwardRefVals.end())
675 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
676
677 // Otherwise, this was a definition of forward ref. Verify that types
678 // agree.
679 if (Val->getType() != GA->getType())
680 return Error(NameLoc,
681 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000682
Chris Lattnerdf986172009-01-02 07:01:27 +0000683 // If they agree, just RAUW the old value with the alias and remove the
684 // forward ref info.
685 Val->replaceAllUsesWith(GA);
686 Val->eraseFromParent();
687 ForwardRefVals.erase(I);
688 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000689
Chris Lattnerdf986172009-01-02 07:01:27 +0000690 // Insert into the module, we know its name won't collide now.
691 M->getAliasList().push_back(GA);
692 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000693
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 return false;
695}
696
697/// ParseGlobal
698/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
699/// OptionalAddrSpace GlobalType Type Const
700/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
701/// OptionalAddrSpace GlobalType Type Const
702///
703/// Everything through visibility has been parsed already.
704///
705bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
706 unsigned Linkage, bool HasLinkage,
707 unsigned Visibility) {
708 unsigned AddrSpace;
709 bool ThreadLocal, IsConstant;
710 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000711
Owen Anderson1d0be152009-08-13 21:58:54 +0000712 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000713 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
714 ParseOptionalAddrSpace(AddrSpace) ||
715 ParseGlobalType(IsConstant) ||
716 ParseType(Ty, TyLoc))
717 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattnerdf986172009-01-02 07:01:27 +0000719 // If the linkage is specified and is external, then no initializer is
720 // present.
721 Constant *Init = 0;
722 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000723 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000724 Linkage != GlobalValue::ExternalLinkage)) {
725 if (ParseGlobalValue(Ty, Init))
726 return true;
727 }
728
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000729 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000730 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731
Chris Lattnerdf986172009-01-02 07:01:27 +0000732 GlobalVariable *GV = 0;
733
734 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000735 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000736 if (GlobalValue *GVal = M->getNamedValue(Name)) {
737 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
738 return Error(NameLoc, "redefinition of global '@" + Name + "'");
739 GV = cast<GlobalVariable>(GVal);
740 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000741 } else {
742 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
743 I = ForwardRefValIDs.find(NumberedVals.size());
744 if (I != ForwardRefValIDs.end()) {
745 GV = cast<GlobalVariable>(I->second.first);
746 ForwardRefValIDs.erase(I);
747 }
748 }
749
750 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000752 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000753 } else {
754 if (GV->getType()->getElementType() != Ty)
755 return Error(TyLoc,
756 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 // Move the forward-reference to the correct spot in the module.
759 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
760 }
761
762 if (Name.empty())
763 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattnerdf986172009-01-02 07:01:27 +0000765 // Set the parsed properties on the global.
766 if (Init)
767 GV->setInitializer(Init);
768 GV->setConstant(IsConstant);
769 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
770 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
771 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 // Parse attributes on the global.
774 while (Lex.getKind() == lltok::comma) {
775 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattnerdf986172009-01-02 07:01:27 +0000777 if (Lex.getKind() == lltok::kw_section) {
778 Lex.Lex();
779 GV->setSection(Lex.getStrVal());
780 if (ParseToken(lltok::StringConstant, "expected global section string"))
781 return true;
782 } else if (Lex.getKind() == lltok::kw_align) {
783 unsigned Alignment;
784 if (ParseOptionalAlignment(Alignment)) return true;
785 GV->setAlignment(Alignment);
786 } else {
787 TokError("unknown global variable property!");
788 }
789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000790
Chris Lattnerdf986172009-01-02 07:01:27 +0000791 return false;
792}
793
794
795//===----------------------------------------------------------------------===//
796// GlobalValue Reference/Resolution Routines.
797//===----------------------------------------------------------------------===//
798
799/// GetGlobalVal - Get a value with the specified name or ID, creating a
800/// forward reference record if needed. This can return null if the value
801/// exists but does not have the right type.
802GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
803 LocTy Loc) {
804 const PointerType *PTy = dyn_cast<PointerType>(Ty);
805 if (PTy == 0) {
806 Error(Loc, "global variable reference must have pointer type");
807 return 0;
808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Chris Lattnerdf986172009-01-02 07:01:27 +0000810 // Look this name up in the normal function symbol table.
811 GlobalValue *Val =
812 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattnerdf986172009-01-02 07:01:27 +0000814 // If this is a forward reference for the value, see if we already created a
815 // forward ref record.
816 if (Val == 0) {
817 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
818 I = ForwardRefVals.find(Name);
819 if (I != ForwardRefVals.end())
820 Val = I->second.first;
821 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000822
Chris Lattnerdf986172009-01-02 07:01:27 +0000823 // If we have the value in the symbol table or fwd-ref table, return it.
824 if (Val) {
825 if (Val->getType() == Ty) return Val;
826 Error(Loc, "'@" + Name + "' defined with type '" +
827 Val->getType()->getDescription() + "'");
828 return 0;
829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Chris Lattnerdf986172009-01-02 07:01:27 +0000831 // Otherwise, create a new forward reference for this value and remember it.
832 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000833 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
834 // Function types can return opaque but functions can't.
835 if (isa<OpaqueType>(FT->getReturnType())) {
836 Error(Loc, "function may not return opaque type");
837 return 0;
838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000840 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000841 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000842 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
843 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000844 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000845
Chris Lattnerdf986172009-01-02 07:01:27 +0000846 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
847 return FwdVal;
848}
849
850GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
851 const PointerType *PTy = dyn_cast<PointerType>(Ty);
852 if (PTy == 0) {
853 Error(Loc, "global variable reference must have pointer type");
854 return 0;
855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000856
Chris Lattnerdf986172009-01-02 07:01:27 +0000857 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000858
Chris Lattnerdf986172009-01-02 07:01:27 +0000859 // If this is a forward reference for the value, see if we already created a
860 // forward ref record.
861 if (Val == 0) {
862 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
863 I = ForwardRefValIDs.find(ID);
864 if (I != ForwardRefValIDs.end())
865 Val = I->second.first;
866 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000867
Chris Lattnerdf986172009-01-02 07:01:27 +0000868 // If we have the value in the symbol table or fwd-ref table, return it.
869 if (Val) {
870 if (Val->getType() == Ty) return Val;
871 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
872 Val->getType()->getDescription() + "'");
873 return 0;
874 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000875
Chris Lattnerdf986172009-01-02 07:01:27 +0000876 // Otherwise, create a new forward reference for this value and remember it.
877 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000878 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
879 // Function types can return opaque but functions can't.
880 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000881 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000882 return 0;
883 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000884 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000885 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000886 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
887 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000888 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000889
Chris Lattnerdf986172009-01-02 07:01:27 +0000890 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
891 return FwdVal;
892}
893
894
895//===----------------------------------------------------------------------===//
896// Helper Routines.
897//===----------------------------------------------------------------------===//
898
899/// ParseToken - If the current token has the specified kind, eat it and return
900/// success. Otherwise, emit the specified error and return failure.
901bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
902 if (Lex.getKind() != T)
903 return TokError(ErrMsg);
904 Lex.Lex();
905 return false;
906}
907
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000908/// ParseStringConstant
909/// ::= StringConstant
910bool LLParser::ParseStringConstant(std::string &Result) {
911 if (Lex.getKind() != lltok::StringConstant)
912 return TokError("expected string constant");
913 Result = Lex.getStrVal();
914 Lex.Lex();
915 return false;
916}
917
918/// ParseUInt32
919/// ::= uint32
920bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000921 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
922 return TokError("expected integer");
923 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
924 if (Val64 != unsigned(Val64))
925 return TokError("expected 32-bit integer (too large)");
926 Val = Val64;
927 Lex.Lex();
928 return false;
929}
930
931
932/// ParseOptionalAddrSpace
933/// := /*empty*/
934/// := 'addrspace' '(' uint32 ')'
935bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
936 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000937 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000938 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000939 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000940 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000941 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000942}
Chris Lattnerdf986172009-01-02 07:01:27 +0000943
944/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
945/// indicates what kind of attribute list this is: 0: function arg, 1: result,
946/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000947/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000948bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
949 Attrs = Attribute::None;
950 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000951
Chris Lattnerdf986172009-01-02 07:01:27 +0000952 while (1) {
953 switch (Lex.getKind()) {
954 case lltok::kw_sext:
955 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000956 // Treat these as signext/zeroext if they occur in the argument list after
957 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
958 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
959 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000960 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000961 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000962 if (Lex.getKind() == lltok::kw_sext)
963 Attrs |= Attribute::SExt;
964 else
965 Attrs |= Attribute::ZExt;
966 break;
967 }
968 // FALL THROUGH.
969 default: // End of attributes.
970 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
971 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000973 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000974 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000975
Chris Lattnerdf986172009-01-02 07:01:27 +0000976 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000977 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
978 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
979 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
980 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
981 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
982 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
983 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
984 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000985
Devang Patel578efa92009-06-05 21:57:13 +0000986 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
987 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
988 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
989 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
990 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000991 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000992 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
993 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
994 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
995 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
996 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
997 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000998 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000999
Chris Lattnerdf986172009-01-02 07:01:27 +00001000 case lltok::kw_align: {
1001 unsigned Alignment;
1002 if (ParseOptionalAlignment(Alignment))
1003 return true;
1004 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1005 continue;
1006 }
1007 }
1008 Lex.Lex();
1009 }
1010}
1011
1012/// ParseOptionalLinkage
1013/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001014/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001015/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +00001016/// ::= 'internal'
1017/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001018/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001019/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001020/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001021/// ::= 'appending'
1022/// ::= 'dllexport'
1023/// ::= 'common'
1024/// ::= 'dllimport'
1025/// ::= 'extern_weak'
1026/// ::= 'external'
1027bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1028 HasLinkage = false;
1029 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001030 default: Res=GlobalValue::ExternalLinkage; return false;
1031 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1032 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1033 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1034 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1035 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1036 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1037 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001038 case lltok::kw_available_externally:
1039 Res = GlobalValue::AvailableExternallyLinkage;
1040 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001041 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1042 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1043 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1044 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1045 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1046 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001047 }
1048 Lex.Lex();
1049 HasLinkage = true;
1050 return false;
1051}
1052
1053/// ParseOptionalVisibility
1054/// ::= /*empty*/
1055/// ::= 'default'
1056/// ::= 'hidden'
1057/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001058///
Chris Lattnerdf986172009-01-02 07:01:27 +00001059bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1060 switch (Lex.getKind()) {
1061 default: Res = GlobalValue::DefaultVisibility; return false;
1062 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1063 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1064 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1065 }
1066 Lex.Lex();
1067 return false;
1068}
1069
1070/// ParseOptionalCallingConv
1071/// ::= /*empty*/
1072/// ::= 'ccc'
1073/// ::= 'fastcc'
1074/// ::= 'coldcc'
1075/// ::= 'x86_stdcallcc'
1076/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001077/// ::= 'arm_apcscc'
1078/// ::= 'arm_aapcscc'
1079/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001080/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001081/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001082///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001083bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001084 switch (Lex.getKind()) {
1085 default: CC = CallingConv::C; return false;
1086 case lltok::kw_ccc: CC = CallingConv::C; break;
1087 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1088 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1089 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1090 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001091 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1092 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1093 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001094 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001095 case lltok::kw_cc: {
1096 unsigned ArbitraryCC;
1097 Lex.Lex();
1098 if (ParseUInt32(ArbitraryCC)) {
1099 return true;
1100 } else
1101 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1102 return false;
1103 }
1104 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001105 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001106
Chris Lattnerdf986172009-01-02 07:01:27 +00001107 Lex.Lex();
1108 return false;
1109}
1110
Devang Patel0475c912009-09-29 00:01:14 +00001111/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001112/// ::= /* empty */
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001113/// ::= !dbg !42 (',' !dbg !57)*
Devang Patel0475c912009-09-29 00:01:14 +00001114bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001115 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001116 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001117
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001118 while (1) {
1119 std::string Name = Lex.getStrVal();
1120 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001121
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001122 if (Lex.getKind() != lltok::Metadata)
1123 return TokError("expected '!' here");
1124 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001125
Chris Lattner442ffa12009-12-29 21:53:55 +00001126 MDNode *Node;
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001127 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001128
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001129 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner442ffa12009-12-29 21:53:55 +00001130 MDsOnInst.push_back(std::make_pair(MDK, Node));
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001131
1132 // If this is the end of the list, we're done.
1133 if (!EatIfPresent(lltok::comma))
1134 return false;
1135
1136 // The next value must be a custom metadata id.
1137 if (Lex.getKind() != lltok::NamedOrCustomMD)
1138 return TokError("expected more custom metadata ids");
1139 }
Devang Patelf633a062009-09-17 23:04:48 +00001140}
1141
Chris Lattnerdf986172009-01-02 07:01:27 +00001142/// ParseOptionalAlignment
1143/// ::= /* empty */
1144/// ::= 'align' 4
1145bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1146 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001147 if (!EatIfPresent(lltok::kw_align))
1148 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001149 LocTy AlignLoc = Lex.getLoc();
1150 if (ParseUInt32(Alignment)) return true;
1151 if (!isPowerOf2_32(Alignment))
1152 return Error(AlignLoc, "alignment is not a power of two");
1153 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001154}
1155
Devang Patelf633a062009-09-17 23:04:48 +00001156/// ParseOptionalInfo
1157/// ::= OptionalInfo (',' OptionalInfo)+
1158bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1159
1160 // FIXME: Handle customized metadata info attached with an instruction.
1161 do {
Devang Patel0475c912009-09-29 00:01:14 +00001162 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1163 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001164 } else if (Lex.getKind() == lltok::kw_align) {
1165 if (ParseOptionalAlignment(Alignment)) return true;
1166 } else
1167 return true;
1168 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001169
Devang Patelf633a062009-09-17 23:04:48 +00001170 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001171}
1172
Devang Patelf633a062009-09-17 23:04:48 +00001173
Chris Lattnerdf986172009-01-02 07:01:27 +00001174/// ParseIndexList
1175/// ::= (',' uint32)+
1176bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1177 if (Lex.getKind() != lltok::comma)
1178 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001179
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001180 while (EatIfPresent(lltok::comma)) {
Devang Patele8bc45a2009-11-03 19:06:07 +00001181 if (Lex.getKind() == lltok::NamedOrCustomMD)
1182 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001183 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001184 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001185 Indices.push_back(Idx);
1186 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 return false;
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// Type Parsing.
1193//===----------------------------------------------------------------------===//
1194
1195/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001196bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1197 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001198 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001199
Chris Lattnerdf986172009-01-02 07:01:27 +00001200 // Verify no unresolved uprefs.
1201 if (!UpRefs.empty())
1202 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001203
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001204 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001205 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Chris Lattnerdf986172009-01-02 07:01:27 +00001207 return false;
1208}
1209
1210/// HandleUpRefs - Every time we finish a new layer of types, this function is
1211/// called. It loops through the UpRefs vector, which is a list of the
1212/// currently active types. For each type, if the up-reference is contained in
1213/// the newly completed type, we decrement the level count. When the level
1214/// count reaches zero, the up-referenced type is the type that is passed in:
1215/// thus we can complete the cycle.
1216///
1217PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1218 // If Ty isn't abstract, or if there are no up-references in it, then there is
1219 // nothing to resolve here.
1220 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001221
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 PATypeHolder Ty(ty);
1223#if 0
David Greene0e28d762009-12-23 23:38:28 +00001224 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 << "' newly formed. Resolving upreferences.\n"
1226 << UpRefs.size() << " upreferences active!\n";
1227#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1230 // to zero), we resolve them all together before we resolve them to Ty. At
1231 // the end of the loop, if there is anything to resolve to Ty, it will be in
1232 // this variable.
1233 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001234
Chris Lattnerdf986172009-01-02 07:01:27 +00001235 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1236 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1237 bool ContainsType =
1238 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1239 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001240
Chris Lattnerdf986172009-01-02 07:01:27 +00001241#if 0
David Greene0e28d762009-12-23 23:38:28 +00001242 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1244 << (ContainsType ? "true" : "false")
1245 << " level=" << UpRefs[i].NestingLevel << "\n";
1246#endif
1247 if (!ContainsType)
1248 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001249
Chris Lattnerdf986172009-01-02 07:01:27 +00001250 // Decrement level of upreference
1251 unsigned Level = --UpRefs[i].NestingLevel;
1252 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001253
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1255 if (Level != 0)
1256 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001257
Chris Lattnerdf986172009-01-02 07:01:27 +00001258#if 0
David Greene0e28d762009-12-23 23:38:28 +00001259 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001260#endif
1261 if (!TypeToResolve)
1262 TypeToResolve = UpRefs[i].UpRefTy;
1263 else
1264 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1265 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1266 --i; // Do not skip the next element.
1267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001268
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 if (TypeToResolve)
1270 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001271
Chris Lattnerdf986172009-01-02 07:01:27 +00001272 return Ty;
1273}
1274
1275
1276/// ParseTypeRec - The recursive function used to process the internal
1277/// implementation details of types.
1278bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1279 switch (Lex.getKind()) {
1280 default:
1281 return TokError("expected type");
1282 case lltok::Type:
1283 // TypeRec ::= 'float' | 'void' (etc)
1284 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 break;
1287 case lltok::kw_opaque:
1288 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001289 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001290 Lex.Lex();
1291 break;
1292 case lltok::lbrace:
1293 // TypeRec ::= '{' ... '}'
1294 if (ParseStructType(Result, false))
1295 return true;
1296 break;
1297 case lltok::lsquare:
1298 // TypeRec ::= '[' ... ']'
1299 Lex.Lex(); // eat the lsquare.
1300 if (ParseArrayVectorType(Result, false))
1301 return true;
1302 break;
1303 case lltok::less: // Either vector or packed struct.
1304 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001305 Lex.Lex();
1306 if (Lex.getKind() == lltok::lbrace) {
1307 if (ParseStructType(Result, true) ||
1308 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 } else if (ParseArrayVectorType(Result, true))
1311 return true;
1312 break;
1313 case lltok::LocalVar:
1314 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1315 // TypeRec ::= %foo
1316 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1317 Result = T;
1318 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001319 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1321 std::make_pair(Result,
1322 Lex.getLoc())));
1323 M->addTypeName(Lex.getStrVal(), Result.get());
1324 }
1325 Lex.Lex();
1326 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001327
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 case lltok::LocalVarID:
1329 // TypeRec ::= %4
1330 if (Lex.getUIntVal() < NumberedTypes.size())
1331 Result = NumberedTypes[Lex.getUIntVal()];
1332 else {
1333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1334 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1335 if (I != ForwardRefTypeIDs.end())
1336 Result = I->second.first;
1337 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001338 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001339 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1340 std::make_pair(Result,
1341 Lex.getLoc())));
1342 }
1343 }
1344 Lex.Lex();
1345 break;
1346 case lltok::backslash: {
1347 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001348 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001349 unsigned Val;
1350 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001351 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1353 Result = OT;
1354 break;
1355 }
1356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001357
1358 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001359 while (1) {
1360 switch (Lex.getKind()) {
1361 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001362 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001363
1364 // TypeRec ::= TypeRec '*'
1365 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001366 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001367 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001368 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001369 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001370 if (!PointerType::isValidElementType(Result.get()))
1371 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001372 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001373 Lex.Lex();
1374 break;
1375
1376 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1377 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001378 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001379 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001380 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001381 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001382 if (!PointerType::isValidElementType(Result.get()))
1383 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001384 unsigned AddrSpace;
1385 if (ParseOptionalAddrSpace(AddrSpace) ||
1386 ParseToken(lltok::star, "expected '*' in address space"))
1387 return true;
1388
Owen Andersondebcb012009-07-29 22:17:13 +00001389 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 break;
1391 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001392
Chris Lattnerdf986172009-01-02 07:01:27 +00001393 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1394 case lltok::lparen:
1395 if (ParseFunctionType(Result))
1396 return true;
1397 break;
1398 }
1399 }
1400}
1401
1402/// ParseParameterList
1403/// ::= '(' ')'
1404/// ::= '(' Arg (',' Arg)* ')'
1405/// Arg
1406/// ::= Type OptionalAttributes Value OptionalAttributes
1407bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1408 PerFunctionState &PFS) {
1409 if (ParseToken(lltok::lparen, "expected '(' in call"))
1410 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001411
Chris Lattnerdf986172009-01-02 07:01:27 +00001412 while (Lex.getKind() != lltok::rparen) {
1413 // If this isn't the first argument, we need a comma.
1414 if (!ArgList.empty() &&
1415 ParseToken(lltok::comma, "expected ',' in argument list"))
1416 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001417
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 // Parse the argument.
1419 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001420 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001421 unsigned ArgAttrs1 = Attribute::None;
1422 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001423 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001424 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001426
1427 if (Lex.getKind() == lltok::Metadata) {
1428 if (ParseInlineMetadata(V, PFS))
1429 return true;
1430 } else {
1431 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1432 ParseValue(ArgTy, V, PFS) ||
1433 // FIXME: Should not allow attributes after the argument, remove this
1434 // in LLVM 3.0.
1435 ParseOptionalAttrs(ArgAttrs2, 3))
1436 return true;
1437 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001438 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1439 }
1440
1441 Lex.Lex(); // Lex the ')'.
1442 return false;
1443}
1444
1445
1446
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001447/// ParseArgumentList - Parse the argument list for a function type or function
1448/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001449/// ::= '(' ArgTypeListI ')'
1450/// ArgTypeListI
1451/// ::= /*empty*/
1452/// ::= '...'
1453/// ::= ArgTypeList ',' '...'
1454/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001455///
Chris Lattnerdf986172009-01-02 07:01:27 +00001456bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001457 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 isVarArg = false;
1459 assert(Lex.getKind() == lltok::lparen);
1460 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 if (Lex.getKind() == lltok::rparen) {
1463 // empty
1464 } else if (Lex.getKind() == lltok::dotdotdot) {
1465 isVarArg = true;
1466 Lex.Lex();
1467 } else {
1468 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001469 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001470 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001472
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001473 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1474 // types (such as a function returning a pointer to itself). If parsing a
1475 // function prototype, we require fully resolved types.
1476 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001477 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001478
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001479 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001480 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001481
Chris Lattnerdf986172009-01-02 07:01:27 +00001482 if (Lex.getKind() == lltok::LocalVar ||
1483 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1484 Name = Lex.getStrVal();
1485 Lex.Lex();
1486 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001487
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001488 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001489 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001490
Chris Lattnerdf986172009-01-02 07:01:27 +00001491 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001492
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001493 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001495 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001496 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 break;
1498 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattnerdf986172009-01-02 07:01:27 +00001500 // Otherwise must be an argument type.
1501 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001502 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001503 ParseOptionalAttrs(Attrs, 0)) return true;
1504
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001505 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001506 return Error(TypeLoc, "argument can not have void type");
1507
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 if (Lex.getKind() == lltok::LocalVar ||
1509 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1510 Name = Lex.getStrVal();
1511 Lex.Lex();
1512 } else {
1513 Name = "";
1514 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001515
1516 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1517 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001518
Chris Lattnerdf986172009-01-02 07:01:27 +00001519 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1520 }
1521 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001523 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001524}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnerdf986172009-01-02 07:01:27 +00001526/// ParseFunctionType
1527/// ::= Type ArgumentList OptionalAttrs
1528bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1529 assert(Lex.getKind() == lltok::lparen);
1530
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001531 if (!FunctionType::isValidReturnType(Result))
1532 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 std::vector<ArgInfo> ArgList;
1535 bool isVarArg;
1536 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001537 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001538 // FIXME: Allow, but ignore attributes on function types!
1539 // FIXME: Remove in LLVM 3.0
1540 ParseOptionalAttrs(Attrs, 2))
1541 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001542
Chris Lattnerdf986172009-01-02 07:01:27 +00001543 // Reject names on the arguments lists.
1544 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1545 if (!ArgList[i].Name.empty())
1546 return Error(ArgList[i].Loc, "argument name invalid in function type");
1547 if (!ArgList[i].Attrs != 0) {
1548 // Allow but ignore attributes on function types; this permits
1549 // auto-upgrade.
1550 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1551 }
1552 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001553
Chris Lattnerdf986172009-01-02 07:01:27 +00001554 std::vector<const Type*> ArgListTy;
1555 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1556 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001557
Owen Andersondebcb012009-07-29 22:17:13 +00001558 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001559 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001560 return false;
1561}
1562
1563/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1564/// TypeRec
1565/// ::= '{' '}'
1566/// ::= '{' TypeRec (',' TypeRec)* '}'
1567/// ::= '<' '{' '}' '>'
1568/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1569bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1570 assert(Lex.getKind() == lltok::lbrace);
1571 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001573 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001574 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001575 return false;
1576 }
1577
1578 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001579 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 if (ParseTypeRec(Result)) return true;
1581 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001582
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001583 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001584 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001585 if (!StructType::isValidElementType(Result))
1586 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001588 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001589 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001591
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001592 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001593 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001594 if (!StructType::isValidElementType(Result))
1595 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001596
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 ParamsList.push_back(Result);
1598 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001599
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001600 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1601 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattnerdf986172009-01-02 07:01:27 +00001603 std::vector<const Type*> ParamsListTy;
1604 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1605 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001606 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001607 return false;
1608}
1609
1610/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1611/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001612/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001613/// ::= '[' APSINTVAL 'x' Types ']'
1614/// ::= '<' APSINTVAL 'x' Types '>'
1615bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1616 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1617 Lex.getAPSIntVal().getBitWidth() > 64)
1618 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001619
Chris Lattnerdf986172009-01-02 07:01:27 +00001620 LocTy SizeLoc = Lex.getLoc();
1621 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001622 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001623
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001624 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1625 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001626
1627 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001628 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001630
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001631 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001632 return Error(TypeLoc, "array and vector element type cannot be void");
1633
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001634 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1635 "expected end of sequential type"))
1636 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001637
Chris Lattnerdf986172009-01-02 07:01:27 +00001638 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001639 if (Size == 0)
1640 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 if ((unsigned)Size != Size)
1642 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001643 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001645 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001646 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001647 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001649 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001650 }
1651 return false;
1652}
1653
1654//===----------------------------------------------------------------------===//
1655// Function Semantic Analysis.
1656//===----------------------------------------------------------------------===//
1657
Chris Lattner09d9ef42009-10-28 03:39:23 +00001658LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1659 int functionNumber)
1660 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001661
1662 // Insert unnamed arguments into the NumberedVals list.
1663 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1664 AI != E; ++AI)
1665 if (!AI->hasName())
1666 NumberedVals.push_back(AI);
1667}
1668
1669LLParser::PerFunctionState::~PerFunctionState() {
1670 // If there were any forward referenced non-basicblock values, delete them.
1671 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1672 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1673 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001674 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001675 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001676 delete I->second.first;
1677 I->second.first = 0;
1678 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001679
Chris Lattnerdf986172009-01-02 07:01:27 +00001680 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1681 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1682 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001683 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001684 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001685 delete I->second.first;
1686 I->second.first = 0;
1687 }
1688}
1689
Chris Lattner09d9ef42009-10-28 03:39:23 +00001690bool LLParser::PerFunctionState::FinishFunction() {
1691 // Check to see if someone took the address of labels in this block.
1692 if (!P.ForwardRefBlockAddresses.empty()) {
1693 ValID FunctionID;
1694 if (!F.getName().empty()) {
1695 FunctionID.Kind = ValID::t_GlobalName;
1696 FunctionID.StrVal = F.getName();
1697 } else {
1698 FunctionID.Kind = ValID::t_GlobalID;
1699 FunctionID.UIntVal = FunctionNumber;
1700 }
1701
1702 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1703 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1704 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1705 // Resolve all these references.
1706 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1707 return true;
1708
1709 P.ForwardRefBlockAddresses.erase(FRBAI);
1710 }
1711 }
1712
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 if (!ForwardRefVals.empty())
1714 return P.Error(ForwardRefVals.begin()->second.second,
1715 "use of undefined value '%" + ForwardRefVals.begin()->first +
1716 "'");
1717 if (!ForwardRefValIDs.empty())
1718 return P.Error(ForwardRefValIDs.begin()->second.second,
1719 "use of undefined value '%" +
1720 utostr(ForwardRefValIDs.begin()->first) + "'");
1721 return false;
1722}
1723
1724
1725/// GetVal - Get a value with the specified name or ID, creating a
1726/// forward reference record if needed. This can return null if the value
1727/// exists but does not have the right type.
1728Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1729 const Type *Ty, LocTy Loc) {
1730 // Look this name up in the normal function symbol table.
1731 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001732
Chris Lattnerdf986172009-01-02 07:01:27 +00001733 // If this is a forward reference for the value, see if we already created a
1734 // forward ref record.
1735 if (Val == 0) {
1736 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1737 I = ForwardRefVals.find(Name);
1738 if (I != ForwardRefVals.end())
1739 Val = I->second.first;
1740 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001741
Chris Lattnerdf986172009-01-02 07:01:27 +00001742 // If we have the value in the symbol table or fwd-ref table, return it.
1743 if (Val) {
1744 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001745 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001746 P.Error(Loc, "'%" + Name + "' is not a basic block");
1747 else
1748 P.Error(Loc, "'%" + Name + "' defined with type '" +
1749 Val->getType()->getDescription() + "'");
1750 return 0;
1751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001752
Chris Lattnerdf986172009-01-02 07:01:27 +00001753 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001754 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1755 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001756 P.Error(Loc, "invalid use of a non-first-class type");
1757 return 0;
1758 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001759
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 // Otherwise, create a new forward reference for this value and remember it.
1761 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001762 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001763 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001764 else
1765 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001766
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1768 return FwdVal;
1769}
1770
1771Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1772 LocTy Loc) {
1773 // Look this name up in the normal function symbol table.
1774 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001775
Chris Lattnerdf986172009-01-02 07:01:27 +00001776 // If this is a forward reference for the value, see if we already created a
1777 // forward ref record.
1778 if (Val == 0) {
1779 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1780 I = ForwardRefValIDs.find(ID);
1781 if (I != ForwardRefValIDs.end())
1782 Val = I->second.first;
1783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 // If we have the value in the symbol table or fwd-ref table, return it.
1786 if (Val) {
1787 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001788 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1790 else
1791 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1792 Val->getType()->getDescription() + "'");
1793 return 0;
1794 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001795
Owen Anderson1d0be152009-08-13 21:58:54 +00001796 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1797 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 P.Error(Loc, "invalid use of a non-first-class type");
1799 return 0;
1800 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001801
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 // Otherwise, create a new forward reference for this value and remember it.
1803 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001804 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001805 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 else
1807 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001808
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1810 return FwdVal;
1811}
1812
1813/// SetInstName - After an instruction is parsed and inserted into its
1814/// basic block, this installs its name.
1815bool LLParser::PerFunctionState::SetInstName(int NameID,
1816 const std::string &NameStr,
1817 LocTy NameLoc, Instruction *Inst) {
1818 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001819 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001820 if (NameID != -1 || !NameStr.empty())
1821 return P.Error(NameLoc, "instructions returning void cannot have a name");
1822 return false;
1823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001824
Chris Lattnerdf986172009-01-02 07:01:27 +00001825 // If this was a numbered instruction, verify that the instruction is the
1826 // expected value and resolve any forward references.
1827 if (NameStr.empty()) {
1828 // If neither a name nor an ID was specified, just use the next ID.
1829 if (NameID == -1)
1830 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Chris Lattnerdf986172009-01-02 07:01:27 +00001832 if (unsigned(NameID) != NumberedVals.size())
1833 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1834 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001835
Chris Lattnerdf986172009-01-02 07:01:27 +00001836 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1837 ForwardRefValIDs.find(NameID);
1838 if (FI != ForwardRefValIDs.end()) {
1839 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001841 FI->second.first->getType()->getDescription() + "'");
1842 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001843 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001844 ForwardRefValIDs.erase(FI);
1845 }
1846
1847 NumberedVals.push_back(Inst);
1848 return false;
1849 }
1850
1851 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1852 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1853 FI = ForwardRefVals.find(NameStr);
1854 if (FI != ForwardRefVals.end()) {
1855 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 FI->second.first->getType()->getDescription() + "'");
1858 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001859 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001860 ForwardRefVals.erase(FI);
1861 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 // Set the name on the instruction.
1864 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Chris Lattnerdf986172009-01-02 07:01:27 +00001866 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 NameStr + "'");
1869 return false;
1870}
1871
1872/// GetBB - Get a basic block with the specified name or ID, creating a
1873/// forward reference record if needed.
1874BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1875 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001876 return cast_or_null<BasicBlock>(GetVal(Name,
1877 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001878}
1879
1880BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001881 return cast_or_null<BasicBlock>(GetVal(ID,
1882 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001883}
1884
1885/// DefineBB - Define the specified basic block, which is either named or
1886/// unnamed. If there is an error, this returns null otherwise it returns
1887/// the block being defined.
1888BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1889 LocTy Loc) {
1890 BasicBlock *BB;
1891 if (Name.empty())
1892 BB = GetBB(NumberedVals.size(), Loc);
1893 else
1894 BB = GetBB(Name, Loc);
1895 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Chris Lattnerdf986172009-01-02 07:01:27 +00001897 // Move the block to the end of the function. Forward ref'd blocks are
1898 // inserted wherever they happen to be referenced.
1899 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattnerdf986172009-01-02 07:01:27 +00001901 // Remove the block from forward ref sets.
1902 if (Name.empty()) {
1903 ForwardRefValIDs.erase(NumberedVals.size());
1904 NumberedVals.push_back(BB);
1905 } else {
1906 // BB forward references are already in the function symbol table.
1907 ForwardRefVals.erase(Name);
1908 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909
Chris Lattnerdf986172009-01-02 07:01:27 +00001910 return BB;
1911}
1912
1913//===----------------------------------------------------------------------===//
1914// Constants.
1915//===----------------------------------------------------------------------===//
1916
1917/// ParseValID - Parse an abstract value that doesn't necessarily have a
1918/// type implied. For example, if we parse "4" we don't know what integer type
1919/// it has. The value will later be combined with its type and checked for
1920/// sanity.
1921bool LLParser::ParseValID(ValID &ID) {
1922 ID.Loc = Lex.getLoc();
1923 switch (Lex.getKind()) {
1924 default: return TokError("expected value token");
1925 case lltok::GlobalID: // @42
1926 ID.UIntVal = Lex.getUIntVal();
1927 ID.Kind = ValID::t_GlobalID;
1928 break;
1929 case lltok::GlobalVar: // @foo
1930 ID.StrVal = Lex.getStrVal();
1931 ID.Kind = ValID::t_GlobalName;
1932 break;
1933 case lltok::LocalVarID: // %42
1934 ID.UIntVal = Lex.getUIntVal();
1935 ID.Kind = ValID::t_LocalID;
1936 break;
1937 case lltok::LocalVar: // %foo
1938 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1939 ID.StrVal = Lex.getStrVal();
1940 ID.Kind = ValID::t_LocalName;
1941 break;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001942 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
Devang Patel104cf9e2009-07-23 01:07:34 +00001943 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001944 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00001945
1946 // FIXME: This doesn't belong here.
Nick Lewycky21cc4462009-04-04 07:22:01 +00001947 if (Lex.getKind() == lltok::lbrace) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001948 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001949 if (ParseMDNodeVector(Elts) ||
1950 ParseToken(lltok::rbrace, "expected end of metadata node"))
1951 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001952
Owen Anderson647e3012009-07-31 21:35:40 +00001953 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
Nick Lewycky21cc4462009-04-04 07:22:01 +00001954 return false;
1955 }
1956
Devang Patel923078c2009-07-01 19:21:12 +00001957 // Standalone metadata reference
1958 // !{ ..., !42, ... }
Chris Lattner442ffa12009-12-29 21:53:55 +00001959 // FIXME: Split MetadataVal into one for MDNode and one for MDString.
1960 if (!ParseMDNode((MDNode*&)ID.MetadataVal))
Devang Patel923078c2009-07-01 19:21:12 +00001961 return false;
Devang Patel256be962009-07-20 19:00:08 +00001962
Nick Lewycky21cc4462009-04-04 07:22:01 +00001963 // MDString:
1964 // ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +00001965 if (ParseMDString((MDString*&)ID.MetadataVal)) return true;
Devang Patele54abc92009-07-22 17:43:22 +00001966 ID.Kind = ValID::t_Metadata;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001967 return false;
1968 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 ID.Kind = ValID::t_APSInt;
1972 break;
1973 case lltok::APFloat:
1974 ID.APFloatVal = Lex.getAPFloatVal();
1975 ID.Kind = ValID::t_APFloat;
1976 break;
1977 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001978 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001979 ID.Kind = ValID::t_Constant;
1980 break;
1981 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001982 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Kind = ValID::t_Constant;
1984 break;
1985 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1986 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1987 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001988
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 case lltok::lbrace: {
1990 // ValID ::= '{' ConstVector '}'
1991 Lex.Lex();
1992 SmallVector<Constant*, 16> Elts;
1993 if (ParseGlobalValueVector(Elts) ||
1994 ParseToken(lltok::rbrace, "expected end of struct constant"))
1995 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001996
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001997 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1998 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 ID.Kind = ValID::t_Constant;
2000 return false;
2001 }
2002 case lltok::less: {
2003 // ValID ::= '<' ConstVector '>' --> Vector.
2004 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2005 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002006 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 SmallVector<Constant*, 16> Elts;
2009 LocTy FirstEltLoc = Lex.getLoc();
2010 if (ParseGlobalValueVector(Elts) ||
2011 (isPackedStruct &&
2012 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2013 ParseToken(lltok::greater, "expected end of constant"))
2014 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002017 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002018 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002019 ID.Kind = ValID::t_Constant;
2020 return false;
2021 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (Elts.empty())
2024 return Error(ID.Loc, "constant vector must not be empty");
2025
2026 if (!Elts[0]->getType()->isInteger() &&
2027 !Elts[0]->getType()->isFloatingPoint())
2028 return Error(FirstEltLoc,
2029 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002030
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 // Verify that all the vector elements have the same type.
2032 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2033 if (Elts[i]->getType() != Elts[0]->getType())
2034 return Error(FirstEltLoc,
2035 "vector element #" + utostr(i) +
2036 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002037
Owen Andersonaf7ec972009-07-28 21:19:26 +00002038 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_Constant;
2040 return false;
2041 }
2042 case lltok::lsquare: { // Array Constant
2043 Lex.Lex();
2044 SmallVector<Constant*, 16> Elts;
2045 LocTy FirstEltLoc = Lex.getLoc();
2046 if (ParseGlobalValueVector(Elts) ||
2047 ParseToken(lltok::rsquare, "expected end of array constant"))
2048 return true;
2049
2050 // Handle empty element.
2051 if (Elts.empty()) {
2052 // Use undef instead of an array because it's inconvenient to determine
2053 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002054 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 return false;
2056 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002057
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002060 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Owen Andersondebcb012009-07-29 22:17:13 +00002062 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002063
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002065 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 if (Elts[i]->getType() != Elts[0]->getType())
2067 return Error(FirstEltLoc,
2068 "array element #" + utostr(i) +
2069 " is not of type '" +Elts[0]->getType()->getDescription());
2070 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Owen Anderson1fd70962009-07-28 18:32:17 +00002072 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 ID.Kind = ValID::t_Constant;
2074 return false;
2075 }
2076 case lltok::kw_c: // c "foo"
2077 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002078 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002079 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2080 ID.Kind = ValID::t_Constant;
2081 return false;
2082
2083 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002084 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2085 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 Lex.Lex();
2087 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002088 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002089 ParseStringConstant(ID.StrVal) ||
2090 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ParseToken(lltok::StringConstant, "expected constraint string"))
2092 return true;
2093 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002094 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 ID.Kind = ValID::t_InlineAsm;
2096 return false;
2097 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Chris Lattner09d9ef42009-10-28 03:39:23 +00002099 case lltok::kw_blockaddress: {
2100 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2101 Lex.Lex();
2102
2103 ValID Fn, Label;
2104 LocTy FnLoc, LabelLoc;
2105
2106 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2107 ParseValID(Fn) ||
2108 ParseToken(lltok::comma, "expected comma in block address expression")||
2109 ParseValID(Label) ||
2110 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2111 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002112
Chris Lattner09d9ef42009-10-28 03:39:23 +00002113 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2114 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002115 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002116 return Error(Label.Loc, "expected basic block name in blockaddress");
2117
2118 // Make a global variable as a placeholder for this reference.
2119 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2120 false, GlobalValue::InternalLinkage,
2121 0, "");
2122 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2123 ID.ConstantVal = FwdRef;
2124 ID.Kind = ValID::t_Constant;
2125 return false;
2126 }
2127
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 case lltok::kw_trunc:
2129 case lltok::kw_zext:
2130 case lltok::kw_sext:
2131 case lltok::kw_fptrunc:
2132 case lltok::kw_fpext:
2133 case lltok::kw_bitcast:
2134 case lltok::kw_uitofp:
2135 case lltok::kw_sitofp:
2136 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002140 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002141 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 Constant *SrcVal;
2143 Lex.Lex();
2144 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2145 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002146 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 ParseType(DestTy) ||
2148 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2149 return true;
2150 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2151 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2152 SrcVal->getType()->getDescription() + "' to '" +
2153 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002154 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002155 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ID.Kind = ValID::t_Constant;
2157 return false;
2158 }
2159 case lltok::kw_extractvalue: {
2160 Lex.Lex();
2161 Constant *Val;
2162 SmallVector<unsigned, 4> Indices;
2163 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2164 ParseGlobalTypeAndValue(Val) ||
2165 ParseIndexList(Indices) ||
2166 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2167 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002168 if (Lex.getKind() == lltok::NamedOrCustomMD)
2169 if (ParseOptionalCustomMetadata()) return true;
2170
Chris Lattnerdf986172009-01-02 07:01:27 +00002171 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2172 return Error(ID.Loc, "extractvalue operand must be array or struct");
2173 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2174 Indices.end()))
2175 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002176 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002177 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 ID.Kind = ValID::t_Constant;
2179 return false;
2180 }
2181 case lltok::kw_insertvalue: {
2182 Lex.Lex();
2183 Constant *Val0, *Val1;
2184 SmallVector<unsigned, 4> Indices;
2185 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2186 ParseGlobalTypeAndValue(Val0) ||
2187 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2188 ParseGlobalTypeAndValue(Val1) ||
2189 ParseIndexList(Indices) ||
2190 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2191 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002192 if (Lex.getKind() == lltok::NamedOrCustomMD)
2193 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2195 return Error(ID.Loc, "extractvalue operand must be array or struct");
2196 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2197 Indices.end()))
2198 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002199 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002200 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 ID.Kind = ValID::t_Constant;
2202 return false;
2203 }
2204 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002205 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 unsigned PredVal, Opc = Lex.getUIntVal();
2207 Constant *Val0, *Val1;
2208 Lex.Lex();
2209 if (ParseCmpPredicate(PredVal, Opc) ||
2210 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2211 ParseGlobalTypeAndValue(Val0) ||
2212 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2213 ParseGlobalTypeAndValue(Val1) ||
2214 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2215 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002216
Chris Lattnerdf986172009-01-02 07:01:27 +00002217 if (Val0->getType() != Val1->getType())
2218 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002219
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 if (Opc == Instruction::FCmp) {
2223 if (!Val0->getType()->isFPOrFPVector())
2224 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002225 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002226 } else {
2227 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002228 if (!Val0->getType()->isIntOrIntVector() &&
2229 !isa<PointerType>(Val0->getType()))
2230 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002231 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002232 }
2233 ID.Kind = ValID::t_Constant;
2234 return false;
2235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 // Binary Operators.
2238 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002239 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002240 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002241 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002242 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002243 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 case lltok::kw_udiv:
2245 case lltok::kw_sdiv:
2246 case lltok::kw_fdiv:
2247 case lltok::kw_urem:
2248 case lltok::kw_srem:
2249 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002250 bool NUW = false;
2251 bool NSW = false;
2252 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002253 unsigned Opc = Lex.getUIntVal();
2254 Constant *Val0, *Val1;
2255 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002256 LocTy ModifierLoc = Lex.getLoc();
2257 if (Opc == Instruction::Add ||
2258 Opc == Instruction::Sub ||
2259 Opc == Instruction::Mul) {
2260 if (EatIfPresent(lltok::kw_nuw))
2261 NUW = true;
2262 if (EatIfPresent(lltok::kw_nsw)) {
2263 NSW = true;
2264 if (EatIfPresent(lltok::kw_nuw))
2265 NUW = true;
2266 }
2267 } else if (Opc == Instruction::SDiv) {
2268 if (EatIfPresent(lltok::kw_exact))
2269 Exact = true;
2270 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002271 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2272 ParseGlobalTypeAndValue(Val0) ||
2273 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2274 ParseGlobalTypeAndValue(Val1) ||
2275 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2276 return true;
2277 if (Val0->getType() != Val1->getType())
2278 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002279 if (!Val0->getType()->isIntOrIntVector()) {
2280 if (NUW)
2281 return Error(ModifierLoc, "nuw only applies to integer operations");
2282 if (NSW)
2283 return Error(ModifierLoc, "nsw only applies to integer operations");
2284 }
2285 // API compatibility: Accept either integer or floating-point types with
2286 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (!Val0->getType()->isIntOrIntVector() &&
2288 !Val0->getType()->isFPOrFPVector())
2289 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002290 unsigned Flags = 0;
2291 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2292 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2293 if (Exact) Flags |= SDivOperator::IsExact;
2294 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002295 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 ID.Kind = ValID::t_Constant;
2297 return false;
2298 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002299
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 // Logical Operations
2301 case lltok::kw_shl:
2302 case lltok::kw_lshr:
2303 case lltok::kw_ashr:
2304 case lltok::kw_and:
2305 case lltok::kw_or:
2306 case lltok::kw_xor: {
2307 unsigned Opc = Lex.getUIntVal();
2308 Constant *Val0, *Val1;
2309 Lex.Lex();
2310 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2311 ParseGlobalTypeAndValue(Val0) ||
2312 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2313 ParseGlobalTypeAndValue(Val1) ||
2314 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2315 return true;
2316 if (Val0->getType() != Val1->getType())
2317 return Error(ID.Loc, "operands of constexpr must have same type");
2318 if (!Val0->getType()->isIntOrIntVector())
2319 return Error(ID.Loc,
2320 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002321 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002322 ID.Kind = ValID::t_Constant;
2323 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002324 }
2325
Chris Lattnerdf986172009-01-02 07:01:27 +00002326 case lltok::kw_getelementptr:
2327 case lltok::kw_shufflevector:
2328 case lltok::kw_insertelement:
2329 case lltok::kw_extractelement:
2330 case lltok::kw_select: {
2331 unsigned Opc = Lex.getUIntVal();
2332 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002333 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002334 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002335 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002336 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2338 ParseGlobalValueVector(Elts) ||
2339 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2340 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 if (Opc == Instruction::GetElementPtr) {
2343 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2344 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345
Chris Lattnerdf986172009-01-02 07:01:27 +00002346 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002347 (Value**)(Elts.data() + 1),
2348 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002350 ID.ConstantVal = InBounds ?
2351 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2352 Elts.data() + 1,
2353 Elts.size() - 1) :
2354 ConstantExpr::getGetElementPtr(Elts[0],
2355 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002356 } else if (Opc == Instruction::Select) {
2357 if (Elts.size() != 3)
2358 return Error(ID.Loc, "expected three operands to select");
2359 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2360 Elts[2]))
2361 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002362 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002363 } else if (Opc == Instruction::ShuffleVector) {
2364 if (Elts.size() != 3)
2365 return Error(ID.Loc, "expected three operands to shufflevector");
2366 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2367 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002368 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002369 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 } else if (Opc == Instruction::ExtractElement) {
2371 if (Elts.size() != 2)
2372 return Error(ID.Loc, "expected two operands to extractelement");
2373 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2374 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002375 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002376 } else {
2377 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2378 if (Elts.size() != 3)
2379 return Error(ID.Loc, "expected three operands to insertelement");
2380 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2381 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002382 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002383 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002384 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002385
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 ID.Kind = ValID::t_Constant;
2387 return false;
2388 }
2389 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002390
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 Lex.Lex();
2392 return false;
2393}
2394
2395/// ParseGlobalValue - Parse a global value with the specified type.
2396bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2397 V = 0;
2398 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002399 return ParseValID(ID) ||
2400 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002401}
2402
2403/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2404/// constant.
2405bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2406 Constant *&V) {
2407 if (isa<FunctionType>(Ty))
2408 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002409
Chris Lattnerdf986172009-01-02 07:01:27 +00002410 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002411 default: llvm_unreachable("Unknown ValID!");
Devang Patele54abc92009-07-22 17:43:22 +00002412 case ValID::t_Metadata:
2413 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002414 case ValID::t_LocalID:
2415 case ValID::t_LocalName:
2416 return Error(ID.Loc, "invalid use of function-local name");
2417 case ValID::t_InlineAsm:
2418 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2419 case ValID::t_GlobalName:
2420 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2421 return V == 0;
2422 case ValID::t_GlobalID:
2423 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2424 return V == 0;
2425 case ValID::t_APSInt:
2426 if (!isa<IntegerType>(Ty))
2427 return Error(ID.Loc, "integer constant must have integer type");
2428 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002429 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 return false;
2431 case ValID::t_APFloat:
2432 if (!Ty->isFloatingPoint() ||
2433 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2434 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002435
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 // The lexer has no type info, so builds all float and double FP constants
2437 // as double. Fix this here. Long double does not need this.
2438 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002439 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002440 bool Ignored;
2441 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2442 &Ignored);
2443 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002444 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattner959873d2009-01-05 18:24:23 +00002446 if (V->getType() != Ty)
2447 return Error(ID.Loc, "floating point constant does not have type '" +
2448 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 return false;
2451 case ValID::t_Null:
2452 if (!isa<PointerType>(Ty))
2453 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002454 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002455 return false;
2456 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002457 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002458 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002459 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002460 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002461 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002462 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002463 case ValID::t_EmptyArray:
2464 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2465 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002466 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002467 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002469 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002470 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002471 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002472 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002473 return false;
2474 case ValID::t_Constant:
2475 if (ID.ConstantVal->getType() != Ty)
2476 return Error(ID.Loc, "constant expression type mismatch");
2477 V = ID.ConstantVal;
2478 return false;
2479 }
2480}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002481
Chris Lattnerdf986172009-01-02 07:01:27 +00002482bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002483 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002484 return ParseType(Type) ||
2485 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486}
Chris Lattnerdf986172009-01-02 07:01:27 +00002487
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002488/// ParseGlobalValueVector
2489/// ::= /*empty*/
2490/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002491bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2492 // Empty list.
2493 if (Lex.getKind() == lltok::rbrace ||
2494 Lex.getKind() == lltok::rsquare ||
2495 Lex.getKind() == lltok::greater ||
2496 Lex.getKind() == lltok::rparen)
2497 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002498
Chris Lattnerdf986172009-01-02 07:01:27 +00002499 Constant *C;
2500 if (ParseGlobalTypeAndValue(C)) return true;
2501 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002502
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002503 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 if (ParseGlobalTypeAndValue(C)) return true;
2505 Elts.push_back(C);
2506 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002507
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 return false;
2509}
2510
2511
2512//===----------------------------------------------------------------------===//
2513// Function Parsing.
2514//===----------------------------------------------------------------------===//
2515
2516bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2517 PerFunctionState &PFS) {
2518 if (ID.Kind == ValID::t_LocalID)
2519 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2520 else if (ID.Kind == ValID::t_LocalName)
2521 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
Steve Naroffb0adcdb2009-01-05 18:48:47 +00002522 else if (ID.Kind == ValID::t_InlineAsm) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002523 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2524 const FunctionType *FTy =
2525 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2526 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2527 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002528 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002529 return false;
Devang Patele54abc92009-07-22 17:43:22 +00002530 } else if (ID.Kind == ValID::t_Metadata) {
2531 V = ID.MetadataVal;
Chris Lattnerdf986172009-01-02 07:01:27 +00002532 } else {
2533 Constant *C;
2534 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2535 V = C;
2536 return false;
2537 }
2538
2539 return V == 0;
2540}
2541
2542bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2543 V = 0;
2544 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002545 return ParseValID(ID) ||
2546 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002547}
2548
2549bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002550 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002551 return ParseType(T) ||
2552 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002553}
2554
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002555bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2556 PerFunctionState &PFS) {
2557 Value *V;
2558 Loc = Lex.getLoc();
2559 if (ParseTypeAndValue(V, PFS)) return true;
2560 if (!isa<BasicBlock>(V))
2561 return Error(Loc, "expected a basic block");
2562 BB = cast<BasicBlock>(V);
2563 return false;
2564}
2565
2566
Chris Lattnerdf986172009-01-02 07:01:27 +00002567/// FunctionHeader
2568/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2569/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2570/// OptionalAlign OptGC
2571bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2572 // Parse the linkage.
2573 LocTy LinkageLoc = Lex.getLoc();
2574 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002575
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002576 unsigned Visibility, RetAttrs;
2577 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002578 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002579 LocTy RetTypeLoc = Lex.getLoc();
2580 if (ParseOptionalLinkage(Linkage) ||
2581 ParseOptionalVisibility(Visibility) ||
2582 ParseOptionalCallingConv(CC) ||
2583 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002584 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return true;
2586
2587 // Verify that the linkage is ok.
2588 switch ((GlobalValue::LinkageTypes)Linkage) {
2589 case GlobalValue::ExternalLinkage:
2590 break; // always ok.
2591 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002592 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 if (isDefine)
2594 return Error(LinkageLoc, "invalid linkage for function definition");
2595 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002596 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002597 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002599 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002600 case GlobalValue::LinkOnceAnyLinkage:
2601 case GlobalValue::LinkOnceODRLinkage:
2602 case GlobalValue::WeakAnyLinkage:
2603 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002604 case GlobalValue::DLLExportLinkage:
2605 if (!isDefine)
2606 return Error(LinkageLoc, "invalid linkage for function declaration");
2607 break;
2608 case GlobalValue::AppendingLinkage:
2609 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002610 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 return Error(LinkageLoc, "invalid function linkage type");
2612 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002613
Chris Lattner99bb3152009-01-05 08:00:30 +00002614 if (!FunctionType::isValidReturnType(RetType) ||
2615 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002616 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002617
Chris Lattnerdf986172009-01-02 07:01:27 +00002618 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002619
2620 std::string FunctionName;
2621 if (Lex.getKind() == lltok::GlobalVar) {
2622 FunctionName = Lex.getStrVal();
2623 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2624 unsigned NameID = Lex.getUIntVal();
2625
2626 if (NameID != NumberedVals.size())
2627 return TokError("function expected to be numbered '%" +
2628 utostr(NumberedVals.size()) + "'");
2629 } else {
2630 return TokError("expected function name");
2631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002633 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002634
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002635 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002636 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Chris Lattnerdf986172009-01-02 07:01:27 +00002638 std::vector<ArgInfo> ArgList;
2639 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002640 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002641 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002642 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002643 std::string GC;
2644
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002645 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002646 ParseOptionalAttrs(FuncAttrs, 2) ||
2647 (EatIfPresent(lltok::kw_section) &&
2648 ParseStringConstant(Section)) ||
2649 ParseOptionalAlignment(Alignment) ||
2650 (EatIfPresent(lltok::kw_gc) &&
2651 ParseStringConstant(GC)))
2652 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002653
2654 // If the alignment was parsed as an attribute, move to the alignment field.
2655 if (FuncAttrs & Attribute::Alignment) {
2656 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2657 FuncAttrs &= ~Attribute::Alignment;
2658 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002659
Chris Lattnerdf986172009-01-02 07:01:27 +00002660 // Okay, if we got here, the function is syntactically valid. Convert types
2661 // and do semantic checks.
2662 std::vector<const Type*> ParamTypeList;
2663 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002664 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002665 // attributes.
2666 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2667 if (FuncAttrs & ObsoleteFuncAttrs) {
2668 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2669 FuncAttrs &= ~ObsoleteFuncAttrs;
2670 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002671
Chris Lattnerdf986172009-01-02 07:01:27 +00002672 if (RetAttrs != Attribute::None)
2673 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002674
Chris Lattnerdf986172009-01-02 07:01:27 +00002675 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2676 ParamTypeList.push_back(ArgList[i].Type);
2677 if (ArgList[i].Attrs != Attribute::None)
2678 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2679 }
2680
2681 if (FuncAttrs != Attribute::None)
2682 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2683
2684 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002685
Chris Lattnera9a9e072009-03-09 04:49:14 +00002686 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002687 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2689
Owen Andersonfba933c2009-07-01 23:57:11 +00002690 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002691 FunctionType::get(RetType, ParamTypeList, isVarArg);
2692 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002693
2694 Fn = 0;
2695 if (!FunctionName.empty()) {
2696 // If this was a definition of a forward reference, remove the definition
2697 // from the forward reference table and fill in the forward ref.
2698 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2699 ForwardRefVals.find(FunctionName);
2700 if (FRVI != ForwardRefVals.end()) {
2701 Fn = M->getFunction(FunctionName);
2702 ForwardRefVals.erase(FRVI);
2703 } else if ((Fn = M->getFunction(FunctionName))) {
2704 // If this function already exists in the symbol table, then it is
2705 // multiply defined. We accept a few cases for old backwards compat.
2706 // FIXME: Remove this stuff for LLVM 3.0.
2707 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2708 (!Fn->isDeclaration() && isDefine)) {
2709 // If the redefinition has different type or different attributes,
2710 // reject it. If both have bodies, reject it.
2711 return Error(NameLoc, "invalid redefinition of function '" +
2712 FunctionName + "'");
2713 } else if (Fn->isDeclaration()) {
2714 // Make sure to strip off any argument names so we can't get conflicts.
2715 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2716 AI != AE; ++AI)
2717 AI->setName("");
2718 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002719 } else if (M->getNamedValue(FunctionName)) {
2720 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002722
Dan Gohman41905542009-08-29 23:37:49 +00002723 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 // If this is a definition of a forward referenced function, make sure the
2725 // types agree.
2726 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2727 = ForwardRefValIDs.find(NumberedVals.size());
2728 if (I != ForwardRefValIDs.end()) {
2729 Fn = cast<Function>(I->second.first);
2730 if (Fn->getType() != PFT)
2731 return Error(NameLoc, "type of definition and forward reference of '@" +
2732 utostr(NumberedVals.size()) +"' disagree");
2733 ForwardRefValIDs.erase(I);
2734 }
2735 }
2736
2737 if (Fn == 0)
2738 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2739 else // Move the forward-reference to the correct spot in the module.
2740 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2741
2742 if (FunctionName.empty())
2743 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002744
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2746 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2747 Fn->setCallingConv(CC);
2748 Fn->setAttributes(PAL);
2749 Fn->setAlignment(Alignment);
2750 Fn->setSection(Section);
2751 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002752
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 // Add all of the arguments we parsed to the function.
2754 Function::arg_iterator ArgIt = Fn->arg_begin();
2755 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002756 // If we run out of arguments in the Function prototype, exit early.
2757 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2758 if (ArgIt == Fn->arg_end()) break;
2759
Chris Lattnerdf986172009-01-02 07:01:27 +00002760 // If the argument has a name, insert it into the argument symbol table.
2761 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002762
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 // Set the name, if it conflicted, it will be auto-renamed.
2764 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Chris Lattnerdf986172009-01-02 07:01:27 +00002766 if (ArgIt->getNameStr() != ArgList[i].Name)
2767 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2768 ArgList[i].Name + "'");
2769 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002770
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 return false;
2772}
2773
2774
2775/// ParseFunctionBody
2776/// ::= '{' BasicBlock+ '}'
2777/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2778///
2779bool LLParser::ParseFunctionBody(Function &Fn) {
2780 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2781 return TokError("expected '{' in function body");
2782 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002783
Chris Lattner09d9ef42009-10-28 03:39:23 +00002784 int FunctionNumber = -1;
2785 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2786
2787 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2790 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 // Eat the }.
2793 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Chris Lattnerdf986172009-01-02 07:01:27 +00002795 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002796 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002797}
2798
2799/// ParseBasicBlock
2800/// ::= LabelStr? Instruction*
2801bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2802 // If this basic block starts out with a name, remember it.
2803 std::string Name;
2804 LocTy NameLoc = Lex.getLoc();
2805 if (Lex.getKind() == lltok::LabelStr) {
2806 Name = Lex.getStrVal();
2807 Lex.Lex();
2808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2811 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002812
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002814
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 // Parse the instructions in this block until we get a terminator.
2816 Instruction *Inst;
2817 do {
2818 // This instruction may have three possibilities for a name: a) none
2819 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2820 LocTy NameLoc = Lex.getLoc();
2821 int NameID = -1;
2822 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 if (Lex.getKind() == lltok::LocalVarID) {
2825 NameID = Lex.getUIntVal();
2826 Lex.Lex();
2827 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2828 return true;
2829 } else if (Lex.getKind() == lltok::LocalVar ||
2830 // FIXME: REMOVE IN LLVM 3.0
2831 Lex.getKind() == lltok::StringConstant) {
2832 NameStr = Lex.getStrVal();
2833 Lex.Lex();
2834 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2835 return true;
2836 }
Devang Patelf633a062009-09-17 23:04:48 +00002837
Chris Lattnerdf986172009-01-02 07:01:27 +00002838 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002839 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002840 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002841
2842 // Set metadata attached with this instruction.
Devang Patela2148402009-09-28 21:14:55 +00002843 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002844 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Chris Lattner3990b122009-12-28 23:41:32 +00002845 Inst->setMetadata(MDI->first, MDI->second);
Devang Patelf633a062009-09-17 23:04:48 +00002846 MDsOnInst.clear();
2847
Chris Lattnerdf986172009-01-02 07:01:27 +00002848 BB->getInstList().push_back(Inst);
2849
2850 // Set the name on the instruction.
2851 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2852 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002853
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 return false;
2855}
2856
2857//===----------------------------------------------------------------------===//
2858// Instruction Parsing.
2859//===----------------------------------------------------------------------===//
2860
2861/// ParseInstruction - Parse one of the many different instructions.
2862///
2863bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2864 PerFunctionState &PFS) {
2865 lltok::Kind Token = Lex.getKind();
2866 if (Token == lltok::Eof)
2867 return TokError("found end of file when expecting more instructions");
2868 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002869 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002870 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002871
Chris Lattnerdf986172009-01-02 07:01:27 +00002872 switch (Token) {
2873 default: return Error(Loc, "expected instruction opcode");
2874 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002875 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2876 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002877 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2878 case lltok::kw_br: return ParseBr(Inst, PFS);
2879 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002880 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002881 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2882 // Binary Operators.
2883 case lltok::kw_add:
2884 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002885 case lltok::kw_mul: {
2886 bool NUW = false;
2887 bool NSW = false;
2888 LocTy ModifierLoc = Lex.getLoc();
2889 if (EatIfPresent(lltok::kw_nuw))
2890 NUW = true;
2891 if (EatIfPresent(lltok::kw_nsw)) {
2892 NSW = true;
2893 if (EatIfPresent(lltok::kw_nuw))
2894 NUW = true;
2895 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002896 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002897 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2898 if (!Result) {
2899 if (!Inst->getType()->isIntOrIntVector()) {
2900 if (NUW)
2901 return Error(ModifierLoc, "nuw only applies to integer operations");
2902 if (NSW)
2903 return Error(ModifierLoc, "nsw only applies to integer operations");
2904 }
2905 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002906 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002907 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002908 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002909 }
2910 return Result;
2911 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002912 case lltok::kw_fadd:
2913 case lltok::kw_fsub:
2914 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2915
Dan Gohman59858cf2009-07-27 16:11:46 +00002916 case lltok::kw_sdiv: {
2917 bool Exact = false;
2918 if (EatIfPresent(lltok::kw_exact))
2919 Exact = true;
2920 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2921 if (!Result)
2922 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002923 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002924 return Result;
2925 }
2926
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002929 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002930 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002931 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002932 case lltok::kw_shl:
2933 case lltok::kw_lshr:
2934 case lltok::kw_ashr:
2935 case lltok::kw_and:
2936 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002937 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002938 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002939 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 // Casts.
2941 case lltok::kw_trunc:
2942 case lltok::kw_zext:
2943 case lltok::kw_sext:
2944 case lltok::kw_fptrunc:
2945 case lltok::kw_fpext:
2946 case lltok::kw_bitcast:
2947 case lltok::kw_uitofp:
2948 case lltok::kw_sitofp:
2949 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002950 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002951 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002952 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 // Other.
2954 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002955 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002956 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2957 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2958 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2959 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2960 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2961 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2962 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002963 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2964 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002965 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002966 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2967 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2968 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002969 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002970 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002971 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002973 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002975 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2976 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2977 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2978 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2979 }
2980}
2981
2982/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2983bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002984 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 switch (Lex.getKind()) {
2986 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2987 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2988 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2989 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2990 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2991 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2992 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2993 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2994 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2995 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2996 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2997 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2998 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2999 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3000 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3001 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3002 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3003 }
3004 } else {
3005 switch (Lex.getKind()) {
3006 default: TokError("expected icmp predicate (e.g. 'eq')");
3007 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3008 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3009 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3010 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3011 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3012 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3013 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3014 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3015 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3016 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3017 }
3018 }
3019 Lex.Lex();
3020 return false;
3021}
3022
3023//===----------------------------------------------------------------------===//
3024// Terminator Instructions.
3025//===----------------------------------------------------------------------===//
3026
3027/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003028/// ::= 'ret' void (',' !dbg, !1)*
3029/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3030/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003031/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00003032bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3033 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003034 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003035 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003036
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003037 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003038 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003039 return false;
3040 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003041
Chris Lattnerdf986172009-01-02 07:01:27 +00003042 Value *RV;
3043 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003044
Devang Patelf633a062009-09-17 23:04:48 +00003045 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003046 // Parse optional custom metadata, e.g. !dbg
3047 if (Lex.getKind() == lltok::NamedOrCustomMD) {
3048 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00003049 } else {
3050 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003051 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3052 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003053 SmallVector<Value*, 8> RVs;
3054 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003055
Devang Patelf633a062009-09-17 23:04:48 +00003056 do {
Devang Patel0475c912009-09-29 00:01:14 +00003057 // If optional custom metadata, e.g. !dbg is seen then this is the
3058 // end of MRV.
3059 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003060 break;
3061 if (ParseTypeAndValue(RV, PFS)) return true;
3062 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003063 } while (EatIfPresent(lltok::comma));
3064
3065 RV = UndefValue::get(PFS.getFunction().getReturnType());
3066 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003067 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3068 BB->getInstList().push_back(I);
3069 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003070 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 }
3072 }
Devang Patelf633a062009-09-17 23:04:48 +00003073
Owen Anderson1d0be152009-08-13 21:58:54 +00003074 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 return false;
3076}
3077
3078
3079/// ParseBr
3080/// ::= 'br' TypeAndValue
3081/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3082bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3083 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003084 Value *Op0;
3085 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003087
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3089 Inst = BranchInst::Create(BB);
3090 return false;
3091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003092
Owen Anderson1d0be152009-08-13 21:58:54 +00003093 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003097 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003098 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003099 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003101
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003102 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003103 return false;
3104}
3105
3106/// ParseSwitch
3107/// Instruction
3108/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3109/// JumpTable
3110/// ::= (TypeAndValue ',' TypeAndValue)*
3111bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3112 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003113 Value *Cond;
3114 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3116 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003117 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003118 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3119 return true;
3120
3121 if (!isa<IntegerType>(Cond->getType()))
3122 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003123
Chris Lattnerdf986172009-01-02 07:01:27 +00003124 // Parse the jump table pairs.
3125 SmallPtrSet<Value*, 32> SeenCases;
3126 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3127 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003128 Value *Constant;
3129 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003130
Chris Lattnerdf986172009-01-02 07:01:27 +00003131 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3132 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003133 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003134 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003135
Chris Lattnerdf986172009-01-02 07:01:27 +00003136 if (!SeenCases.insert(Constant))
3137 return Error(CondLoc, "duplicate case value in switch");
3138 if (!isa<ConstantInt>(Constant))
3139 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003140
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003141 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003143
Chris Lattnerdf986172009-01-02 07:01:27 +00003144 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003145
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003146 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3148 SI->addCase(Table[i].first, Table[i].second);
3149 Inst = SI;
3150 return false;
3151}
3152
Chris Lattnerab21db72009-10-28 00:19:10 +00003153/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003154/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003155/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3156bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003157 LocTy AddrLoc;
3158 Value *Address;
3159 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003160 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3161 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003162 return true;
3163
3164 if (!isa<PointerType>(Address->getType()))
Chris Lattnerab21db72009-10-28 00:19:10 +00003165 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166
3167 // Parse the destination list.
3168 SmallVector<BasicBlock*, 16> DestList;
3169
3170 if (Lex.getKind() != lltok::rsquare) {
3171 BasicBlock *DestBB;
3172 if (ParseTypeAndBasicBlock(DestBB, PFS))
3173 return true;
3174 DestList.push_back(DestBB);
3175
3176 while (EatIfPresent(lltok::comma)) {
3177 if (ParseTypeAndBasicBlock(DestBB, PFS))
3178 return true;
3179 DestList.push_back(DestBB);
3180 }
3181 }
3182
3183 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3184 return true;
3185
Chris Lattnerab21db72009-10-28 00:19:10 +00003186 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003187 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3188 IBI->addDestination(DestList[i]);
3189 Inst = IBI;
3190 return false;
3191}
3192
3193
Chris Lattnerdf986172009-01-02 07:01:27 +00003194/// ParseInvoke
3195/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3196/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3197bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3198 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003199 unsigned RetAttrs, FnAttrs;
3200 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003201 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 LocTy RetTypeLoc;
3203 ValID CalleeID;
3204 SmallVector<ParamInfo, 16> ArgList;
3205
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003206 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 if (ParseOptionalCallingConv(CC) ||
3208 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003209 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 ParseValID(CalleeID) ||
3211 ParseParameterList(ArgList, PFS) ||
3212 ParseOptionalAttrs(FnAttrs, 2) ||
3213 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003214 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003216 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003217 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003218
Chris Lattnerdf986172009-01-02 07:01:27 +00003219 // If RetType is a non-function pointer type, then this is the short syntax
3220 // for the call, which means that RetType is just the return type. Infer the
3221 // rest of the function argument types from the arguments that are present.
3222 const PointerType *PFTy = 0;
3223 const FunctionType *Ty = 0;
3224 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3225 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3226 // Pull out the types of all of the arguments...
3227 std::vector<const Type*> ParamTypes;
3228 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3229 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003230
Chris Lattnerdf986172009-01-02 07:01:27 +00003231 if (!FunctionType::isValidReturnType(RetType))
3232 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Owen Andersondebcb012009-07-29 22:17:13 +00003234 Ty = FunctionType::get(RetType, ParamTypes, false);
3235 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerdf986172009-01-02 07:01:27 +00003238 // Look up the callee.
3239 Value *Callee;
3240 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3243 // function attributes.
3244 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3245 if (FnAttrs & ObsoleteFuncAttrs) {
3246 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3247 FnAttrs &= ~ObsoleteFuncAttrs;
3248 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 // Set up the Attributes for the function.
3251 SmallVector<AttributeWithIndex, 8> Attrs;
3252 if (RetAttrs != Attribute::None)
3253 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003254
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 // Loop through FunctionType's arguments and ensure they are specified
3258 // correctly. Also, gather any parameter attributes.
3259 FunctionType::param_iterator I = Ty->param_begin();
3260 FunctionType::param_iterator E = Ty->param_end();
3261 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3262 const Type *ExpectedTy = 0;
3263 if (I != E) {
3264 ExpectedTy = *I++;
3265 } else if (!Ty->isVarArg()) {
3266 return Error(ArgList[i].Loc, "too many arguments specified");
3267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003268
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3270 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3271 ExpectedTy->getDescription() + "'");
3272 Args.push_back(ArgList[i].V);
3273 if (ArgList[i].Attrs != Attribute::None)
3274 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3275 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003276
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 if (I != E)
3278 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003279
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 if (FnAttrs != Attribute::None)
3281 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003282
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 // Finish off the Attributes and check them
3284 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003285
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003286 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003287 Args.begin(), Args.end());
3288 II->setCallingConv(CC);
3289 II->setAttributes(PAL);
3290 Inst = II;
3291 return false;
3292}
3293
3294
3295
3296//===----------------------------------------------------------------------===//
3297// Binary Operators.
3298//===----------------------------------------------------------------------===//
3299
3300/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003301/// ::= ArithmeticOps TypeAndValue ',' Value
3302///
3303/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3304/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003305bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003306 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003307 LocTy Loc; Value *LHS, *RHS;
3308 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3309 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3310 ParseValue(LHS->getType(), RHS, PFS))
3311 return true;
3312
Chris Lattnere914b592009-01-05 08:24:46 +00003313 bool Valid;
3314 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003315 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003316 case 0: // int or FP.
3317 Valid = LHS->getType()->isIntOrIntVector() ||
3318 LHS->getType()->isFPOrFPVector();
3319 break;
3320 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3321 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3322 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003323
Chris Lattnere914b592009-01-05 08:24:46 +00003324 if (!Valid)
3325 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003326
Chris Lattnerdf986172009-01-02 07:01:27 +00003327 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3328 return false;
3329}
3330
3331/// ParseLogical
3332/// ::= ArithmeticOps TypeAndValue ',' Value {
3333bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3334 unsigned Opc) {
3335 LocTy Loc; Value *LHS, *RHS;
3336 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3337 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3338 ParseValue(LHS->getType(), RHS, PFS))
3339 return true;
3340
3341 if (!LHS->getType()->isIntOrIntVector())
3342 return Error(Loc,"instruction requires integer or integer vector operands");
3343
3344 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3345 return false;
3346}
3347
3348
3349/// ParseCompare
3350/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3351/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003352bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3353 unsigned Opc) {
3354 // Parse the integer/fp comparison predicate.
3355 LocTy Loc;
3356 unsigned Pred;
3357 Value *LHS, *RHS;
3358 if (ParseCmpPredicate(Pred, Opc) ||
3359 ParseTypeAndValue(LHS, Loc, PFS) ||
3360 ParseToken(lltok::comma, "expected ',' after compare value") ||
3361 ParseValue(LHS->getType(), RHS, PFS))
3362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003363
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 if (Opc == Instruction::FCmp) {
3365 if (!LHS->getType()->isFPOrFPVector())
3366 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003367 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003368 } else {
3369 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 if (!LHS->getType()->isIntOrIntVector() &&
3371 !isa<PointerType>(LHS->getType()))
3372 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003373 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003374 }
3375 return false;
3376}
3377
3378//===----------------------------------------------------------------------===//
3379// Other Instructions.
3380//===----------------------------------------------------------------------===//
3381
3382
3383/// ParseCast
3384/// ::= CastOpc TypeAndValue 'to' Type
3385bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3386 unsigned Opc) {
3387 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003388 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 if (ParseTypeAndValue(Op, Loc, PFS) ||
3390 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3391 ParseType(DestTy))
3392 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003393
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003394 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3395 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003396 return Error(Loc, "invalid cast opcode for cast from '" +
3397 Op->getType()->getDescription() + "' to '" +
3398 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003399 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003400 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3401 return false;
3402}
3403
3404/// ParseSelect
3405/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3406bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3407 LocTy Loc;
3408 Value *Op0, *Op1, *Op2;
3409 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3410 ParseToken(lltok::comma, "expected ',' after select condition") ||
3411 ParseTypeAndValue(Op1, PFS) ||
3412 ParseToken(lltok::comma, "expected ',' after select value") ||
3413 ParseTypeAndValue(Op2, PFS))
3414 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003415
Chris Lattnerdf986172009-01-02 07:01:27 +00003416 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3417 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003418
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 Inst = SelectInst::Create(Op0, Op1, Op2);
3420 return false;
3421}
3422
Chris Lattner0088a5c2009-01-05 08:18:44 +00003423/// ParseVA_Arg
3424/// ::= 'va_arg' TypeAndValue ',' Type
3425bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003426 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003427 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003428 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003429 if (ParseTypeAndValue(Op, PFS) ||
3430 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003431 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003432 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003433
Chris Lattner0088a5c2009-01-05 08:18:44 +00003434 if (!EltTy->isFirstClassType())
3435 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003436
3437 Inst = new VAArgInst(Op, EltTy);
3438 return false;
3439}
3440
3441/// ParseExtractElement
3442/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3443bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3444 LocTy Loc;
3445 Value *Op0, *Op1;
3446 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3447 ParseToken(lltok::comma, "expected ',' after extract value") ||
3448 ParseTypeAndValue(Op1, PFS))
3449 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003450
Chris Lattnerdf986172009-01-02 07:01:27 +00003451 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3452 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003453
Eric Christophera3500da2009-07-25 02:28:41 +00003454 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 return false;
3456}
3457
3458/// ParseInsertElement
3459/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3460bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3461 LocTy Loc;
3462 Value *Op0, *Op1, *Op2;
3463 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3464 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3465 ParseTypeAndValue(Op1, PFS) ||
3466 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3467 ParseTypeAndValue(Op2, PFS))
3468 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003469
Chris Lattnerdf986172009-01-02 07:01:27 +00003470 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003471 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003472
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3474 return false;
3475}
3476
3477/// ParseShuffleVector
3478/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3479bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3480 LocTy Loc;
3481 Value *Op0, *Op1, *Op2;
3482 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3484 ParseTypeAndValue(Op1, PFS) ||
3485 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3486 ParseTypeAndValue(Op2, PFS))
3487 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003488
Chris Lattnerdf986172009-01-02 07:01:27 +00003489 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3490 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003491
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3493 return false;
3494}
3495
3496/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003497/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003498bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003499 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 Value *Op0, *Op1;
3501 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003502
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 if (ParseType(Ty) ||
3504 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3505 ParseValue(Ty, Op0, PFS) ||
3506 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003507 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3509 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003510
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3512 while (1) {
3513 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003514
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003515 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003516 break;
3517
Devang Patela43d46f2009-10-16 18:45:49 +00003518 if (Lex.getKind() == lltok::NamedOrCustomMD)
3519 break;
3520
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003521 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 ParseValue(Ty, Op0, PFS) ||
3523 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003524 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003525 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3526 return true;
3527 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003528
Devang Patela43d46f2009-10-16 18:45:49 +00003529 if (Lex.getKind() == lltok::NamedOrCustomMD)
3530 if (ParseOptionalCustomMetadata()) return true;
3531
Chris Lattnerdf986172009-01-02 07:01:27 +00003532 if (!Ty->isFirstClassType())
3533 return Error(TypeLoc, "phi node must have first class type");
3534
3535 PHINode *PN = PHINode::Create(Ty);
3536 PN->reserveOperandSpace(PHIVals.size());
3537 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3538 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3539 Inst = PN;
3540 return false;
3541}
3542
3543/// ParseCall
3544/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3545/// ParameterList OptionalAttrs
3546bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3547 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003548 unsigned RetAttrs, FnAttrs;
3549 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003550 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003551 LocTy RetTypeLoc;
3552 ValID CalleeID;
3553 SmallVector<ParamInfo, 16> ArgList;
3554 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3557 ParseOptionalCallingConv(CC) ||
3558 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003559 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003560 ParseValID(CalleeID) ||
3561 ParseParameterList(ArgList, PFS) ||
3562 ParseOptionalAttrs(FnAttrs, 2))
3563 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003564
Chris Lattnerdf986172009-01-02 07:01:27 +00003565 // If RetType is a non-function pointer type, then this is the short syntax
3566 // for the call, which means that RetType is just the return type. Infer the
3567 // rest of the function argument types from the arguments that are present.
3568 const PointerType *PFTy = 0;
3569 const FunctionType *Ty = 0;
3570 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3571 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3572 // Pull out the types of all of the arguments...
3573 std::vector<const Type*> ParamTypes;
3574 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3575 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003576
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 if (!FunctionType::isValidReturnType(RetType))
3578 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Owen Andersondebcb012009-07-29 22:17:13 +00003580 Ty = FunctionType::get(RetType, ParamTypes, false);
3581 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003583
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 // Look up the callee.
3585 Value *Callee;
3586 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003587
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3589 // function attributes.
3590 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3591 if (FnAttrs & ObsoleteFuncAttrs) {
3592 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3593 FnAttrs &= ~ObsoleteFuncAttrs;
3594 }
3595
3596 // Set up the Attributes for the function.
3597 SmallVector<AttributeWithIndex, 8> Attrs;
3598 if (RetAttrs != Attribute::None)
3599 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003600
Chris Lattnerdf986172009-01-02 07:01:27 +00003601 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003602
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 // Loop through FunctionType's arguments and ensure they are specified
3604 // correctly. Also, gather any parameter attributes.
3605 FunctionType::param_iterator I = Ty->param_begin();
3606 FunctionType::param_iterator E = Ty->param_end();
3607 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3608 const Type *ExpectedTy = 0;
3609 if (I != E) {
3610 ExpectedTy = *I++;
3611 } else if (!Ty->isVarArg()) {
3612 return Error(ArgList[i].Loc, "too many arguments specified");
3613 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3616 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3617 ExpectedTy->getDescription() + "'");
3618 Args.push_back(ArgList[i].V);
3619 if (ArgList[i].Attrs != Attribute::None)
3620 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3621 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003622
Chris Lattnerdf986172009-01-02 07:01:27 +00003623 if (I != E)
3624 return Error(CallLoc, "not enough parameters specified for call");
3625
3626 if (FnAttrs != Attribute::None)
3627 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3628
3629 // Finish off the Attributes and check them
3630 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003631
Chris Lattnerdf986172009-01-02 07:01:27 +00003632 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3633 CI->setTailCall(isTail);
3634 CI->setCallingConv(CC);
3635 CI->setAttributes(PAL);
3636 Inst = CI;
3637 return false;
3638}
3639
3640//===----------------------------------------------------------------------===//
3641// Memory Instructions.
3642//===----------------------------------------------------------------------===//
3643
3644/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003645/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3646/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003647bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003648 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003649 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003650 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003651 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003652 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003653 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003654
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003655 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003656 if (Lex.getKind() == lltok::kw_align
3657 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003658 if (ParseOptionalInfo(Alignment)) return true;
3659 } else {
3660 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3661 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003662 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003663 }
3664 }
3665
Owen Anderson1d0be152009-08-13 21:58:54 +00003666 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 return Error(SizeLoc, "element count must be i32");
3668
Victor Hernandez68afa542009-10-21 19:11:40 +00003669 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003670 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003671 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003672 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003673
3674 // Autoupgrade old malloc instruction to malloc call.
3675 // FIXME: Remove in LLVM 3.0.
3676 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003677 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3678 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003679 if (!MallocF)
3680 // Prototype malloc as "void *(int32)".
3681 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003682 MallocF = cast<Function>(
3683 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003684 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 return false;
3686}
3687
3688/// ParseFree
3689/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003690bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3691 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 Value *Val; LocTy Loc;
3693 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3694 if (!isa<PointerType>(Val->getType()))
3695 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003696 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 return false;
3698}
3699
3700/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003701/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003702bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3703 bool isVolatile) {
3704 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003705 unsigned Alignment = 0;
3706 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003707
Devang Patelf633a062009-09-17 23:04:48 +00003708 if (EatIfPresent(lltok::comma))
3709 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003710
3711 if (!isa<PointerType>(Val->getType()) ||
3712 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3713 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003714
Chris Lattnerdf986172009-01-02 07:01:27 +00003715 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3716 return false;
3717}
3718
3719/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003720/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003721bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3722 bool isVolatile) {
3723 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003724 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003725 if (ParseTypeAndValue(Val, Loc, PFS) ||
3726 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003727 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003728 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003729
3730 if (EatIfPresent(lltok::comma))
3731 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003732
Chris Lattnerdf986172009-01-02 07:01:27 +00003733 if (!isa<PointerType>(Ptr->getType()))
3734 return Error(PtrLoc, "store operand must be a pointer");
3735 if (!Val->getType()->isFirstClassType())
3736 return Error(Loc, "store operand must be a first class value");
3737 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3738 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003739
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3741 return false;
3742}
3743
3744/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003745/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003746/// FIXME: Remove support for getresult in LLVM 3.0
3747bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3748 Value *Val; LocTy ValLoc, EltLoc;
3749 unsigned Element;
3750 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3751 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003752 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003753 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003754
Chris Lattnerdf986172009-01-02 07:01:27 +00003755 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3756 return Error(ValLoc, "getresult inst requires an aggregate operand");
3757 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3758 return Error(EltLoc, "invalid getresult index for value");
3759 Inst = ExtractValueInst::Create(Val, Element);
3760 return false;
3761}
3762
3763/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003764/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003765bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3766 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003767
Dan Gohmandcb40a32009-07-29 15:58:36 +00003768 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003769
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003770 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003771
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 if (!isa<PointerType>(Ptr->getType()))
3773 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003774
Chris Lattnerdf986172009-01-02 07:01:27 +00003775 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003776 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003777 if (Lex.getKind() == lltok::NamedOrCustomMD)
3778 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003779 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003780 if (!isa<IntegerType>(Val->getType()))
3781 return Error(EltLoc, "getelementptr index must be an integer");
3782 Indices.push_back(Val);
3783 }
Devang Patel6225d642009-10-13 18:49:55 +00003784 if (Lex.getKind() == lltok::NamedOrCustomMD)
3785 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003786
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3788 Indices.begin(), Indices.end()))
3789 return Error(Loc, "invalid getelementptr indices");
3790 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003791 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003792 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003793 return false;
3794}
3795
3796/// ParseExtractValue
3797/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3798bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3799 Value *Val; LocTy Loc;
3800 SmallVector<unsigned, 4> Indices;
3801 if (ParseTypeAndValue(Val, Loc, PFS) ||
3802 ParseIndexList(Indices))
3803 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003804 if (Lex.getKind() == lltok::NamedOrCustomMD)
3805 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003806
3807 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3808 return Error(Loc, "extractvalue operand must be array or struct");
3809
3810 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3811 Indices.end()))
3812 return Error(Loc, "invalid indices for extractvalue");
3813 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3814 return false;
3815}
3816
3817/// ParseInsertValue
3818/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3819bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3820 Value *Val0, *Val1; LocTy Loc0, Loc1;
3821 SmallVector<unsigned, 4> Indices;
3822 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3823 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3824 ParseTypeAndValue(Val1, Loc1, PFS) ||
3825 ParseIndexList(Indices))
3826 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003827 if (Lex.getKind() == lltok::NamedOrCustomMD)
3828 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003829
Chris Lattnerdf986172009-01-02 07:01:27 +00003830 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3831 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003832
Chris Lattnerdf986172009-01-02 07:01:27 +00003833 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3834 Indices.end()))
3835 return Error(Loc0, "invalid indices for insertvalue");
3836 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3837 return false;
3838}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003839
3840//===----------------------------------------------------------------------===//
3841// Embedded metadata.
3842//===----------------------------------------------------------------------===//
3843
3844/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003845/// ::= Element (',' Element)*
3846/// Element
3847/// ::= 'null' | TypeAndValue
3848bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003849 assert(Lex.getKind() == lltok::lbrace);
3850 Lex.Lex();
3851 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003852 Value *V = 0;
Chris Lattner442ffa12009-12-29 21:53:55 +00003853 // FIXME: REWRITE.
Nick Lewyckycb337992009-05-10 20:57:05 +00003854 if (Lex.getKind() == lltok::kw_null) {
3855 Lex.Lex();
3856 V = 0;
3857 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003858 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003859 if (ParseType(Ty)) return true;
3860 if (Lex.getKind() == lltok::Metadata) {
3861 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00003862 MDNode *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003863 if (!ParseMDNode(Node))
3864 V = Node;
3865 else {
Chris Lattner442ffa12009-12-29 21:53:55 +00003866 MDString *MDS = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003867 if (ParseMDString(MDS)) return true;
3868 V = MDS;
3869 }
3870 } else {
3871 Constant *C;
3872 if (ParseGlobalValue(Ty, C)) return true;
3873 V = C;
3874 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003875 }
3876 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003877 } while (EatIfPresent(lltok::comma));
3878
3879 return false;
3880}