blob: 1ef4209dae3ae53432d04435b98e5ad92a5a50af [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
Chris Lattner42991ee2009-12-29 22:01:50 +0000495 // Create MDNode forward reference.
496
497 // FIXME: This is not unique enough!
Devang Patel256be962009-07-20 19:00:08 +0000498 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
Benjamin Kramerc17300f2009-12-29 22:17:06 +0000499 Value *V = MDString::get(Context, FwdRefName);
Chris Lattner42991ee2009-12-29 22:01:50 +0000500 MDNode *FwdNode = MDNode::get(Context, &V, 1);
Devang Patel256be962009-07-20 19:00:08 +0000501 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner442ffa12009-12-29 21:53:55 +0000502 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000503 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504}
Devang Patel256be962009-07-20 19:00:08 +0000505
Chris Lattner84d03b12009-12-29 22:35:39 +0000506/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000507/// !foo = !{ !1, !2 }
508bool LLParser::ParseNamedMetadata() {
Devang Patel0475c912009-09-29 00:01:14 +0000509 assert(Lex.getKind() == lltok::NamedOrCustomMD);
Devang Pateleff2ab62009-07-29 00:34:02 +0000510 Lex.Lex();
511 std::string Name = Lex.getStrVal();
512
Chris Lattner84d03b12009-12-29 22:35:39 +0000513 if (ParseToken(lltok::equal, "expected '=' here") ||
514 ParseToken(lltok::Metadata, "Expected '!' here") ||
515 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000516 return true;
517
Devang Pateleff2ab62009-07-29 00:34:02 +0000518 SmallVector<MetadataBase *, 8> Elts;
519 do {
Chris Lattner42991ee2009-12-29 22:01:50 +0000520 if (ParseToken(lltok::Metadata, "Expected '!' here"))
521 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000522
Chris Lattner42991ee2009-12-29 22:01:50 +0000523 // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not?
Chris Lattner442ffa12009-12-29 21:53:55 +0000524 MDNode *N = 0;
Devang Pateleff2ab62009-07-29 00:34:02 +0000525 if (ParseMDNode(N)) return true;
526 Elts.push_back(N);
527 } while (EatIfPresent(lltok::comma));
528
529 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
530 return true;
531
Owen Anderson1d0be152009-08-13 21:58:54 +0000532 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
Devang Pateleff2ab62009-07-29 00:34:02 +0000533 return false;
534}
535
Devang Patel923078c2009-07-01 19:21:12 +0000536/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000538bool LLParser::ParseStandaloneMetadata() {
539 assert(Lex.getKind() == lltok::Metadata);
540 Lex.Lex();
541 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000542
543 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000544 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000545 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000546 // FIXME: This doesn't make sense here. Pull braced MD stuff parsing out!
547 if (ParseUInt32(MetadataID) ||
548 ParseToken(lltok::equal, "expected '=' here") ||
549 ParseType(Ty, TyLoc) ||
550 ParseToken(lltok::Metadata, "Expected metadata here") ||
551 ParseToken(lltok::lbrace, "Expected '{' here") ||
552 ParseMDNodeVector(Elts) ||
553 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000554 return true;
555
Chris Lattner3f5132a2009-12-29 22:40:21 +0000556 if (MetadataCache.count(MetadataID))
557 return TokError("Metadata id is already used");
558
Owen Anderson647e3012009-07-31 21:35:40 +0000559 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Devang Patel923078c2009-07-01 19:21:12 +0000560 MetadataCache[MetadataID] = Init;
Chris Lattnere80250e2009-12-29 21:43:58 +0000561 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000562 FI = ForwardRefMDNodes.find(MetadataID);
563 if (FI != ForwardRefMDNodes.end()) {
Chris Lattnere80250e2009-12-29 21:43:58 +0000564 FI->second.first->replaceAllUsesWith(Init);
Devang Patel1c7eea62009-07-08 19:23:54 +0000565 ForwardRefMDNodes.erase(FI);
566 }
567
Devang Patel923078c2009-07-01 19:21:12 +0000568 return false;
569}
570
Chris Lattnerdf986172009-01-02 07:01:27 +0000571/// ParseAlias:
572/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
573/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000574/// ::= TypeAndValue
575/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000576/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000577///
578/// Everything through visibility has already been parsed.
579///
580bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
581 unsigned Visibility) {
582 assert(Lex.getKind() == lltok::kw_alias);
583 Lex.Lex();
584 unsigned Linkage;
585 LocTy LinkageLoc = Lex.getLoc();
586 if (ParseOptionalLinkage(Linkage))
587 return true;
588
589 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000590 Linkage != GlobalValue::WeakAnyLinkage &&
591 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000592 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000593 Linkage != GlobalValue::PrivateLinkage &&
594 Linkage != GlobalValue::LinkerPrivateLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000595 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000596
Chris Lattnerdf986172009-01-02 07:01:27 +0000597 Constant *Aliasee;
598 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000599 if (Lex.getKind() != lltok::kw_bitcast &&
600 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000601 if (ParseGlobalTypeAndValue(Aliasee)) return true;
602 } else {
603 // The bitcast dest type is not present, it is implied by the dest type.
604 ValID ID;
605 if (ParseValID(ID)) return true;
606 if (ID.Kind != ValID::t_Constant)
607 return Error(AliaseeLoc, "invalid aliasee");
608 Aliasee = ID.ConstantVal;
609 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000610
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 if (!isa<PointerType>(Aliasee->getType()))
612 return Error(AliaseeLoc, "alias must have pointer type");
613
614 // Okay, create the alias but do not insert it into the module yet.
615 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
616 (GlobalValue::LinkageTypes)Linkage, Name,
617 Aliasee);
618 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000619
Chris Lattnerdf986172009-01-02 07:01:27 +0000620 // See if this value already exists in the symbol table. If so, it is either
621 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000622 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000623 // See if this was a redefinition. If so, there is no entry in
624 // ForwardRefVals.
625 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
626 I = ForwardRefVals.find(Name);
627 if (I == ForwardRefVals.end())
628 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
629
630 // Otherwise, this was a definition of forward ref. Verify that types
631 // agree.
632 if (Val->getType() != GA->getType())
633 return Error(NameLoc,
634 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattnerdf986172009-01-02 07:01:27 +0000636 // If they agree, just RAUW the old value with the alias and remove the
637 // forward ref info.
638 Val->replaceAllUsesWith(GA);
639 Val->eraseFromParent();
640 ForwardRefVals.erase(I);
641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000642
Chris Lattnerdf986172009-01-02 07:01:27 +0000643 // Insert into the module, we know its name won't collide now.
644 M->getAliasList().push_back(GA);
645 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000646
Chris Lattnerdf986172009-01-02 07:01:27 +0000647 return false;
648}
649
650/// ParseGlobal
651/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
652/// OptionalAddrSpace GlobalType Type Const
653/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
654/// OptionalAddrSpace GlobalType Type Const
655///
656/// Everything through visibility has been parsed already.
657///
658bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
659 unsigned Linkage, bool HasLinkage,
660 unsigned Visibility) {
661 unsigned AddrSpace;
662 bool ThreadLocal, IsConstant;
663 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000664
Owen Anderson1d0be152009-08-13 21:58:54 +0000665 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000666 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
667 ParseOptionalAddrSpace(AddrSpace) ||
668 ParseGlobalType(IsConstant) ||
669 ParseType(Ty, TyLoc))
670 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Chris Lattnerdf986172009-01-02 07:01:27 +0000672 // If the linkage is specified and is external, then no initializer is
673 // present.
674 Constant *Init = 0;
675 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000676 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 Linkage != GlobalValue::ExternalLinkage)) {
678 if (ParseGlobalValue(Ty, Init))
679 return true;
680 }
681
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000682 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000683 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 GlobalVariable *GV = 0;
686
687 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000688 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000689 if (GlobalValue *GVal = M->getNamedValue(Name)) {
690 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
691 return Error(NameLoc, "redefinition of global '@" + Name + "'");
692 GV = cast<GlobalVariable>(GVal);
693 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000694 } else {
695 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
696 I = ForwardRefValIDs.find(NumberedVals.size());
697 if (I != ForwardRefValIDs.end()) {
698 GV = cast<GlobalVariable>(I->second.first);
699 ForwardRefValIDs.erase(I);
700 }
701 }
702
703 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000704 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000705 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000706 } else {
707 if (GV->getType()->getElementType() != Ty)
708 return Error(TyLoc,
709 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000710
Chris Lattnerdf986172009-01-02 07:01:27 +0000711 // Move the forward-reference to the correct spot in the module.
712 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
713 }
714
715 if (Name.empty())
716 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 // Set the parsed properties on the global.
719 if (Init)
720 GV->setInitializer(Init);
721 GV->setConstant(IsConstant);
722 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
723 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
724 GV->setThreadLocal(ThreadLocal);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000725
Chris Lattnerdf986172009-01-02 07:01:27 +0000726 // Parse attributes on the global.
727 while (Lex.getKind() == lltok::comma) {
728 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000729
Chris Lattnerdf986172009-01-02 07:01:27 +0000730 if (Lex.getKind() == lltok::kw_section) {
731 Lex.Lex();
732 GV->setSection(Lex.getStrVal());
733 if (ParseToken(lltok::StringConstant, "expected global section string"))
734 return true;
735 } else if (Lex.getKind() == lltok::kw_align) {
736 unsigned Alignment;
737 if (ParseOptionalAlignment(Alignment)) return true;
738 GV->setAlignment(Alignment);
739 } else {
740 TokError("unknown global variable property!");
741 }
742 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743
Chris Lattnerdf986172009-01-02 07:01:27 +0000744 return false;
745}
746
747
748//===----------------------------------------------------------------------===//
749// GlobalValue Reference/Resolution Routines.
750//===----------------------------------------------------------------------===//
751
752/// GetGlobalVal - Get a value with the specified name or ID, creating a
753/// forward reference record if needed. This can return null if the value
754/// exists but does not have the right type.
755GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
756 LocTy Loc) {
757 const PointerType *PTy = dyn_cast<PointerType>(Ty);
758 if (PTy == 0) {
759 Error(Loc, "global variable reference must have pointer type");
760 return 0;
761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000762
Chris Lattnerdf986172009-01-02 07:01:27 +0000763 // Look this name up in the normal function symbol table.
764 GlobalValue *Val =
765 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Chris Lattnerdf986172009-01-02 07:01:27 +0000767 // If this is a forward reference for the value, see if we already created a
768 // forward ref record.
769 if (Val == 0) {
770 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
771 I = ForwardRefVals.find(Name);
772 if (I != ForwardRefVals.end())
773 Val = I->second.first;
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 // If we have the value in the symbol table or fwd-ref table, return it.
777 if (Val) {
778 if (Val->getType() == Ty) return Val;
779 Error(Loc, "'@" + Name + "' defined with type '" +
780 Val->getType()->getDescription() + "'");
781 return 0;
782 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000783
Chris Lattnerdf986172009-01-02 07:01:27 +0000784 // Otherwise, create a new forward reference for this value and remember it.
785 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000786 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
787 // Function types can return opaque but functions can't.
788 if (isa<OpaqueType>(FT->getReturnType())) {
789 Error(Loc, "function may not return opaque type");
790 return 0;
791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000793 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000794 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000795 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
796 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000797 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
800 return FwdVal;
801}
802
803GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, 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 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 // If this is a forward reference for the value, see if we already created a
813 // forward ref record.
814 if (Val == 0) {
815 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
816 I = ForwardRefValIDs.find(ID);
817 if (I != ForwardRefValIDs.end())
818 Val = I->second.first;
819 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000820
Chris Lattnerdf986172009-01-02 07:01:27 +0000821 // If we have the value in the symbol table or fwd-ref table, return it.
822 if (Val) {
823 if (Val->getType() == Ty) return Val;
824 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
825 Val->getType()->getDescription() + "'");
826 return 0;
827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000828
Chris Lattnerdf986172009-01-02 07:01:27 +0000829 // Otherwise, create a new forward reference for this value and remember it.
830 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000831 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
832 // Function types can return opaque but functions can't.
833 if (isa<OpaqueType>(FT->getReturnType())) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000834 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000835 return 0;
836 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000837 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000838 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000839 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
840 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000842
Chris Lattnerdf986172009-01-02 07:01:27 +0000843 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
844 return FwdVal;
845}
846
847
848//===----------------------------------------------------------------------===//
849// Helper Routines.
850//===----------------------------------------------------------------------===//
851
852/// ParseToken - If the current token has the specified kind, eat it and return
853/// success. Otherwise, emit the specified error and return failure.
854bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
855 if (Lex.getKind() != T)
856 return TokError(ErrMsg);
857 Lex.Lex();
858 return false;
859}
860
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000861/// ParseStringConstant
862/// ::= StringConstant
863bool LLParser::ParseStringConstant(std::string &Result) {
864 if (Lex.getKind() != lltok::StringConstant)
865 return TokError("expected string constant");
866 Result = Lex.getStrVal();
867 Lex.Lex();
868 return false;
869}
870
871/// ParseUInt32
872/// ::= uint32
873bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000874 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
875 return TokError("expected integer");
876 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
877 if (Val64 != unsigned(Val64))
878 return TokError("expected 32-bit integer (too large)");
879 Val = Val64;
880 Lex.Lex();
881 return false;
882}
883
884
885/// ParseOptionalAddrSpace
886/// := /*empty*/
887/// := 'addrspace' '(' uint32 ')'
888bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
889 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000890 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000891 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000892 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000893 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000894 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895}
Chris Lattnerdf986172009-01-02 07:01:27 +0000896
897/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
898/// indicates what kind of attribute list this is: 0: function arg, 1: result,
899/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000900/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000901bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
902 Attrs = Attribute::None;
903 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000904
Chris Lattnerdf986172009-01-02 07:01:27 +0000905 while (1) {
906 switch (Lex.getKind()) {
907 case lltok::kw_sext:
908 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000909 // Treat these as signext/zeroext if they occur in the argument list after
910 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
911 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
912 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000914 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 if (Lex.getKind() == lltok::kw_sext)
916 Attrs |= Attribute::SExt;
917 else
918 Attrs |= Attribute::ZExt;
919 break;
920 }
921 // FALL THROUGH.
922 default: // End of attributes.
923 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
924 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000926 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000927 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928
Chris Lattnerdf986172009-01-02 07:01:27 +0000929 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000930 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
931 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
932 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
933 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
934 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
935 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
936 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
937 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000938
Devang Patel578efa92009-06-05 21:57:13 +0000939 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
940 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
941 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
942 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
943 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Dale Johannesende86d472009-08-26 01:08:21 +0000944 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000945 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
946 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
947 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
948 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
949 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
950 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000951 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000952
Chris Lattnerdf986172009-01-02 07:01:27 +0000953 case lltok::kw_align: {
954 unsigned Alignment;
955 if (ParseOptionalAlignment(Alignment))
956 return true;
957 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
958 continue;
959 }
960 }
961 Lex.Lex();
962 }
963}
964
965/// ParseOptionalLinkage
966/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000967/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000968/// ::= 'linker_private'
Chris Lattnerdf986172009-01-02 07:01:27 +0000969/// ::= 'internal'
970/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000971/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000972/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000973/// ::= 'linkonce_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000974/// ::= 'appending'
975/// ::= 'dllexport'
976/// ::= 'common'
977/// ::= 'dllimport'
978/// ::= 'extern_weak'
979/// ::= 'external'
980bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
981 HasLinkage = false;
982 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000983 default: Res=GlobalValue::ExternalLinkage; return false;
984 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
985 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
986 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
987 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
988 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
989 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
990 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000991 case lltok::kw_available_externally:
992 Res = GlobalValue::AvailableExternallyLinkage;
993 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000994 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
995 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
996 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
997 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
998 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
999 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001000 }
1001 Lex.Lex();
1002 HasLinkage = true;
1003 return false;
1004}
1005
1006/// ParseOptionalVisibility
1007/// ::= /*empty*/
1008/// ::= 'default'
1009/// ::= 'hidden'
1010/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001011///
Chris Lattnerdf986172009-01-02 07:01:27 +00001012bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1013 switch (Lex.getKind()) {
1014 default: Res = GlobalValue::DefaultVisibility; return false;
1015 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1016 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1017 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1018 }
1019 Lex.Lex();
1020 return false;
1021}
1022
1023/// ParseOptionalCallingConv
1024/// ::= /*empty*/
1025/// ::= 'ccc'
1026/// ::= 'fastcc'
1027/// ::= 'coldcc'
1028/// ::= 'x86_stdcallcc'
1029/// ::= 'x86_fastcallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001030/// ::= 'arm_apcscc'
1031/// ::= 'arm_aapcscc'
1032/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001033/// ::= 'msp430_intrcc'
Chris Lattnerdf986172009-01-02 07:01:27 +00001034/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001035///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001036bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001037 switch (Lex.getKind()) {
1038 default: CC = CallingConv::C; return false;
1039 case lltok::kw_ccc: CC = CallingConv::C; break;
1040 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1041 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1042 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1043 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001044 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1045 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1046 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001047 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001048 case lltok::kw_cc: {
1049 unsigned ArbitraryCC;
1050 Lex.Lex();
1051 if (ParseUInt32(ArbitraryCC)) {
1052 return true;
1053 } else
1054 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1055 return false;
1056 }
1057 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001058 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001059
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 Lex.Lex();
1061 return false;
1062}
1063
Devang Patel0475c912009-09-29 00:01:14 +00001064/// ParseOptionalCustomMetadata
Devang Patelf633a062009-09-17 23:04:48 +00001065/// ::= /* empty */
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001066/// ::= !dbg !42 (',' !dbg !57)*
Devang Patel0475c912009-09-29 00:01:14 +00001067bool LLParser::ParseOptionalCustomMetadata() {
Chris Lattner52e20312009-10-19 05:31:10 +00001068 if (Lex.getKind() != lltok::NamedOrCustomMD)
Devang Patelf633a062009-09-17 23:04:48 +00001069 return false;
Devang Patel0475c912009-09-29 00:01:14 +00001070
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001071 while (1) {
1072 std::string Name = Lex.getStrVal();
1073 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001074
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001075 if (Lex.getKind() != lltok::Metadata)
1076 return TokError("expected '!' here");
1077 Lex.Lex();
Devang Patel0475c912009-09-29 00:01:14 +00001078
Chris Lattner442ffa12009-12-29 21:53:55 +00001079 MDNode *Node;
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001080 if (ParseMDNode(Node)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001082 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner442ffa12009-12-29 21:53:55 +00001083 MDsOnInst.push_back(std::make_pair(MDK, Node));
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001084
1085 // If this is the end of the list, we're done.
1086 if (!EatIfPresent(lltok::comma))
1087 return false;
1088
1089 // The next value must be a custom metadata id.
1090 if (Lex.getKind() != lltok::NamedOrCustomMD)
1091 return TokError("expected more custom metadata ids");
1092 }
Devang Patelf633a062009-09-17 23:04:48 +00001093}
1094
Chris Lattnerdf986172009-01-02 07:01:27 +00001095/// ParseOptionalAlignment
1096/// ::= /* empty */
1097/// ::= 'align' 4
1098bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1099 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001100 if (!EatIfPresent(lltok::kw_align))
1101 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001102 LocTy AlignLoc = Lex.getLoc();
1103 if (ParseUInt32(Alignment)) return true;
1104 if (!isPowerOf2_32(Alignment))
1105 return Error(AlignLoc, "alignment is not a power of two");
1106 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001107}
1108
Devang Patelf633a062009-09-17 23:04:48 +00001109/// ParseOptionalInfo
1110/// ::= OptionalInfo (',' OptionalInfo)+
1111bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1112
1113 // FIXME: Handle customized metadata info attached with an instruction.
1114 do {
Devang Patel0475c912009-09-29 00:01:14 +00001115 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1116 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00001117 } else if (Lex.getKind() == lltok::kw_align) {
1118 if (ParseOptionalAlignment(Alignment)) return true;
1119 } else
1120 return true;
1121 } while (EatIfPresent(lltok::comma));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001122
Devang Patelf633a062009-09-17 23:04:48 +00001123 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001124}
1125
Devang Patelf633a062009-09-17 23:04:48 +00001126
Chris Lattnerdf986172009-01-02 07:01:27 +00001127/// ParseIndexList
1128/// ::= (',' uint32)+
1129bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1130 if (Lex.getKind() != lltok::comma)
1131 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001132
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001133 while (EatIfPresent(lltok::comma)) {
Devang Patele8bc45a2009-11-03 19:06:07 +00001134 if (Lex.getKind() == lltok::NamedOrCustomMD)
1135 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001136 unsigned Idx;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001137 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001138 Indices.push_back(Idx);
1139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140
Chris Lattnerdf986172009-01-02 07:01:27 +00001141 return false;
1142}
1143
1144//===----------------------------------------------------------------------===//
1145// Type Parsing.
1146//===----------------------------------------------------------------------===//
1147
1148/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001149bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1150 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001151 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152
Chris Lattnerdf986172009-01-02 07:01:27 +00001153 // Verify no unresolved uprefs.
1154 if (!UpRefs.empty())
1155 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001156
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001157 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001158 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001159
Chris Lattnerdf986172009-01-02 07:01:27 +00001160 return false;
1161}
1162
1163/// HandleUpRefs - Every time we finish a new layer of types, this function is
1164/// called. It loops through the UpRefs vector, which is a list of the
1165/// currently active types. For each type, if the up-reference is contained in
1166/// the newly completed type, we decrement the level count. When the level
1167/// count reaches zero, the up-referenced type is the type that is passed in:
1168/// thus we can complete the cycle.
1169///
1170PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1171 // If Ty isn't abstract, or if there are no up-references in it, then there is
1172 // nothing to resolve here.
1173 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001174
Chris Lattnerdf986172009-01-02 07:01:27 +00001175 PATypeHolder Ty(ty);
1176#if 0
David Greene0e28d762009-12-23 23:38:28 +00001177 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001178 << "' newly formed. Resolving upreferences.\n"
1179 << UpRefs.size() << " upreferences active!\n";
1180#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001181
Chris Lattnerdf986172009-01-02 07:01:27 +00001182 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1183 // to zero), we resolve them all together before we resolve them to Ty. At
1184 // the end of the loop, if there is anything to resolve to Ty, it will be in
1185 // this variable.
1186 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001187
Chris Lattnerdf986172009-01-02 07:01:27 +00001188 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1189 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1190 bool ContainsType =
1191 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1192 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001193
Chris Lattnerdf986172009-01-02 07:01:27 +00001194#if 0
David Greene0e28d762009-12-23 23:38:28 +00001195 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001196 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1197 << (ContainsType ? "true" : "false")
1198 << " level=" << UpRefs[i].NestingLevel << "\n";
1199#endif
1200 if (!ContainsType)
1201 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202
Chris Lattnerdf986172009-01-02 07:01:27 +00001203 // Decrement level of upreference
1204 unsigned Level = --UpRefs[i].NestingLevel;
1205 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Chris Lattnerdf986172009-01-02 07:01:27 +00001207 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1208 if (Level != 0)
1209 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210
Chris Lattnerdf986172009-01-02 07:01:27 +00001211#if 0
David Greene0e28d762009-12-23 23:38:28 +00001212 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001213#endif
1214 if (!TypeToResolve)
1215 TypeToResolve = UpRefs[i].UpRefTy;
1216 else
1217 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1218 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1219 --i; // Do not skip the next element.
1220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001221
Chris Lattnerdf986172009-01-02 07:01:27 +00001222 if (TypeToResolve)
1223 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001224
Chris Lattnerdf986172009-01-02 07:01:27 +00001225 return Ty;
1226}
1227
1228
1229/// ParseTypeRec - The recursive function used to process the internal
1230/// implementation details of types.
1231bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1232 switch (Lex.getKind()) {
1233 default:
1234 return TokError("expected type");
1235 case lltok::Type:
1236 // TypeRec ::= 'float' | 'void' (etc)
1237 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001238 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001239 break;
1240 case lltok::kw_opaque:
1241 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001242 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001243 Lex.Lex();
1244 break;
1245 case lltok::lbrace:
1246 // TypeRec ::= '{' ... '}'
1247 if (ParseStructType(Result, false))
1248 return true;
1249 break;
1250 case lltok::lsquare:
1251 // TypeRec ::= '[' ... ']'
1252 Lex.Lex(); // eat the lsquare.
1253 if (ParseArrayVectorType(Result, false))
1254 return true;
1255 break;
1256 case lltok::less: // Either vector or packed struct.
1257 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001258 Lex.Lex();
1259 if (Lex.getKind() == lltok::lbrace) {
1260 if (ParseStructType(Result, true) ||
1261 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001262 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001263 } else if (ParseArrayVectorType(Result, true))
1264 return true;
1265 break;
1266 case lltok::LocalVar:
1267 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1268 // TypeRec ::= %foo
1269 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1270 Result = T;
1271 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001272 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001273 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1274 std::make_pair(Result,
1275 Lex.getLoc())));
1276 M->addTypeName(Lex.getStrVal(), Result.get());
1277 }
1278 Lex.Lex();
1279 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001280
Chris Lattnerdf986172009-01-02 07:01:27 +00001281 case lltok::LocalVarID:
1282 // TypeRec ::= %4
1283 if (Lex.getUIntVal() < NumberedTypes.size())
1284 Result = NumberedTypes[Lex.getUIntVal()];
1285 else {
1286 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1287 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1288 if (I != ForwardRefTypeIDs.end())
1289 Result = I->second.first;
1290 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001291 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1293 std::make_pair(Result,
1294 Lex.getLoc())));
1295 }
1296 }
1297 Lex.Lex();
1298 break;
1299 case lltok::backslash: {
1300 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001302 unsigned Val;
1303 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001304 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1306 Result = OT;
1307 break;
1308 }
1309 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
1311 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001312 while (1) {
1313 switch (Lex.getKind()) {
1314 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001315 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001316
1317 // TypeRec ::= TypeRec '*'
1318 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001319 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001321 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001322 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001323 if (!PointerType::isValidElementType(Result.get()))
1324 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001325 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 Lex.Lex();
1327 break;
1328
1329 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1330 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001331 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001332 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001333 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001334 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001335 if (!PointerType::isValidElementType(Result.get()))
1336 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001337 unsigned AddrSpace;
1338 if (ParseOptionalAddrSpace(AddrSpace) ||
1339 ParseToken(lltok::star, "expected '*' in address space"))
1340 return true;
1341
Owen Andersondebcb012009-07-29 22:17:13 +00001342 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 break;
1344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001345
Chris Lattnerdf986172009-01-02 07:01:27 +00001346 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1347 case lltok::lparen:
1348 if (ParseFunctionType(Result))
1349 return true;
1350 break;
1351 }
1352 }
1353}
1354
1355/// ParseParameterList
1356/// ::= '(' ')'
1357/// ::= '(' Arg (',' Arg)* ')'
1358/// Arg
1359/// ::= Type OptionalAttributes Value OptionalAttributes
1360bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1361 PerFunctionState &PFS) {
1362 if (ParseToken(lltok::lparen, "expected '(' in call"))
1363 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattnerdf986172009-01-02 07:01:27 +00001365 while (Lex.getKind() != lltok::rparen) {
1366 // If this isn't the first argument, we need a comma.
1367 if (!ArgList.empty() &&
1368 ParseToken(lltok::comma, "expected ',' in argument list"))
1369 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001370
Chris Lattnerdf986172009-01-02 07:01:27 +00001371 // Parse the argument.
1372 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001373 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001374 unsigned ArgAttrs1 = Attribute::None;
1375 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001376 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001377 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001378 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001379
Chris Lattner287881d2009-12-30 02:11:14 +00001380 // Otherwise, handle normal operands.
1381 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1382 ParseValue(ArgTy, V, PFS) ||
1383 // FIXME: Should not allow attributes after the argument, remove this
1384 // in LLVM 3.0.
1385 ParseOptionalAttrs(ArgAttrs2, 3))
1386 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1388 }
1389
1390 Lex.Lex(); // Lex the ')'.
1391 return false;
1392}
1393
1394
1395
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001396/// ParseArgumentList - Parse the argument list for a function type or function
1397/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001398/// ::= '(' ArgTypeListI ')'
1399/// ArgTypeListI
1400/// ::= /*empty*/
1401/// ::= '...'
1402/// ::= ArgTypeList ',' '...'
1403/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001404///
Chris Lattnerdf986172009-01-02 07:01:27 +00001405bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001406 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001407 isVarArg = false;
1408 assert(Lex.getKind() == lltok::lparen);
1409 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattnerdf986172009-01-02 07:01:27 +00001411 if (Lex.getKind() == lltok::rparen) {
1412 // empty
1413 } else if (Lex.getKind() == lltok::dotdotdot) {
1414 isVarArg = true;
1415 Lex.Lex();
1416 } else {
1417 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001418 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001421
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001422 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1423 // types (such as a function returning a pointer to itself). If parsing a
1424 // function prototype, we require fully resolved types.
1425 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001426 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001428 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001429 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001430
Chris Lattnerdf986172009-01-02 07:01:27 +00001431 if (Lex.getKind() == lltok::LocalVar ||
1432 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1433 Name = Lex.getStrVal();
1434 Lex.Lex();
1435 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001436
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001437 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001438 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001439
Chris Lattnerdf986172009-01-02 07:01:27 +00001440 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001441
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001442 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001444 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001445 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001446 break;
1447 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 // Otherwise must be an argument type.
1450 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001451 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001452 ParseOptionalAttrs(Attrs, 0)) return true;
1453
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001454 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001455 return Error(TypeLoc, "argument can not have void type");
1456
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 if (Lex.getKind() == lltok::LocalVar ||
1458 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1459 Name = Lex.getStrVal();
1460 Lex.Lex();
1461 } else {
1462 Name = "";
1463 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001464
1465 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1466 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001467
Chris Lattnerdf986172009-01-02 07:01:27 +00001468 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1469 }
1470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001472 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001473}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattnerdf986172009-01-02 07:01:27 +00001475/// ParseFunctionType
1476/// ::= Type ArgumentList OptionalAttrs
1477bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1478 assert(Lex.getKind() == lltok::lparen);
1479
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001480 if (!FunctionType::isValidReturnType(Result))
1481 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001482
Chris Lattnerdf986172009-01-02 07:01:27 +00001483 std::vector<ArgInfo> ArgList;
1484 bool isVarArg;
1485 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001486 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001487 // FIXME: Allow, but ignore attributes on function types!
1488 // FIXME: Remove in LLVM 3.0
1489 ParseOptionalAttrs(Attrs, 2))
1490 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001491
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 // Reject names on the arguments lists.
1493 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1494 if (!ArgList[i].Name.empty())
1495 return Error(ArgList[i].Loc, "argument name invalid in function type");
1496 if (!ArgList[i].Attrs != 0) {
1497 // Allow but ignore attributes on function types; this permits
1498 // auto-upgrade.
1499 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1500 }
1501 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001502
Chris Lattnerdf986172009-01-02 07:01:27 +00001503 std::vector<const Type*> ArgListTy;
1504 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1505 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Owen Andersondebcb012009-07-29 22:17:13 +00001507 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001508 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001509 return false;
1510}
1511
1512/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1513/// TypeRec
1514/// ::= '{' '}'
1515/// ::= '{' TypeRec (',' TypeRec)* '}'
1516/// ::= '<' '{' '}' '>'
1517/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1518bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1519 assert(Lex.getKind() == lltok::lbrace);
1520 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001521
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001522 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001523 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001524 return false;
1525 }
1526
1527 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001528 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001529 if (ParseTypeRec(Result)) return true;
1530 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001531
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001532 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001533 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001534 if (!StructType::isValidElementType(Result))
1535 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001536
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001538 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001539 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001541 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001542 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001543 if (!StructType::isValidElementType(Result))
1544 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001545
Chris Lattnerdf986172009-01-02 07:01:27 +00001546 ParamsList.push_back(Result);
1547 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001548
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1550 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 std::vector<const Type*> ParamsListTy;
1553 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1554 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001555 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001556 return false;
1557}
1558
1559/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1560/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001562/// ::= '[' APSINTVAL 'x' Types ']'
1563/// ::= '<' APSINTVAL 'x' Types '>'
1564bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1565 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1566 Lex.getAPSIntVal().getBitWidth() > 64)
1567 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001568
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 LocTy SizeLoc = Lex.getLoc();
1570 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001571 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001573 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1574 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001575
1576 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001577 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001578 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001580 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001581 return Error(TypeLoc, "array and vector element type cannot be void");
1582
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001583 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1584 "expected end of sequential type"))
1585 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586
Chris Lattnerdf986172009-01-02 07:01:27 +00001587 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001588 if (Size == 0)
1589 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 if ((unsigned)Size != Size)
1591 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001592 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001593 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001594 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001595 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001596 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001598 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001599 }
1600 return false;
1601}
1602
1603//===----------------------------------------------------------------------===//
1604// Function Semantic Analysis.
1605//===----------------------------------------------------------------------===//
1606
Chris Lattner09d9ef42009-10-28 03:39:23 +00001607LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1608 int functionNumber)
1609 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001610
1611 // Insert unnamed arguments into the NumberedVals list.
1612 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1613 AI != E; ++AI)
1614 if (!AI->hasName())
1615 NumberedVals.push_back(AI);
1616}
1617
1618LLParser::PerFunctionState::~PerFunctionState() {
1619 // If there were any forward referenced non-basicblock values, delete them.
1620 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1621 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1622 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001623 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001624 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001625 delete I->second.first;
1626 I->second.first = 0;
1627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001628
Chris Lattnerdf986172009-01-02 07:01:27 +00001629 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1630 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1631 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001632 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001633 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001634 delete I->second.first;
1635 I->second.first = 0;
1636 }
1637}
1638
Chris Lattner09d9ef42009-10-28 03:39:23 +00001639bool LLParser::PerFunctionState::FinishFunction() {
1640 // Check to see if someone took the address of labels in this block.
1641 if (!P.ForwardRefBlockAddresses.empty()) {
1642 ValID FunctionID;
1643 if (!F.getName().empty()) {
1644 FunctionID.Kind = ValID::t_GlobalName;
1645 FunctionID.StrVal = F.getName();
1646 } else {
1647 FunctionID.Kind = ValID::t_GlobalID;
1648 FunctionID.UIntVal = FunctionNumber;
1649 }
1650
1651 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1652 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1653 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1654 // Resolve all these references.
1655 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1656 return true;
1657
1658 P.ForwardRefBlockAddresses.erase(FRBAI);
1659 }
1660 }
1661
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 if (!ForwardRefVals.empty())
1663 return P.Error(ForwardRefVals.begin()->second.second,
1664 "use of undefined value '%" + ForwardRefVals.begin()->first +
1665 "'");
1666 if (!ForwardRefValIDs.empty())
1667 return P.Error(ForwardRefValIDs.begin()->second.second,
1668 "use of undefined value '%" +
1669 utostr(ForwardRefValIDs.begin()->first) + "'");
1670 return false;
1671}
1672
1673
1674/// GetVal - Get a value with the specified name or ID, creating a
1675/// forward reference record if needed. This can return null if the value
1676/// exists but does not have the right type.
1677Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1678 const Type *Ty, LocTy Loc) {
1679 // Look this name up in the normal function symbol table.
1680 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 // If this is a forward reference for the value, see if we already created a
1683 // forward ref record.
1684 if (Val == 0) {
1685 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1686 I = ForwardRefVals.find(Name);
1687 if (I != ForwardRefVals.end())
1688 Val = I->second.first;
1689 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Chris Lattnerdf986172009-01-02 07:01:27 +00001691 // If we have the value in the symbol table or fwd-ref table, return it.
1692 if (Val) {
1693 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001694 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001695 P.Error(Loc, "'%" + Name + "' is not a basic block");
1696 else
1697 P.Error(Loc, "'%" + Name + "' defined with type '" +
1698 Val->getType()->getDescription() + "'");
1699 return 0;
1700 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001701
Chris Lattnerdf986172009-01-02 07:01:27 +00001702 // Don't make placeholders with invalid type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001703 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1704 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001705 P.Error(Loc, "invalid use of a non-first-class type");
1706 return 0;
1707 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Chris Lattnerdf986172009-01-02 07:01:27 +00001709 // Otherwise, create a new forward reference for this value and remember it.
1710 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001711 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001712 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 else
1714 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001715
Chris Lattnerdf986172009-01-02 07:01:27 +00001716 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1717 return FwdVal;
1718}
1719
1720Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1721 LocTy Loc) {
1722 // Look this name up in the normal function symbol table.
1723 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattnerdf986172009-01-02 07:01:27 +00001725 // If this is a forward reference for the value, see if we already created a
1726 // forward ref record.
1727 if (Val == 0) {
1728 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1729 I = ForwardRefValIDs.find(ID);
1730 if (I != ForwardRefValIDs.end())
1731 Val = I->second.first;
1732 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001733
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 // If we have the value in the symbol table or fwd-ref table, return it.
1735 if (Val) {
1736 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001737 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1739 else
1740 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1741 Val->getType()->getDescription() + "'");
1742 return 0;
1743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001744
Owen Anderson1d0be152009-08-13 21:58:54 +00001745 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1746 Ty != Type::getLabelTy(F.getContext())) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 P.Error(Loc, "invalid use of a non-first-class type");
1748 return 0;
1749 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001750
Chris Lattnerdf986172009-01-02 07:01:27 +00001751 // Otherwise, create a new forward reference for this value and remember it.
1752 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001753 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001754 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001755 else
1756 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001757
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1759 return FwdVal;
1760}
1761
1762/// SetInstName - After an instruction is parsed and inserted into its
1763/// basic block, this installs its name.
1764bool LLParser::PerFunctionState::SetInstName(int NameID,
1765 const std::string &NameStr,
1766 LocTy NameLoc, Instruction *Inst) {
1767 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001768 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001769 if (NameID != -1 || !NameStr.empty())
1770 return P.Error(NameLoc, "instructions returning void cannot have a name");
1771 return false;
1772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 // If this was a numbered instruction, verify that the instruction is the
1775 // expected value and resolve any forward references.
1776 if (NameStr.empty()) {
1777 // If neither a name nor an ID was specified, just use the next ID.
1778 if (NameID == -1)
1779 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001780
Chris Lattnerdf986172009-01-02 07:01:27 +00001781 if (unsigned(NameID) != NumberedVals.size())
1782 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1783 utostr(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1786 ForwardRefValIDs.find(NameID);
1787 if (FI != ForwardRefValIDs.end()) {
1788 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001789 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001790 FI->second.first->getType()->getDescription() + "'");
1791 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001792 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 ForwardRefValIDs.erase(FI);
1794 }
1795
1796 NumberedVals.push_back(Inst);
1797 return false;
1798 }
1799
1800 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1801 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1802 FI = ForwardRefVals.find(NameStr);
1803 if (FI != ForwardRefVals.end()) {
1804 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001805 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001806 FI->second.first->getType()->getDescription() + "'");
1807 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001808 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 ForwardRefVals.erase(FI);
1810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001811
Chris Lattnerdf986172009-01-02 07:01:27 +00001812 // Set the name on the instruction.
1813 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 if (Inst->getNameStr() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001816 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001817 NameStr + "'");
1818 return false;
1819}
1820
1821/// GetBB - Get a basic block with the specified name or ID, creating a
1822/// forward reference record if needed.
1823BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1824 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001825 return cast_or_null<BasicBlock>(GetVal(Name,
1826 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001827}
1828
1829BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001830 return cast_or_null<BasicBlock>(GetVal(ID,
1831 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001832}
1833
1834/// DefineBB - Define the specified basic block, which is either named or
1835/// unnamed. If there is an error, this returns null otherwise it returns
1836/// the block being defined.
1837BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1838 LocTy Loc) {
1839 BasicBlock *BB;
1840 if (Name.empty())
1841 BB = GetBB(NumberedVals.size(), Loc);
1842 else
1843 BB = GetBB(Name, Loc);
1844 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001845
Chris Lattnerdf986172009-01-02 07:01:27 +00001846 // Move the block to the end of the function. Forward ref'd blocks are
1847 // inserted wherever they happen to be referenced.
1848 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001849
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 // Remove the block from forward ref sets.
1851 if (Name.empty()) {
1852 ForwardRefValIDs.erase(NumberedVals.size());
1853 NumberedVals.push_back(BB);
1854 } else {
1855 // BB forward references are already in the function symbol table.
1856 ForwardRefVals.erase(Name);
1857 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Chris Lattnerdf986172009-01-02 07:01:27 +00001859 return BB;
1860}
1861
1862//===----------------------------------------------------------------------===//
1863// Constants.
1864//===----------------------------------------------------------------------===//
1865
1866/// ParseValID - Parse an abstract value that doesn't necessarily have a
1867/// type implied. For example, if we parse "4" we don't know what integer type
1868/// it has. The value will later be combined with its type and checked for
1869/// sanity.
1870bool LLParser::ParseValID(ValID &ID) {
1871 ID.Loc = Lex.getLoc();
1872 switch (Lex.getKind()) {
1873 default: return TokError("expected value token");
1874 case lltok::GlobalID: // @42
1875 ID.UIntVal = Lex.getUIntVal();
1876 ID.Kind = ValID::t_GlobalID;
1877 break;
1878 case lltok::GlobalVar: // @foo
1879 ID.StrVal = Lex.getStrVal();
1880 ID.Kind = ValID::t_GlobalName;
1881 break;
1882 case lltok::LocalVarID: // %42
1883 ID.UIntVal = Lex.getUIntVal();
1884 ID.Kind = ValID::t_LocalID;
1885 break;
1886 case lltok::LocalVar: // %foo
1887 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1888 ID.StrVal = Lex.getStrVal();
1889 ID.Kind = ValID::t_LocalName;
1890 break;
Chris Lattner860775c2009-12-30 04:13:37 +00001891 case lltok::Metadata: // !{...} MDNode, !"foo" MDString
Nick Lewycky21cc4462009-04-04 07:22:01 +00001892 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00001893
1894 // FIXME: This doesn't belong here.
Chris Lattner3f5132a2009-12-29 22:40:21 +00001895 if (EatIfPresent(lltok::lbrace)) {
Nick Lewyckycb337992009-05-10 20:57:05 +00001896 SmallVector<Value*, 16> Elts;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001897 if (ParseMDNodeVector(Elts) ||
1898 ParseToken(lltok::rbrace, "expected end of metadata node"))
1899 return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00001900
Chris Lattner287881d2009-12-30 02:11:14 +00001901 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
1902 ID.Kind = ValID::t_MDNode;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001903 return false;
1904 }
1905
Devang Patel923078c2009-07-01 19:21:12 +00001906 // Standalone metadata reference
1907 // !{ ..., !42, ... }
Chris Lattner860775c2009-12-30 04:13:37 +00001908 if (Lex.getKind() == lltok::APSInt) {
1909 if (ParseMDNode(ID.MDNodeVal)) return true;
Chris Lattner287881d2009-12-30 02:11:14 +00001910 ID.Kind = ValID::t_MDNode;
Devang Patel923078c2009-07-01 19:21:12 +00001911 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00001912 }
1913
Nick Lewycky21cc4462009-04-04 07:22:01 +00001914 // MDString:
1915 // ::= '!' STRINGCONSTANT
Chris Lattner287881d2009-12-30 02:11:14 +00001916 if (ParseMDString(ID.MDStringVal)) return true;
1917 ID.Kind = ValID::t_MDString;
Nick Lewycky21cc4462009-04-04 07:22:01 +00001918 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001919 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 ID.Kind = ValID::t_APSInt;
1922 break;
1923 case lltok::APFloat:
1924 ID.APFloatVal = Lex.getAPFloatVal();
1925 ID.Kind = ValID::t_APFloat;
1926 break;
1927 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001928 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 ID.Kind = ValID::t_Constant;
1930 break;
1931 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001932 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 ID.Kind = ValID::t_Constant;
1934 break;
1935 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1936 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1937 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938
Chris Lattnerdf986172009-01-02 07:01:27 +00001939 case lltok::lbrace: {
1940 // ValID ::= '{' ConstVector '}'
1941 Lex.Lex();
1942 SmallVector<Constant*, 16> Elts;
1943 if (ParseGlobalValueVector(Elts) ||
1944 ParseToken(lltok::rbrace, "expected end of struct constant"))
1945 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001946
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001947 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1948 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00001949 ID.Kind = ValID::t_Constant;
1950 return false;
1951 }
1952 case lltok::less: {
1953 // ValID ::= '<' ConstVector '>' --> Vector.
1954 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1955 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001956 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957
Chris Lattnerdf986172009-01-02 07:01:27 +00001958 SmallVector<Constant*, 16> Elts;
1959 LocTy FirstEltLoc = Lex.getLoc();
1960 if (ParseGlobalValueVector(Elts) ||
1961 (isPackedStruct &&
1962 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1963 ParseToken(lltok::greater, "expected end of constant"))
1964 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001965
Chris Lattnerdf986172009-01-02 07:01:27 +00001966 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00001967 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001968 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00001969 ID.Kind = ValID::t_Constant;
1970 return false;
1971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001972
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 if (Elts.empty())
1974 return Error(ID.Loc, "constant vector must not be empty");
1975
1976 if (!Elts[0]->getType()->isInteger() &&
1977 !Elts[0]->getType()->isFloatingPoint())
1978 return Error(FirstEltLoc,
1979 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001980
Chris Lattnerdf986172009-01-02 07:01:27 +00001981 // Verify that all the vector elements have the same type.
1982 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1983 if (Elts[i]->getType() != Elts[0]->getType())
1984 return Error(FirstEltLoc,
1985 "vector element #" + utostr(i) +
1986 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001987
Owen Andersonaf7ec972009-07-28 21:19:26 +00001988 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00001989 ID.Kind = ValID::t_Constant;
1990 return false;
1991 }
1992 case lltok::lsquare: { // Array Constant
1993 Lex.Lex();
1994 SmallVector<Constant*, 16> Elts;
1995 LocTy FirstEltLoc = Lex.getLoc();
1996 if (ParseGlobalValueVector(Elts) ||
1997 ParseToken(lltok::rsquare, "expected end of array constant"))
1998 return true;
1999
2000 // Handle empty element.
2001 if (Elts.empty()) {
2002 // Use undef instead of an array because it's inconvenient to determine
2003 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002004 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002005 return false;
2006 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002009 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002010 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002011
Owen Andersondebcb012009-07-29 22:17:13 +00002012 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002013
Chris Lattnerdf986172009-01-02 07:01:27 +00002014 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002015 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 if (Elts[i]->getType() != Elts[0]->getType())
2017 return Error(FirstEltLoc,
2018 "array element #" + utostr(i) +
2019 " is not of type '" +Elts[0]->getType()->getDescription());
2020 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002021
Owen Anderson1fd70962009-07-28 18:32:17 +00002022 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 ID.Kind = ValID::t_Constant;
2024 return false;
2025 }
2026 case lltok::kw_c: // c "foo"
2027 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002028 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002029 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2030 ID.Kind = ValID::t_Constant;
2031 return false;
2032
2033 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002034 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2035 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 Lex.Lex();
2037 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002038 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002039 ParseStringConstant(ID.StrVal) ||
2040 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002041 ParseToken(lltok::StringConstant, "expected constraint string"))
2042 return true;
2043 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002044 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002045 ID.Kind = ValID::t_InlineAsm;
2046 return false;
2047 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002048
Chris Lattner09d9ef42009-10-28 03:39:23 +00002049 case lltok::kw_blockaddress: {
2050 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2051 Lex.Lex();
2052
2053 ValID Fn, Label;
2054 LocTy FnLoc, LabelLoc;
2055
2056 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2057 ParseValID(Fn) ||
2058 ParseToken(lltok::comma, "expected comma in block address expression")||
2059 ParseValID(Label) ||
2060 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2061 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002062
Chris Lattner09d9ef42009-10-28 03:39:23 +00002063 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2064 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002065 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002066 return Error(Label.Loc, "expected basic block name in blockaddress");
2067
2068 // Make a global variable as a placeholder for this reference.
2069 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2070 false, GlobalValue::InternalLinkage,
2071 0, "");
2072 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2073 ID.ConstantVal = FwdRef;
2074 ID.Kind = ValID::t_Constant;
2075 return false;
2076 }
2077
Chris Lattnerdf986172009-01-02 07:01:27 +00002078 case lltok::kw_trunc:
2079 case lltok::kw_zext:
2080 case lltok::kw_sext:
2081 case lltok::kw_fptrunc:
2082 case lltok::kw_fpext:
2083 case lltok::kw_bitcast:
2084 case lltok::kw_uitofp:
2085 case lltok::kw_sitofp:
2086 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002087 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002090 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002091 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 Constant *SrcVal;
2093 Lex.Lex();
2094 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2095 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002096 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002097 ParseType(DestTy) ||
2098 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2099 return true;
2100 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2101 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2102 SrcVal->getType()->getDescription() + "' to '" +
2103 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002105 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002106 ID.Kind = ValID::t_Constant;
2107 return false;
2108 }
2109 case lltok::kw_extractvalue: {
2110 Lex.Lex();
2111 Constant *Val;
2112 SmallVector<unsigned, 4> Indices;
2113 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2114 ParseGlobalTypeAndValue(Val) ||
2115 ParseIndexList(Indices) ||
2116 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2117 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002118 if (Lex.getKind() == lltok::NamedOrCustomMD)
2119 if (ParseOptionalCustomMetadata()) return true;
2120
Chris Lattnerdf986172009-01-02 07:01:27 +00002121 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2122 return Error(ID.Loc, "extractvalue operand must be array or struct");
2123 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2124 Indices.end()))
2125 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002126 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002127 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 ID.Kind = ValID::t_Constant;
2129 return false;
2130 }
2131 case lltok::kw_insertvalue: {
2132 Lex.Lex();
2133 Constant *Val0, *Val1;
2134 SmallVector<unsigned, 4> Indices;
2135 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2136 ParseGlobalTypeAndValue(Val0) ||
2137 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2138 ParseGlobalTypeAndValue(Val1) ||
2139 ParseIndexList(Indices) ||
2140 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2141 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002142 if (Lex.getKind() == lltok::NamedOrCustomMD)
2143 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002144 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2145 return Error(ID.Loc, "extractvalue operand must be array or struct");
2146 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2147 Indices.end()))
2148 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002149 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002150 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 ID.Kind = ValID::t_Constant;
2152 return false;
2153 }
2154 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002155 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 unsigned PredVal, Opc = Lex.getUIntVal();
2157 Constant *Val0, *Val1;
2158 Lex.Lex();
2159 if (ParseCmpPredicate(PredVal, Opc) ||
2160 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2161 ParseGlobalTypeAndValue(Val0) ||
2162 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2163 ParseGlobalTypeAndValue(Val1) ||
2164 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2165 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 if (Val0->getType() != Val1->getType())
2168 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002169
Chris Lattnerdf986172009-01-02 07:01:27 +00002170 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002171
Chris Lattnerdf986172009-01-02 07:01:27 +00002172 if (Opc == Instruction::FCmp) {
2173 if (!Val0->getType()->isFPOrFPVector())
2174 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002175 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002176 } else {
2177 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 if (!Val0->getType()->isIntOrIntVector() &&
2179 !isa<PointerType>(Val0->getType()))
2180 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002181 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002182 }
2183 ID.Kind = ValID::t_Constant;
2184 return false;
2185 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 // Binary Operators.
2188 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002189 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002190 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002191 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002193 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 case lltok::kw_udiv:
2195 case lltok::kw_sdiv:
2196 case lltok::kw_fdiv:
2197 case lltok::kw_urem:
2198 case lltok::kw_srem:
2199 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002200 bool NUW = false;
2201 bool NSW = false;
2202 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 unsigned Opc = Lex.getUIntVal();
2204 Constant *Val0, *Val1;
2205 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002206 LocTy ModifierLoc = Lex.getLoc();
2207 if (Opc == Instruction::Add ||
2208 Opc == Instruction::Sub ||
2209 Opc == Instruction::Mul) {
2210 if (EatIfPresent(lltok::kw_nuw))
2211 NUW = true;
2212 if (EatIfPresent(lltok::kw_nsw)) {
2213 NSW = true;
2214 if (EatIfPresent(lltok::kw_nuw))
2215 NUW = true;
2216 }
2217 } else if (Opc == Instruction::SDiv) {
2218 if (EatIfPresent(lltok::kw_exact))
2219 Exact = true;
2220 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002221 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2222 ParseGlobalTypeAndValue(Val0) ||
2223 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2224 ParseGlobalTypeAndValue(Val1) ||
2225 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2226 return true;
2227 if (Val0->getType() != Val1->getType())
2228 return Error(ID.Loc, "operands of constexpr must have same type");
Dan Gohman59858cf2009-07-27 16:11:46 +00002229 if (!Val0->getType()->isIntOrIntVector()) {
2230 if (NUW)
2231 return Error(ModifierLoc, "nuw only applies to integer operations");
2232 if (NSW)
2233 return Error(ModifierLoc, "nsw only applies to integer operations");
2234 }
2235 // API compatibility: Accept either integer or floating-point types with
2236 // add, sub, and mul.
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 if (!Val0->getType()->isIntOrIntVector() &&
2238 !Val0->getType()->isFPOrFPVector())
2239 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002240 unsigned Flags = 0;
2241 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2242 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2243 if (Exact) Flags |= SDivOperator::IsExact;
2244 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002245 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002246 ID.Kind = ValID::t_Constant;
2247 return false;
2248 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249
Chris Lattnerdf986172009-01-02 07:01:27 +00002250 // Logical Operations
2251 case lltok::kw_shl:
2252 case lltok::kw_lshr:
2253 case lltok::kw_ashr:
2254 case lltok::kw_and:
2255 case lltok::kw_or:
2256 case lltok::kw_xor: {
2257 unsigned Opc = Lex.getUIntVal();
2258 Constant *Val0, *Val1;
2259 Lex.Lex();
2260 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2261 ParseGlobalTypeAndValue(Val0) ||
2262 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2263 ParseGlobalTypeAndValue(Val1) ||
2264 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2265 return true;
2266 if (Val0->getType() != Val1->getType())
2267 return Error(ID.Loc, "operands of constexpr must have same type");
2268 if (!Val0->getType()->isIntOrIntVector())
2269 return Error(ID.Loc,
2270 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002271 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002272 ID.Kind = ValID::t_Constant;
2273 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002274 }
2275
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 case lltok::kw_getelementptr:
2277 case lltok::kw_shufflevector:
2278 case lltok::kw_insertelement:
2279 case lltok::kw_extractelement:
2280 case lltok::kw_select: {
2281 unsigned Opc = Lex.getUIntVal();
2282 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002283 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002284 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002285 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002286 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2288 ParseGlobalValueVector(Elts) ||
2289 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2290 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002291
Chris Lattnerdf986172009-01-02 07:01:27 +00002292 if (Opc == Instruction::GetElementPtr) {
2293 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2294 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002295
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002297 (Value**)(Elts.data() + 1),
2298 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002300 ID.ConstantVal = InBounds ?
2301 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2302 Elts.data() + 1,
2303 Elts.size() - 1) :
2304 ConstantExpr::getGetElementPtr(Elts[0],
2305 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 } else if (Opc == Instruction::Select) {
2307 if (Elts.size() != 3)
2308 return Error(ID.Loc, "expected three operands to select");
2309 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2310 Elts[2]))
2311 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002312 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002313 } else if (Opc == Instruction::ShuffleVector) {
2314 if (Elts.size() != 3)
2315 return Error(ID.Loc, "expected three operands to shufflevector");
2316 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2317 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002318 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002319 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002320 } else if (Opc == Instruction::ExtractElement) {
2321 if (Elts.size() != 2)
2322 return Error(ID.Loc, "expected two operands to extractelement");
2323 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2324 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002325 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002326 } else {
2327 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2328 if (Elts.size() != 3)
2329 return Error(ID.Loc, "expected three operands to insertelement");
2330 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2331 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002332 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002333 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002334 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002335
Chris Lattnerdf986172009-01-02 07:01:27 +00002336 ID.Kind = ValID::t_Constant;
2337 return false;
2338 }
2339 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002340
Chris Lattnerdf986172009-01-02 07:01:27 +00002341 Lex.Lex();
2342 return false;
2343}
2344
2345/// ParseGlobalValue - Parse a global value with the specified type.
2346bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2347 V = 0;
2348 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002349 return ParseValID(ID) ||
2350 ConvertGlobalValIDToValue(Ty, ID, V);
Chris Lattnerdf986172009-01-02 07:01:27 +00002351}
2352
2353/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2354/// constant.
2355bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2356 Constant *&V) {
2357 if (isa<FunctionType>(Ty))
2358 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002359
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361 default: llvm_unreachable("Unknown ValID!");
Chris Lattner287881d2009-12-30 02:11:14 +00002362 case ValID::t_MDNode:
2363 case ValID::t_MDString:
Devang Patele54abc92009-07-22 17:43:22 +00002364 return Error(ID.Loc, "invalid use of metadata");
Chris Lattnerdf986172009-01-02 07:01:27 +00002365 case ValID::t_LocalID:
2366 case ValID::t_LocalName:
2367 return Error(ID.Loc, "invalid use of function-local name");
2368 case ValID::t_InlineAsm:
2369 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2370 case ValID::t_GlobalName:
2371 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2372 return V == 0;
2373 case ValID::t_GlobalID:
2374 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2375 return V == 0;
2376 case ValID::t_APSInt:
2377 if (!isa<IntegerType>(Ty))
2378 return Error(ID.Loc, "integer constant must have integer type");
2379 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002380 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002381 return false;
2382 case ValID::t_APFloat:
2383 if (!Ty->isFloatingPoint() ||
2384 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2385 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002386
Chris Lattnerdf986172009-01-02 07:01:27 +00002387 // The lexer has no type info, so builds all float and double FP constants
2388 // as double. Fix this here. Long double does not need this.
2389 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002390 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002391 bool Ignored;
2392 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2393 &Ignored);
2394 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002395 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396
Chris Lattner959873d2009-01-05 18:24:23 +00002397 if (V->getType() != Ty)
2398 return Error(ID.Loc, "floating point constant does not have type '" +
2399 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002400
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 return false;
2402 case ValID::t_Null:
2403 if (!isa<PointerType>(Ty))
2404 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002405 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 return false;
2407 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002408 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002409 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Chris Lattner0b616352009-01-05 18:12:21 +00002410 !isa<OpaqueType>(Ty))
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002411 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002412 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002413 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002414 case ValID::t_EmptyArray:
2415 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2416 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002417 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002418 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002419 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002420 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002421 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002422 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002423 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002424 return false;
2425 case ValID::t_Constant:
2426 if (ID.ConstantVal->getType() != Ty)
2427 return Error(ID.Loc, "constant expression type mismatch");
2428 V = ID.ConstantVal;
2429 return false;
2430 }
2431}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002432
Chris Lattnerdf986172009-01-02 07:01:27 +00002433bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002434 PATypeHolder Type(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002435 return ParseType(Type) ||
2436 ParseGlobalValue(Type, V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002437}
Chris Lattnerdf986172009-01-02 07:01:27 +00002438
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002439/// ParseGlobalValueVector
2440/// ::= /*empty*/
2441/// ::= TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00002442bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2443 // Empty list.
2444 if (Lex.getKind() == lltok::rbrace ||
2445 Lex.getKind() == lltok::rsquare ||
2446 Lex.getKind() == lltok::greater ||
2447 Lex.getKind() == lltok::rparen)
2448 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattnerdf986172009-01-02 07:01:27 +00002450 Constant *C;
2451 if (ParseGlobalTypeAndValue(C)) return true;
2452 Elts.push_back(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002453
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002454 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002455 if (ParseGlobalTypeAndValue(C)) return true;
2456 Elts.push_back(C);
2457 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002458
Chris Lattnerdf986172009-01-02 07:01:27 +00002459 return false;
2460}
2461
2462
2463//===----------------------------------------------------------------------===//
2464// Function Parsing.
2465//===----------------------------------------------------------------------===//
2466
2467bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2468 PerFunctionState &PFS) {
Chris Lattner287881d2009-12-30 02:11:14 +00002469 switch (ID.Kind) {
2470 case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break;
2471 case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break;
2472 case ValID::t_MDNode: V = ID.MDNodeVal; break;
Chris Lattner860775c2009-12-30 04:13:37 +00002473 case ValID::t_MDString: V = ID.MDStringVal; break;
Chris Lattner287881d2009-12-30 02:11:14 +00002474 case ValID::t_InlineAsm: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002475 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerc49363b2009-12-30 02:20:07 +00002476 const FunctionType *FTy =
2477 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002478 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2479 return Error(ID.Loc, "invalid type for inline asm constraint string");
Dale Johannesen43602982009-10-13 20:46:56 +00002480 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002481 return false;
Chris Lattner287881d2009-12-30 02:11:14 +00002482 }
2483 default: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002484 Constant *C;
2485 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2486 V = C;
2487 return false;
2488 }
Chris Lattner287881d2009-12-30 02:11:14 +00002489 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002490
2491 return V == 0;
2492}
2493
2494bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2495 V = 0;
2496 ValID ID;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002497 return ParseValID(ID) ||
2498 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002499}
2500
2501bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002502 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002503 return ParseType(T) ||
2504 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002505}
2506
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002507bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2508 PerFunctionState &PFS) {
2509 Value *V;
2510 Loc = Lex.getLoc();
2511 if (ParseTypeAndValue(V, PFS)) return true;
2512 if (!isa<BasicBlock>(V))
2513 return Error(Loc, "expected a basic block");
2514 BB = cast<BasicBlock>(V);
2515 return false;
2516}
2517
2518
Chris Lattnerdf986172009-01-02 07:01:27 +00002519/// FunctionHeader
2520/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2521/// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2522/// OptionalAlign OptGC
2523bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2524 // Parse the linkage.
2525 LocTy LinkageLoc = Lex.getLoc();
2526 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002527
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002528 unsigned Visibility, RetAttrs;
2529 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002530 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002531 LocTy RetTypeLoc = Lex.getLoc();
2532 if (ParseOptionalLinkage(Linkage) ||
2533 ParseOptionalVisibility(Visibility) ||
2534 ParseOptionalCallingConv(CC) ||
2535 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002536 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 return true;
2538
2539 // Verify that the linkage is ok.
2540 switch ((GlobalValue::LinkageTypes)Linkage) {
2541 case GlobalValue::ExternalLinkage:
2542 break; // always ok.
2543 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002544 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002545 if (isDefine)
2546 return Error(LinkageLoc, "invalid linkage for function definition");
2547 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002548 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002549 case GlobalValue::LinkerPrivateLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002550 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002551 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002552 case GlobalValue::LinkOnceAnyLinkage:
2553 case GlobalValue::LinkOnceODRLinkage:
2554 case GlobalValue::WeakAnyLinkage:
2555 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002556 case GlobalValue::DLLExportLinkage:
2557 if (!isDefine)
2558 return Error(LinkageLoc, "invalid linkage for function declaration");
2559 break;
2560 case GlobalValue::AppendingLinkage:
2561 case GlobalValue::GhostLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002562 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 return Error(LinkageLoc, "invalid function linkage type");
2564 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002565
Chris Lattner99bb3152009-01-05 08:00:30 +00002566 if (!FunctionType::isValidReturnType(RetType) ||
2567 isa<OpaqueType>(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002568 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002569
Chris Lattnerdf986172009-01-02 07:01:27 +00002570 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002571
2572 std::string FunctionName;
2573 if (Lex.getKind() == lltok::GlobalVar) {
2574 FunctionName = Lex.getStrVal();
2575 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2576 unsigned NameID = Lex.getUIntVal();
2577
2578 if (NameID != NumberedVals.size())
2579 return TokError("function expected to be numbered '%" +
2580 utostr(NumberedVals.size()) + "'");
2581 } else {
2582 return TokError("expected function name");
2583 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002585 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002586
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002587 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Chris Lattnerdf986172009-01-02 07:01:27 +00002590 std::vector<ArgInfo> ArgList;
2591 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002592 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002595 std::string GC;
2596
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002597 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002598 ParseOptionalAttrs(FuncAttrs, 2) ||
2599 (EatIfPresent(lltok::kw_section) &&
2600 ParseStringConstant(Section)) ||
2601 ParseOptionalAlignment(Alignment) ||
2602 (EatIfPresent(lltok::kw_gc) &&
2603 ParseStringConstant(GC)))
2604 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002605
2606 // If the alignment was parsed as an attribute, move to the alignment field.
2607 if (FuncAttrs & Attribute::Alignment) {
2608 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2609 FuncAttrs &= ~Attribute::Alignment;
2610 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611
Chris Lattnerdf986172009-01-02 07:01:27 +00002612 // Okay, if we got here, the function is syntactically valid. Convert types
2613 // and do semantic checks.
2614 std::vector<const Type*> ParamTypeList;
2615 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002616 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002617 // attributes.
2618 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2619 if (FuncAttrs & ObsoleteFuncAttrs) {
2620 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2621 FuncAttrs &= ~ObsoleteFuncAttrs;
2622 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002623
Chris Lattnerdf986172009-01-02 07:01:27 +00002624 if (RetAttrs != Attribute::None)
2625 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2628 ParamTypeList.push_back(ArgList[i].Type);
2629 if (ArgList[i].Attrs != Attribute::None)
2630 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2631 }
2632
2633 if (FuncAttrs != Attribute::None)
2634 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2635
2636 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Chris Lattnera9a9e072009-03-09 04:49:14 +00002638 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00002639 RetType != Type::getVoidTy(Context))
Daniel Dunbara279bc32009-09-20 02:20:51 +00002640 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2641
Owen Andersonfba933c2009-07-01 23:57:11 +00002642 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002643 FunctionType::get(RetType, ParamTypeList, isVarArg);
2644 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002645
2646 Fn = 0;
2647 if (!FunctionName.empty()) {
2648 // If this was a definition of a forward reference, remove the definition
2649 // from the forward reference table and fill in the forward ref.
2650 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2651 ForwardRefVals.find(FunctionName);
2652 if (FRVI != ForwardRefVals.end()) {
2653 Fn = M->getFunction(FunctionName);
2654 ForwardRefVals.erase(FRVI);
2655 } else if ((Fn = M->getFunction(FunctionName))) {
2656 // If this function already exists in the symbol table, then it is
2657 // multiply defined. We accept a few cases for old backwards compat.
2658 // FIXME: Remove this stuff for LLVM 3.0.
2659 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2660 (!Fn->isDeclaration() && isDefine)) {
2661 // If the redefinition has different type or different attributes,
2662 // reject it. If both have bodies, reject it.
2663 return Error(NameLoc, "invalid redefinition of function '" +
2664 FunctionName + "'");
2665 } else if (Fn->isDeclaration()) {
2666 // Make sure to strip off any argument names so we can't get conflicts.
2667 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2668 AI != AE; ++AI)
2669 AI->setName("");
2670 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002671 } else if (M->getNamedValue(FunctionName)) {
2672 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002673 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002674
Dan Gohman41905542009-08-29 23:37:49 +00002675 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 // If this is a definition of a forward referenced function, make sure the
2677 // types agree.
2678 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2679 = ForwardRefValIDs.find(NumberedVals.size());
2680 if (I != ForwardRefValIDs.end()) {
2681 Fn = cast<Function>(I->second.first);
2682 if (Fn->getType() != PFT)
2683 return Error(NameLoc, "type of definition and forward reference of '@" +
2684 utostr(NumberedVals.size()) +"' disagree");
2685 ForwardRefValIDs.erase(I);
2686 }
2687 }
2688
2689 if (Fn == 0)
2690 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2691 else // Move the forward-reference to the correct spot in the module.
2692 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2693
2694 if (FunctionName.empty())
2695 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002696
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2698 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2699 Fn->setCallingConv(CC);
2700 Fn->setAttributes(PAL);
2701 Fn->setAlignment(Alignment);
2702 Fn->setSection(Section);
2703 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002704
Chris Lattnerdf986172009-01-02 07:01:27 +00002705 // Add all of the arguments we parsed to the function.
2706 Function::arg_iterator ArgIt = Fn->arg_begin();
2707 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002708 // If we run out of arguments in the Function prototype, exit early.
2709 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2710 if (ArgIt == Fn->arg_end()) break;
2711
Chris Lattnerdf986172009-01-02 07:01:27 +00002712 // If the argument has a name, insert it into the argument symbol table.
2713 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002714
Chris Lattnerdf986172009-01-02 07:01:27 +00002715 // Set the name, if it conflicted, it will be auto-renamed.
2716 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 if (ArgIt->getNameStr() != ArgList[i].Name)
2719 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2720 ArgList[i].Name + "'");
2721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002722
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 return false;
2724}
2725
2726
2727/// ParseFunctionBody
2728/// ::= '{' BasicBlock+ '}'
2729/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2730///
2731bool LLParser::ParseFunctionBody(Function &Fn) {
2732 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2733 return TokError("expected '{' in function body");
2734 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002735
Chris Lattner09d9ef42009-10-28 03:39:23 +00002736 int FunctionNumber = -1;
2737 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2738
2739 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Chris Lattnerdf986172009-01-02 07:01:27 +00002741 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2742 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Chris Lattnerdf986172009-01-02 07:01:27 +00002744 // Eat the }.
2745 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002746
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002748 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002749}
2750
2751/// ParseBasicBlock
2752/// ::= LabelStr? Instruction*
2753bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2754 // If this basic block starts out with a name, remember it.
2755 std::string Name;
2756 LocTy NameLoc = Lex.getLoc();
2757 if (Lex.getKind() == lltok::LabelStr) {
2758 Name = Lex.getStrVal();
2759 Lex.Lex();
2760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002761
Chris Lattnerdf986172009-01-02 07:01:27 +00002762 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2763 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 // Parse the instructions in this block until we get a terminator.
2768 Instruction *Inst;
2769 do {
2770 // This instruction may have three possibilities for a name: a) none
2771 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2772 LocTy NameLoc = Lex.getLoc();
2773 int NameID = -1;
2774 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Chris Lattnerdf986172009-01-02 07:01:27 +00002776 if (Lex.getKind() == lltok::LocalVarID) {
2777 NameID = Lex.getUIntVal();
2778 Lex.Lex();
2779 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2780 return true;
2781 } else if (Lex.getKind() == lltok::LocalVar ||
2782 // FIXME: REMOVE IN LLVM 3.0
2783 Lex.getKind() == lltok::StringConstant) {
2784 NameStr = Lex.getStrVal();
2785 Lex.Lex();
2786 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2787 return true;
2788 }
Devang Patelf633a062009-09-17 23:04:48 +00002789
Chris Lattnerdf986172009-01-02 07:01:27 +00002790 if (ParseInstruction(Inst, BB, PFS)) return true;
Devang Patelf633a062009-09-17 23:04:48 +00002791 if (EatIfPresent(lltok::comma))
Devang Patel0475c912009-09-29 00:01:14 +00002792 ParseOptionalCustomMetadata();
Devang Patelf633a062009-09-17 23:04:48 +00002793
2794 // Set metadata attached with this instruction.
Devang Patela2148402009-09-28 21:14:55 +00002795 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
Daniel Dunbara279bc32009-09-20 02:20:51 +00002796 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
Chris Lattner3990b122009-12-28 23:41:32 +00002797 Inst->setMetadata(MDI->first, MDI->second);
Devang Patelf633a062009-09-17 23:04:48 +00002798 MDsOnInst.clear();
2799
Chris Lattnerdf986172009-01-02 07:01:27 +00002800 BB->getInstList().push_back(Inst);
2801
2802 // Set the name on the instruction.
2803 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2804 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Chris Lattnerdf986172009-01-02 07:01:27 +00002806 return false;
2807}
2808
2809//===----------------------------------------------------------------------===//
2810// Instruction Parsing.
2811//===----------------------------------------------------------------------===//
2812
2813/// ParseInstruction - Parse one of the many different instructions.
2814///
2815bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2816 PerFunctionState &PFS) {
2817 lltok::Kind Token = Lex.getKind();
2818 if (Token == lltok::Eof)
2819 return TokError("found end of file when expecting more instructions");
2820 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002821 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002822 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattnerdf986172009-01-02 07:01:27 +00002824 switch (Token) {
2825 default: return Error(Loc, "expected instruction opcode");
2826 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002827 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2828 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2830 case lltok::kw_br: return ParseBr(Inst, PFS);
2831 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002832 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2834 // Binary Operators.
2835 case lltok::kw_add:
2836 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00002837 case lltok::kw_mul: {
2838 bool NUW = false;
2839 bool NSW = false;
2840 LocTy ModifierLoc = Lex.getLoc();
2841 if (EatIfPresent(lltok::kw_nuw))
2842 NUW = true;
2843 if (EatIfPresent(lltok::kw_nsw)) {
2844 NSW = true;
2845 if (EatIfPresent(lltok::kw_nuw))
2846 NUW = true;
2847 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002848 // API compatibility: Accept either integer or floating-point types.
Dan Gohman59858cf2009-07-27 16:11:46 +00002849 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2850 if (!Result) {
2851 if (!Inst->getType()->isIntOrIntVector()) {
2852 if (NUW)
2853 return Error(ModifierLoc, "nuw only applies to integer operations");
2854 if (NSW)
2855 return Error(ModifierLoc, "nsw only applies to integer operations");
2856 }
2857 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002858 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002859 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002860 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002861 }
2862 return Result;
2863 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002864 case lltok::kw_fadd:
2865 case lltok::kw_fsub:
2866 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2867
Dan Gohman59858cf2009-07-27 16:11:46 +00002868 case lltok::kw_sdiv: {
2869 bool Exact = false;
2870 if (EatIfPresent(lltok::kw_exact))
2871 Exact = true;
2872 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2873 if (!Result)
2874 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002875 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00002876 return Result;
2877 }
2878
Chris Lattnerdf986172009-01-02 07:01:27 +00002879 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002881 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002882 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002883 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002884 case lltok::kw_shl:
2885 case lltok::kw_lshr:
2886 case lltok::kw_ashr:
2887 case lltok::kw_and:
2888 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002889 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002890 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002891 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002892 // Casts.
2893 case lltok::kw_trunc:
2894 case lltok::kw_zext:
2895 case lltok::kw_sext:
2896 case lltok::kw_fptrunc:
2897 case lltok::kw_fpext:
2898 case lltok::kw_bitcast:
2899 case lltok::kw_uitofp:
2900 case lltok::kw_sitofp:
2901 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002902 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002903 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002904 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002905 // Other.
2906 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002907 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002908 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2909 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2910 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2911 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2912 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2913 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2914 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002915 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2916 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00002917 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2919 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2920 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002921 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002922 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002923 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002924 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002925 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002926 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002927 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2928 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2929 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2930 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2931 }
2932}
2933
2934/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2935bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002936 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002937 switch (Lex.getKind()) {
2938 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2939 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2940 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2941 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2942 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2943 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2944 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2945 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2946 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2947 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2948 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2949 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2950 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2951 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2952 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2953 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2954 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2955 }
2956 } else {
2957 switch (Lex.getKind()) {
2958 default: TokError("expected icmp predicate (e.g. 'eq')");
2959 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2960 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2961 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2962 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2963 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2964 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2965 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2966 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2967 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2968 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2969 }
2970 }
2971 Lex.Lex();
2972 return false;
2973}
2974
2975//===----------------------------------------------------------------------===//
2976// Terminator Instructions.
2977//===----------------------------------------------------------------------===//
2978
2979/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00002980/// ::= 'ret' void (',' !dbg, !1)*
2981/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
2982/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00002983/// [[obsolete: LLVM 3.0]]
Chris Lattnerdf986172009-01-02 07:01:27 +00002984bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2985 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002986 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00002987 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002988
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002989 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002990 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 return false;
2992 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002993
Chris Lattnerdf986172009-01-02 07:01:27 +00002994 Value *RV;
2995 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002996
Devang Patelf633a062009-09-17 23:04:48 +00002997 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00002998 // Parse optional custom metadata, e.g. !dbg
2999 if (Lex.getKind() == lltok::NamedOrCustomMD) {
3000 if (ParseOptionalCustomMetadata()) return true;
Devang Patelf633a062009-09-17 23:04:48 +00003001 } else {
3002 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003003 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3004 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003005 SmallVector<Value*, 8> RVs;
3006 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003007
Devang Patelf633a062009-09-17 23:04:48 +00003008 do {
Devang Patel0475c912009-09-29 00:01:14 +00003009 // If optional custom metadata, e.g. !dbg is seen then this is the
3010 // end of MRV.
3011 if (Lex.getKind() == lltok::NamedOrCustomMD)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003012 break;
3013 if (ParseTypeAndValue(RV, PFS)) return true;
3014 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003015 } while (EatIfPresent(lltok::comma));
3016
3017 RV = UndefValue::get(PFS.getFunction().getReturnType());
3018 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003019 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3020 BB->getInstList().push_back(I);
3021 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003022 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003023 }
3024 }
Devang Patelf633a062009-09-17 23:04:48 +00003025
Owen Anderson1d0be152009-08-13 21:58:54 +00003026 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerdf986172009-01-02 07:01:27 +00003027 return false;
3028}
3029
3030
3031/// ParseBr
3032/// ::= 'br' TypeAndValue
3033/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3034bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3035 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003036 Value *Op0;
3037 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003038 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003039
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3041 Inst = BranchInst::Create(BB);
3042 return false;
3043 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003044
Owen Anderson1d0be152009-08-13 21:58:54 +00003045 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003046 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003047
Chris Lattnerdf986172009-01-02 07:01:27 +00003048 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003049 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003050 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003051 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003052 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003053
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003054 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003055 return false;
3056}
3057
3058/// ParseSwitch
3059/// Instruction
3060/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3061/// JumpTable
3062/// ::= (TypeAndValue ',' TypeAndValue)*
3063bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3064 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003065 Value *Cond;
3066 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3068 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003069 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003070 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3071 return true;
3072
3073 if (!isa<IntegerType>(Cond->getType()))
3074 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003075
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 // Parse the jump table pairs.
3077 SmallPtrSet<Value*, 32> SeenCases;
3078 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3079 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003080 Value *Constant;
3081 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003082
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3084 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003085 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003087
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 if (!SeenCases.insert(Constant))
3089 return Error(CondLoc, "duplicate case value in switch");
3090 if (!isa<ConstantInt>(Constant))
3091 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003092
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003093 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003097
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003098 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3100 SI->addCase(Table[i].first, Table[i].second);
3101 Inst = SI;
3102 return false;
3103}
3104
Chris Lattnerab21db72009-10-28 00:19:10 +00003105/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003106/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003107/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3108bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003109 LocTy AddrLoc;
3110 Value *Address;
3111 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003112 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3113 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003114 return true;
3115
3116 if (!isa<PointerType>(Address->getType()))
Chris Lattnerab21db72009-10-28 00:19:10 +00003117 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003118
3119 // Parse the destination list.
3120 SmallVector<BasicBlock*, 16> DestList;
3121
3122 if (Lex.getKind() != lltok::rsquare) {
3123 BasicBlock *DestBB;
3124 if (ParseTypeAndBasicBlock(DestBB, PFS))
3125 return true;
3126 DestList.push_back(DestBB);
3127
3128 while (EatIfPresent(lltok::comma)) {
3129 if (ParseTypeAndBasicBlock(DestBB, PFS))
3130 return true;
3131 DestList.push_back(DestBB);
3132 }
3133 }
3134
3135 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3136 return true;
3137
Chris Lattnerab21db72009-10-28 00:19:10 +00003138 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003139 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3140 IBI->addDestination(DestList[i]);
3141 Inst = IBI;
3142 return false;
3143}
3144
3145
Chris Lattnerdf986172009-01-02 07:01:27 +00003146/// ParseInvoke
3147/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3148/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3149bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3150 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003151 unsigned RetAttrs, FnAttrs;
3152 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003153 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003154 LocTy RetTypeLoc;
3155 ValID CalleeID;
3156 SmallVector<ParamInfo, 16> ArgList;
3157
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003158 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003159 if (ParseOptionalCallingConv(CC) ||
3160 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003161 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003162 ParseValID(CalleeID) ||
3163 ParseParameterList(ArgList, PFS) ||
3164 ParseOptionalAttrs(FnAttrs, 2) ||
3165 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003166 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003167 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003168 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003169 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003170
Chris Lattnerdf986172009-01-02 07:01:27 +00003171 // If RetType is a non-function pointer type, then this is the short syntax
3172 // for the call, which means that RetType is just the return type. Infer the
3173 // rest of the function argument types from the arguments that are present.
3174 const PointerType *PFTy = 0;
3175 const FunctionType *Ty = 0;
3176 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3177 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3178 // Pull out the types of all of the arguments...
3179 std::vector<const Type*> ParamTypes;
3180 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3181 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003182
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 if (!FunctionType::isValidReturnType(RetType))
3184 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003185
Owen Andersondebcb012009-07-29 22:17:13 +00003186 Ty = FunctionType::get(RetType, ParamTypes, false);
3187 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003188 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003189
Chris Lattnerdf986172009-01-02 07:01:27 +00003190 // Look up the callee.
3191 Value *Callee;
3192 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003193
Chris Lattnerdf986172009-01-02 07:01:27 +00003194 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3195 // function attributes.
3196 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3197 if (FnAttrs & ObsoleteFuncAttrs) {
3198 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3199 FnAttrs &= ~ObsoleteFuncAttrs;
3200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201
Chris Lattnerdf986172009-01-02 07:01:27 +00003202 // Set up the Attributes for the function.
3203 SmallVector<AttributeWithIndex, 8> Attrs;
3204 if (RetAttrs != Attribute::None)
3205 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003206
Chris Lattnerdf986172009-01-02 07:01:27 +00003207 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003208
Chris Lattnerdf986172009-01-02 07:01:27 +00003209 // Loop through FunctionType's arguments and ensure they are specified
3210 // correctly. Also, gather any parameter attributes.
3211 FunctionType::param_iterator I = Ty->param_begin();
3212 FunctionType::param_iterator E = Ty->param_end();
3213 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3214 const Type *ExpectedTy = 0;
3215 if (I != E) {
3216 ExpectedTy = *I++;
3217 } else if (!Ty->isVarArg()) {
3218 return Error(ArgList[i].Loc, "too many arguments specified");
3219 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003220
Chris Lattnerdf986172009-01-02 07:01:27 +00003221 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3222 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3223 ExpectedTy->getDescription() + "'");
3224 Args.push_back(ArgList[i].V);
3225 if (ArgList[i].Attrs != Attribute::None)
3226 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003228
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 if (I != E)
3230 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003231
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 if (FnAttrs != Attribute::None)
3233 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003234
Chris Lattnerdf986172009-01-02 07:01:27 +00003235 // Finish off the Attributes and check them
3236 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003237
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003238 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 Args.begin(), Args.end());
3240 II->setCallingConv(CC);
3241 II->setAttributes(PAL);
3242 Inst = II;
3243 return false;
3244}
3245
3246
3247
3248//===----------------------------------------------------------------------===//
3249// Binary Operators.
3250//===----------------------------------------------------------------------===//
3251
3252/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003253/// ::= ArithmeticOps TypeAndValue ',' Value
3254///
3255/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3256/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003257bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003258 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003259 LocTy Loc; Value *LHS, *RHS;
3260 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3261 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3262 ParseValue(LHS->getType(), RHS, PFS))
3263 return true;
3264
Chris Lattnere914b592009-01-05 08:24:46 +00003265 bool Valid;
3266 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003267 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003268 case 0: // int or FP.
3269 Valid = LHS->getType()->isIntOrIntVector() ||
3270 LHS->getType()->isFPOrFPVector();
3271 break;
3272 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3273 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3274 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003275
Chris Lattnere914b592009-01-05 08:24:46 +00003276 if (!Valid)
3277 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003278
Chris Lattnerdf986172009-01-02 07:01:27 +00003279 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3280 return false;
3281}
3282
3283/// ParseLogical
3284/// ::= ArithmeticOps TypeAndValue ',' Value {
3285bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3286 unsigned Opc) {
3287 LocTy Loc; Value *LHS, *RHS;
3288 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3289 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3290 ParseValue(LHS->getType(), RHS, PFS))
3291 return true;
3292
3293 if (!LHS->getType()->isIntOrIntVector())
3294 return Error(Loc,"instruction requires integer or integer vector operands");
3295
3296 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3297 return false;
3298}
3299
3300
3301/// ParseCompare
3302/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3303/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003304bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3305 unsigned Opc) {
3306 // Parse the integer/fp comparison predicate.
3307 LocTy Loc;
3308 unsigned Pred;
3309 Value *LHS, *RHS;
3310 if (ParseCmpPredicate(Pred, Opc) ||
3311 ParseTypeAndValue(LHS, Loc, PFS) ||
3312 ParseToken(lltok::comma, "expected ',' after compare value") ||
3313 ParseValue(LHS->getType(), RHS, PFS))
3314 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003315
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 if (Opc == Instruction::FCmp) {
3317 if (!LHS->getType()->isFPOrFPVector())
3318 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003319 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003320 } else {
3321 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 if (!LHS->getType()->isIntOrIntVector() &&
3323 !isa<PointerType>(LHS->getType()))
3324 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003325 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003326 }
3327 return false;
3328}
3329
3330//===----------------------------------------------------------------------===//
3331// Other Instructions.
3332//===----------------------------------------------------------------------===//
3333
3334
3335/// ParseCast
3336/// ::= CastOpc TypeAndValue 'to' Type
3337bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3338 unsigned Opc) {
3339 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003340 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 if (ParseTypeAndValue(Op, Loc, PFS) ||
3342 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3343 ParseType(DestTy))
3344 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003345
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003346 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3347 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003348 return Error(Loc, "invalid cast opcode for cast from '" +
3349 Op->getType()->getDescription() + "' to '" +
3350 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003351 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003352 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3353 return false;
3354}
3355
3356/// ParseSelect
3357/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3358bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3359 LocTy Loc;
3360 Value *Op0, *Op1, *Op2;
3361 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3362 ParseToken(lltok::comma, "expected ',' after select condition") ||
3363 ParseTypeAndValue(Op1, PFS) ||
3364 ParseToken(lltok::comma, "expected ',' after select value") ||
3365 ParseTypeAndValue(Op2, PFS))
3366 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3369 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003370
Chris Lattnerdf986172009-01-02 07:01:27 +00003371 Inst = SelectInst::Create(Op0, Op1, Op2);
3372 return false;
3373}
3374
Chris Lattner0088a5c2009-01-05 08:18:44 +00003375/// ParseVA_Arg
3376/// ::= 'va_arg' TypeAndValue ',' Type
3377bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003378 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003379 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003380 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 if (ParseTypeAndValue(Op, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003383 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003384 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003385
Chris Lattner0088a5c2009-01-05 08:18:44 +00003386 if (!EltTy->isFirstClassType())
3387 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003388
3389 Inst = new VAArgInst(Op, EltTy);
3390 return false;
3391}
3392
3393/// ParseExtractElement
3394/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3395bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3396 LocTy Loc;
3397 Value *Op0, *Op1;
3398 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3399 ParseToken(lltok::comma, "expected ',' after extract value") ||
3400 ParseTypeAndValue(Op1, PFS))
3401 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003402
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3404 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003405
Eric Christophera3500da2009-07-25 02:28:41 +00003406 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003407 return false;
3408}
3409
3410/// ParseInsertElement
3411/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3412bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3413 LocTy Loc;
3414 Value *Op0, *Op1, *Op2;
3415 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3416 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3417 ParseTypeAndValue(Op1, PFS) ||
3418 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3419 ParseTypeAndValue(Op2, PFS))
3420 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003421
Chris Lattnerdf986172009-01-02 07:01:27 +00003422 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003423 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003424
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3426 return false;
3427}
3428
3429/// ParseShuffleVector
3430/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3431bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3432 LocTy Loc;
3433 Value *Op0, *Op1, *Op2;
3434 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3435 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3436 ParseTypeAndValue(Op1, PFS) ||
3437 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3438 ParseTypeAndValue(Op2, PFS))
3439 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003440
Chris Lattnerdf986172009-01-02 07:01:27 +00003441 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3442 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003443
Chris Lattnerdf986172009-01-02 07:01:27 +00003444 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3445 return false;
3446}
3447
3448/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003449/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnerdf986172009-01-02 07:01:27 +00003450bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003451 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003452 Value *Op0, *Op1;
3453 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003454
Chris Lattnerdf986172009-01-02 07:01:27 +00003455 if (ParseType(Ty) ||
3456 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3457 ParseValue(Ty, Op0, PFS) ||
3458 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003459 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003460 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3461 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003462
Chris Lattnerdf986172009-01-02 07:01:27 +00003463 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3464 while (1) {
3465 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003466
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003467 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 break;
3469
Devang Patela43d46f2009-10-16 18:45:49 +00003470 if (Lex.getKind() == lltok::NamedOrCustomMD)
3471 break;
3472
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003473 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003474 ParseValue(Ty, Op0, PFS) ||
3475 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003476 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3478 return true;
3479 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003480
Devang Patela43d46f2009-10-16 18:45:49 +00003481 if (Lex.getKind() == lltok::NamedOrCustomMD)
3482 if (ParseOptionalCustomMetadata()) return true;
3483
Chris Lattnerdf986172009-01-02 07:01:27 +00003484 if (!Ty->isFirstClassType())
3485 return Error(TypeLoc, "phi node must have first class type");
3486
3487 PHINode *PN = PHINode::Create(Ty);
3488 PN->reserveOperandSpace(PHIVals.size());
3489 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3490 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3491 Inst = PN;
3492 return false;
3493}
3494
3495/// ParseCall
3496/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3497/// ParameterList OptionalAttrs
3498bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3499 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003500 unsigned RetAttrs, FnAttrs;
3501 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003502 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 LocTy RetTypeLoc;
3504 ValID CalleeID;
3505 SmallVector<ParamInfo, 16> ArgList;
3506 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003507
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3509 ParseOptionalCallingConv(CC) ||
3510 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003511 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003512 ParseValID(CalleeID) ||
3513 ParseParameterList(ArgList, PFS) ||
3514 ParseOptionalAttrs(FnAttrs, 2))
3515 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003516
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 // If RetType is a non-function pointer type, then this is the short syntax
3518 // for the call, which means that RetType is just the return type. Infer the
3519 // rest of the function argument types from the arguments that are present.
3520 const PointerType *PFTy = 0;
3521 const FunctionType *Ty = 0;
3522 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3523 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3524 // Pull out the types of all of the arguments...
3525 std::vector<const Type*> ParamTypes;
3526 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3527 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003528
Chris Lattnerdf986172009-01-02 07:01:27 +00003529 if (!FunctionType::isValidReturnType(RetType))
3530 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003531
Owen Andersondebcb012009-07-29 22:17:13 +00003532 Ty = FunctionType::get(RetType, ParamTypes, false);
3533 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003535
Chris Lattnerdf986172009-01-02 07:01:27 +00003536 // Look up the callee.
3537 Value *Callee;
3538 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003539
Chris Lattnerdf986172009-01-02 07:01:27 +00003540 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3541 // function attributes.
3542 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3543 if (FnAttrs & ObsoleteFuncAttrs) {
3544 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3545 FnAttrs &= ~ObsoleteFuncAttrs;
3546 }
3547
3548 // Set up the Attributes for the function.
3549 SmallVector<AttributeWithIndex, 8> Attrs;
3550 if (RetAttrs != Attribute::None)
3551 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003552
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003554
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 // Loop through FunctionType's arguments and ensure they are specified
3556 // correctly. Also, gather any parameter attributes.
3557 FunctionType::param_iterator I = Ty->param_begin();
3558 FunctionType::param_iterator E = Ty->param_end();
3559 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3560 const Type *ExpectedTy = 0;
3561 if (I != E) {
3562 ExpectedTy = *I++;
3563 } else if (!Ty->isVarArg()) {
3564 return Error(ArgList[i].Loc, "too many arguments specified");
3565 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003566
Chris Lattnerdf986172009-01-02 07:01:27 +00003567 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3568 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3569 ExpectedTy->getDescription() + "'");
3570 Args.push_back(ArgList[i].V);
3571 if (ArgList[i].Attrs != Attribute::None)
3572 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3573 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003574
Chris Lattnerdf986172009-01-02 07:01:27 +00003575 if (I != E)
3576 return Error(CallLoc, "not enough parameters specified for call");
3577
3578 if (FnAttrs != Attribute::None)
3579 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3580
3581 // Finish off the Attributes and check them
3582 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003583
Chris Lattnerdf986172009-01-02 07:01:27 +00003584 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3585 CI->setTailCall(isTail);
3586 CI->setCallingConv(CC);
3587 CI->setAttributes(PAL);
3588 Inst = CI;
3589 return false;
3590}
3591
3592//===----------------------------------------------------------------------===//
3593// Memory Instructions.
3594//===----------------------------------------------------------------------===//
3595
3596/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003597/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3598/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003599bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003600 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003601 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003603 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003604 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003605 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003606
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003607 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003608 if (Lex.getKind() == lltok::kw_align
3609 || Lex.getKind() == lltok::NamedOrCustomMD) {
Devang Patelf633a062009-09-17 23:04:48 +00003610 if (ParseOptionalInfo(Alignment)) return true;
3611 } else {
3612 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3613 if (EatIfPresent(lltok::comma))
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 }
3616 }
3617
Owen Anderson1d0be152009-08-13 21:58:54 +00003618 if (Size && Size->getType() != Type::getInt32Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 return Error(SizeLoc, "element count must be i32");
3620
Victor Hernandez68afa542009-10-21 19:11:40 +00003621 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003622 Inst = new AllocaInst(Ty, Size, Alignment);
Victor Hernandez68afa542009-10-21 19:11:40 +00003623 return false;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003624 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003625
3626 // Autoupgrade old malloc instruction to malloc call.
3627 // FIXME: Remove in LLVM 3.0.
3628 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003629 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3630 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003631 if (!MallocF)
3632 // Prototype malloc as "void *(int32)".
3633 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003634 MallocF = cast<Function>(
3635 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003636 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerdf986172009-01-02 07:01:27 +00003637 return false;
3638}
3639
3640/// ParseFree
3641/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003642bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3643 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003644 Value *Val; LocTy Loc;
3645 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3646 if (!isa<PointerType>(Val->getType()))
3647 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003648 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003649 return false;
3650}
3651
3652/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003653/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003654bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3655 bool isVolatile) {
3656 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003657 unsigned Alignment = 0;
3658 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003659
Devang Patelf633a062009-09-17 23:04:48 +00003660 if (EatIfPresent(lltok::comma))
3661 if (ParseOptionalInfo(Alignment)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003662
3663 if (!isa<PointerType>(Val->getType()) ||
3664 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3665 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003666
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3668 return false;
3669}
3670
3671/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003672/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerdf986172009-01-02 07:01:27 +00003673bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3674 bool isVolatile) {
3675 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003676 unsigned Alignment = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003677 if (ParseTypeAndValue(Val, Loc, PFS) ||
3678 ParseToken(lltok::comma, "expected ',' after store operand") ||
Devang Patelf633a062009-09-17 23:04:48 +00003679 ParseTypeAndValue(Ptr, PtrLoc, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003680 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003681
3682 if (EatIfPresent(lltok::comma))
3683 if (ParseOptionalInfo(Alignment)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003684
Chris Lattnerdf986172009-01-02 07:01:27 +00003685 if (!isa<PointerType>(Ptr->getType()))
3686 return Error(PtrLoc, "store operand must be a pointer");
3687 if (!Val->getType()->isFirstClassType())
3688 return Error(Loc, "store operand must be a first class value");
3689 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3690 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003691
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3693 return false;
3694}
3695
3696/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003697/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003698/// FIXME: Remove support for getresult in LLVM 3.0
3699bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3700 Value *Val; LocTy ValLoc, EltLoc;
3701 unsigned Element;
3702 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3703 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003704 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003705 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003706
Chris Lattnerdf986172009-01-02 07:01:27 +00003707 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3708 return Error(ValLoc, "getresult inst requires an aggregate operand");
3709 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3710 return Error(EltLoc, "invalid getresult index for value");
3711 Inst = ExtractValueInst::Create(Val, Element);
3712 return false;
3713}
3714
3715/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003716/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnerdf986172009-01-02 07:01:27 +00003717bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3718 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003719
Dan Gohmandcb40a32009-07-29 15:58:36 +00003720 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003721
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003722 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003723
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 if (!isa<PointerType>(Ptr->getType()))
3725 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 SmallVector<Value*, 16> Indices;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003728 while (EatIfPresent(lltok::comma)) {
Devang Patel6225d642009-10-13 18:49:55 +00003729 if (Lex.getKind() == lltok::NamedOrCustomMD)
3730 break;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003731 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003732 if (!isa<IntegerType>(Val->getType()))
3733 return Error(EltLoc, "getelementptr index must be an integer");
3734 Indices.push_back(Val);
3735 }
Devang Patel6225d642009-10-13 18:49:55 +00003736 if (Lex.getKind() == lltok::NamedOrCustomMD)
3737 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003738
Chris Lattnerdf986172009-01-02 07:01:27 +00003739 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3740 Indices.begin(), Indices.end()))
3741 return Error(Loc, "invalid getelementptr indices");
3742 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003743 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003744 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnerdf986172009-01-02 07:01:27 +00003745 return false;
3746}
3747
3748/// ParseExtractValue
3749/// ::= 'extractvalue' TypeAndValue (',' uint32)+
3750bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3751 Value *Val; LocTy Loc;
3752 SmallVector<unsigned, 4> Indices;
3753 if (ParseTypeAndValue(Val, Loc, PFS) ||
3754 ParseIndexList(Indices))
3755 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003756 if (Lex.getKind() == lltok::NamedOrCustomMD)
3757 if (ParseOptionalCustomMetadata()) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003758
3759 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3760 return Error(Loc, "extractvalue operand must be array or struct");
3761
3762 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3763 Indices.end()))
3764 return Error(Loc, "invalid indices for extractvalue");
3765 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3766 return false;
3767}
3768
3769/// ParseInsertValue
3770/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3771bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3772 Value *Val0, *Val1; LocTy Loc0, Loc1;
3773 SmallVector<unsigned, 4> Indices;
3774 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3775 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3776 ParseTypeAndValue(Val1, Loc1, PFS) ||
3777 ParseIndexList(Indices))
3778 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00003779 if (Lex.getKind() == lltok::NamedOrCustomMD)
3780 if (ParseOptionalCustomMetadata()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003781
Chris Lattnerdf986172009-01-02 07:01:27 +00003782 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3783 return Error(Loc0, "extractvalue operand must be array or struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003784
Chris Lattnerdf986172009-01-02 07:01:27 +00003785 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3786 Indices.end()))
3787 return Error(Loc0, "invalid indices for insertvalue");
3788 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3789 return false;
3790}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003791
3792//===----------------------------------------------------------------------===//
3793// Embedded metadata.
3794//===----------------------------------------------------------------------===//
3795
3796/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003797/// ::= Element (',' Element)*
3798/// Element
3799/// ::= 'null' | TypeAndValue
3800bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
Nick Lewycky21cc4462009-04-04 07:22:01 +00003801 do {
Devang Pateldb5e9002009-07-23 01:36:16 +00003802 Value *V = 0;
Chris Lattner442ffa12009-12-29 21:53:55 +00003803 // FIXME: REWRITE.
Nick Lewyckycb337992009-05-10 20:57:05 +00003804 if (Lex.getKind() == lltok::kw_null) {
3805 Lex.Lex();
3806 V = 0;
3807 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00003808 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patele54abc92009-07-22 17:43:22 +00003809 if (ParseType(Ty)) return true;
3810 if (Lex.getKind() == lltok::Metadata) {
3811 Lex.Lex();
Chris Lattner442ffa12009-12-29 21:53:55 +00003812 MDNode *Node = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003813 if (!ParseMDNode(Node))
3814 V = Node;
3815 else {
Chris Lattner442ffa12009-12-29 21:53:55 +00003816 MDString *MDS = 0;
Devang Patele54abc92009-07-22 17:43:22 +00003817 if (ParseMDString(MDS)) return true;
3818 V = MDS;
3819 }
3820 } else {
3821 Constant *C;
3822 if (ParseGlobalValue(Ty, C)) return true;
3823 V = C;
3824 }
Nick Lewyckycb337992009-05-10 20:57:05 +00003825 }
3826 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003827 } while (EatIfPresent(lltok::comma));
3828
3829 return false;
3830}