blob: fa1d97d99f90ab40c4f3aa9ed7aca50e18872ca8 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerdf986172009-01-02 07:01:27 +000026#include "llvm/Support/raw_ostream.h"
27using namespace llvm;
28
Chris Lattner3ed88ef2009-01-02 08:05:26 +000029/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000030bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000031 // Prime the lexer.
32 Lex.Lex();
33
Chris Lattnerad7d1e22009-01-04 20:44:11 +000034 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000036}
37
38/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
39/// module.
40bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000041 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
45 I != E; ++I) {
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
48
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
51
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000054 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000055 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
56 }
57 }
58 ForwardRefInstMetadata.clear();
59 }
60
61
Chris Lattner09d9ef42009-10-28 03:39:23 +000062 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
66 Function *TheFn = 0;
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
72
73 if (TheFn == 0)
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
75
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
79 0))
80 return true;
81
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
83 }
84
85
Chris Lattnerdf986172009-01-02 07:01:27 +000086 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000093 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000094
Chris Lattnerdf986172009-01-02 07:01:27 +000095 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
98 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +000099
Chris Lattnerdf986172009-01-02 07:01:27 +0000100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000103 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000104
Devang Patel1c7eea62009-07-08 19:23:54 +0000105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000108 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000109
Devang Patel1c7eea62009-07-08 19:23:54 +0000110
Chris Lattnerdf986172009-01-02 07:01:27 +0000111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000114
Devang Patele4b27562009-08-28 23:24:31 +0000115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000117 return false;
118}
119
Chris Lattner09d9ef42009-10-28 03:39:23 +0000120bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
125 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000126 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000129 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000133 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000134 } else {
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
137 }
138
Chris Lattnercdfc9402009-11-01 01:27:45 +0000139 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
142
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
147 }
148 return false;
149}
150
151
Chris Lattnerdf986172009-01-02 07:01:27 +0000152//===----------------------------------------------------------------------===//
153// Top-Level Entities
154//===----------------------------------------------------------------------===//
155
156bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000157 while (1) {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000161 case lltok::kw_declare: if (ParseDeclare()) return true; break;
162 case lltok::kw_define: if (ParseDefine()) return true; break;
163 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
164 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
165 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
166 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000167 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000168 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
169 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000170 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000171 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000172 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000173 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000174
175 // The Global variable production with no name can have many different
176 // optional leading prefixes, the production is:
177 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000178 // OptionalAddrSpace OptionalUnNammedAddr
179 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000180 case lltok::kw_private: // OptionalLinkage
181 case lltok::kw_linker_private: // OptionalLinkage
182 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000183 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000184 case lltok::kw_internal: // OptionalLinkage
185 case lltok::kw_weak: // OptionalLinkage
186 case lltok::kw_weak_odr: // OptionalLinkage
187 case lltok::kw_linkonce: // OptionalLinkage
188 case lltok::kw_linkonce_odr: // OptionalLinkage
189 case lltok::kw_appending: // OptionalLinkage
190 case lltok::kw_dllexport: // OptionalLinkage
191 case lltok::kw_common: // OptionalLinkage
192 case lltok::kw_dllimport: // OptionalLinkage
193 case lltok::kw_extern_weak: // OptionalLinkage
194 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000195 unsigned Linkage, Visibility;
196 if (ParseOptionalLinkage(Linkage) ||
197 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000198 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 return true;
200 break;
201 }
202 case lltok::kw_default: // OptionalVisibility
203 case lltok::kw_hidden: // OptionalVisibility
204 case lltok::kw_protected: { // OptionalVisibility
205 unsigned Visibility;
206 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000207 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000208 return true;
209 break;
210 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 case lltok::kw_thread_local: // OptionalThreadLocal
213 case lltok::kw_addrspace: // OptionalAddrSpace
214 case lltok::kw_constant: // GlobalType
215 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000216 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000217 break;
218 }
219 }
220}
221
222
223/// toplevelentity
224/// ::= 'module' 'asm' STRINGCONSTANT
225bool LLParser::ParseModuleAsm() {
226 assert(Lex.getKind() == lltok::kw_module);
227 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000228
229 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000230 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
231 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000232
Rafael Espindola38c4e532011-03-02 04:14:42 +0000233 M->appendModuleInlineAsm(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 '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000297 Twine(TypeID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000298 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 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000305 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000306
Owen Anderson1d0be152009-08-13 21:58:54 +0000307 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000308 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattnerdf986172009-01-02 07:01:27 +0000310 // See if this type was previously referenced.
311 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
312 FI = ForwardRefTypeIDs.find(TypeID);
313 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000314 if (FI->second.first.get() == Ty)
315 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000316
Chris Lattnerdf986172009-01-02 07:01:27 +0000317 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
318 Ty = FI->second.first.get();
319 ForwardRefTypeIDs.erase(FI);
320 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000321
Chris Lattnerdf986172009-01-02 07:01:27 +0000322 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000323
Chris Lattnerdf986172009-01-02 07:01:27 +0000324 return false;
325}
326
327/// toplevelentity
328/// ::= LocalVar '=' 'type' type
329bool LLParser::ParseNamedType() {
330 std::string Name = Lex.getStrVal();
331 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000332 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000333
Owen Anderson1d0be152009-08-13 21:58:54 +0000334 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000335
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000336 if (ParseToken(lltok::equal, "expected '=' after name") ||
337 ParseToken(lltok::kw_type, "expected 'type' after name") ||
338 ParseType(Ty))
339 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000340
Chris Lattnerdf986172009-01-02 07:01:27 +0000341 // Set the type name, checking for conflicts as we do so.
342 bool AlreadyExists = M->addTypeName(Name, Ty);
343 if (!AlreadyExists) return false;
344
345 // See if this type is a forward reference. We need to eagerly resolve
346 // types to allow recursive type redefinitions below.
347 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
348 FI = ForwardRefTypes.find(Name);
349 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000350 if (FI->second.first.get() == Ty)
351 return Error(NameLoc, "self referential type is invalid");
352
Chris Lattnerdf986172009-01-02 07:01:27 +0000353 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
354 Ty = FI->second.first.get();
355 ForwardRefTypes.erase(FI);
356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000357
Chris Lattnerdf986172009-01-02 07:01:27 +0000358 // Inserting a name that is already defined, get the existing name.
359 const Type *Existing = M->getTypeByName(Name);
360 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Chris Lattnerdf986172009-01-02 07:01:27 +0000362 // Otherwise, this is an attempt to redefine a type. That's okay if
363 // the redefinition is identical to the original.
364 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
365 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000366
Chris Lattnerdf986172009-01-02 07:01:27 +0000367 // Any other kind of (non-equivalent) redefinition is an error.
368 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
369 Ty->getDescription() + "'");
370}
371
372
373/// toplevelentity
374/// ::= 'declare' FunctionHeader
375bool LLParser::ParseDeclare() {
376 assert(Lex.getKind() == lltok::kw_declare);
377 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000378
Chris Lattnerdf986172009-01-02 07:01:27 +0000379 Function *F;
380 return ParseFunctionHeader(F, false);
381}
382
383/// toplevelentity
384/// ::= 'define' FunctionHeader '{' ...
385bool LLParser::ParseDefine() {
386 assert(Lex.getKind() == lltok::kw_define);
387 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Chris Lattnerdf986172009-01-02 07:01:27 +0000389 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000390 return ParseFunctionHeader(F, true) ||
391 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000392}
393
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000394/// ParseGlobalType
395/// ::= 'constant'
396/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000397bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
399 IsConstant = true;
400 else if (Lex.getKind() == lltok::kw_global)
401 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000402 else {
403 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000404 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000405 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000406 Lex.Lex();
407 return false;
408}
409
Dan Gohman3845e502009-08-12 23:32:33 +0000410/// ParseUnnamedGlobal:
411/// OptionalVisibility ALIAS ...
412/// OptionalLinkage OptionalVisibility ... -> global variable
413/// GlobalID '=' OptionalVisibility ALIAS ...
414/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
415bool LLParser::ParseUnnamedGlobal() {
416 unsigned VarID = NumberedVals.size();
417 std::string Name;
418 LocTy NameLoc = Lex.getLoc();
419
420 // Handle the GlobalID form.
421 if (Lex.getKind() == lltok::GlobalID) {
422 if (Lex.getUIntVal() != VarID)
423 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000424 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000425 Lex.Lex(); // eat GlobalID;
426
427 if (ParseToken(lltok::equal, "expected '=' after name"))
428 return true;
429 }
430
431 bool HasLinkage;
432 unsigned Linkage, Visibility;
433 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
434 ParseOptionalVisibility(Visibility))
435 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000436
Dan Gohman3845e502009-08-12 23:32:33 +0000437 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
438 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
439 return ParseAlias(Name, NameLoc, Visibility);
440}
441
Chris Lattnerdf986172009-01-02 07:01:27 +0000442/// ParseNamedGlobal:
443/// GlobalVar '=' OptionalVisibility ALIAS ...
444/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
445bool LLParser::ParseNamedGlobal() {
446 assert(Lex.getKind() == lltok::GlobalVar);
447 LocTy NameLoc = Lex.getLoc();
448 std::string Name = Lex.getStrVal();
449 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattnerdf986172009-01-02 07:01:27 +0000451 bool HasLinkage;
452 unsigned Linkage, Visibility;
453 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
454 ParseOptionalLinkage(Linkage, HasLinkage) ||
455 ParseOptionalVisibility(Visibility))
456 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Chris Lattnerdf986172009-01-02 07:01:27 +0000458 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
459 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
460 return ParseAlias(Name, NameLoc, Visibility);
461}
462
Devang Patel256be962009-07-20 19:00:08 +0000463// MDString:
464// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000465bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000466 std::string Str;
467 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000468 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000469 return false;
470}
471
472// MDNode:
473// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000474//
475/// This version of ParseMDNodeID returns the slot number and null in the case
476/// of a forward reference.
477bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
478 // !{ ..., !42, ... }
479 if (ParseUInt32(SlotNo)) return true;
480
481 // Check existing MDNode.
482 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
483 Result = NumberedMetadata[SlotNo];
484 else
485 Result = 0;
486 return false;
487}
488
Chris Lattner4a72efc2009-12-30 04:15:23 +0000489bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000490 // !{ ..., !42, ... }
491 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000492 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000493
Chris Lattner449c3102010-04-01 05:14:45 +0000494 // If not a forward reference, just return it now.
495 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000496
Chris Lattner449c3102010-04-01 05:14:45 +0000497 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000498 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000499 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000500
501 if (NumberedMetadata.size() <= MID)
502 NumberedMetadata.resize(MID+1);
503 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000504 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000505 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000506}
Devang Patel256be962009-07-20 19:00:08 +0000507
Chris Lattner84d03b12009-12-29 22:35:39 +0000508/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000509/// !foo = !{ !1, !2 }
510bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000511 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000512 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000513 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000514
Chris Lattner84d03b12009-12-29 22:35:39 +0000515 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000516 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000517 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000518 return true;
519
Dan Gohman17aa92c2010-07-21 23:38:33 +0000520 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000521 if (Lex.getKind() != lltok::rbrace)
522 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000523 if (ParseToken(lltok::exclaim, "Expected '!' here"))
524 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000525
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000526 MDNode *N = 0;
527 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000528 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000529 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000530
531 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
532 return true;
533
Devang Pateleff2ab62009-07-29 00:34:02 +0000534 return false;
535}
536
Devang Patel923078c2009-07-01 19:21:12 +0000537/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000538/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000539bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000540 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000541 Lex.Lex();
542 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000543
544 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000545 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000546 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000547 if (ParseUInt32(MetadataID) ||
548 ParseToken(lltok::equal, "expected '=' here") ||
549 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000550 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000551 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000552 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000553 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000554 return true;
555
Jay Foadec9186b2011-04-21 19:59:31 +0000556 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000557
558 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000559 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000560 FI = ForwardRefMDNodes.find(MetadataID);
561 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000562 MDNode *Temp = FI->second.first;
563 Temp->replaceAllUsesWith(Init);
564 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000565 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000566
567 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
568 } else {
569 if (MetadataID >= NumberedMetadata.size())
570 NumberedMetadata.resize(MetadataID+1);
571
572 if (NumberedMetadata[MetadataID] != 0)
573 return TokError("Metadata id is already used");
574 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000575 }
576
Devang Patel923078c2009-07-01 19:21:12 +0000577 return false;
578}
579
Chris Lattnerdf986172009-01-02 07:01:27 +0000580/// ParseAlias:
581/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
582/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000583/// ::= TypeAndValue
584/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000585/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000586///
587/// Everything through visibility has already been parsed.
588///
589bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
590 unsigned Visibility) {
591 assert(Lex.getKind() == lltok::kw_alias);
592 Lex.Lex();
593 unsigned Linkage;
594 LocTy LinkageLoc = Lex.getLoc();
595 if (ParseOptionalLinkage(Linkage))
596 return true;
597
598 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000599 Linkage != GlobalValue::WeakAnyLinkage &&
600 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000601 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000602 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000603 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000604 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
605 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000606 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000607
Chris Lattnerdf986172009-01-02 07:01:27 +0000608 Constant *Aliasee;
609 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000610 if (Lex.getKind() != lltok::kw_bitcast &&
611 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000612 if (ParseGlobalTypeAndValue(Aliasee)) return true;
613 } else {
614 // The bitcast dest type is not present, it is implied by the dest type.
615 ValID ID;
616 if (ParseValID(ID)) return true;
617 if (ID.Kind != ValID::t_Constant)
618 return Error(AliaseeLoc, "invalid aliasee");
619 Aliasee = ID.ConstantVal;
620 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000621
Duncan Sands1df98592010-02-16 11:11:14 +0000622 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000623 return Error(AliaseeLoc, "alias must have pointer type");
624
625 // Okay, create the alias but do not insert it into the module yet.
626 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
627 (GlobalValue::LinkageTypes)Linkage, Name,
628 Aliasee);
629 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 // See if this value already exists in the symbol table. If so, it is either
632 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000633 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000634 // See if this was a redefinition. If so, there is no entry in
635 // ForwardRefVals.
636 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
637 I = ForwardRefVals.find(Name);
638 if (I == ForwardRefVals.end())
639 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
640
641 // Otherwise, this was a definition of forward ref. Verify that types
642 // agree.
643 if (Val->getType() != GA->getType())
644 return Error(NameLoc,
645 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000646
Chris Lattnerdf986172009-01-02 07:01:27 +0000647 // If they agree, just RAUW the old value with the alias and remove the
648 // forward ref info.
649 Val->replaceAllUsesWith(GA);
650 Val->eraseFromParent();
651 ForwardRefVals.erase(I);
652 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // Insert into the module, we know its name won't collide now.
655 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000656 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 return false;
659}
660
661/// ParseGlobal
662/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000663/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000664/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000665/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000666///
667/// Everything through visibility has been parsed already.
668///
669bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
670 unsigned Linkage, bool HasLinkage,
671 unsigned Visibility) {
672 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000673 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000674 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Owen Anderson1d0be152009-08-13 21:58:54 +0000677 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000678 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
679 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000680 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
681 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000682 ParseGlobalType(IsConstant) ||
683 ParseType(Ty, TyLoc))
684 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000685
Chris Lattnerdf986172009-01-02 07:01:27 +0000686 // If the linkage is specified and is external, then no initializer is
687 // present.
688 Constant *Init = 0;
689 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000690 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000691 Linkage != GlobalValue::ExternalLinkage)) {
692 if (ParseGlobalValue(Ty, Init))
693 return true;
694 }
695
Duncan Sands1df98592010-02-16 11:11:14 +0000696 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000697 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000698
Chris Lattnerdf986172009-01-02 07:01:27 +0000699 GlobalVariable *GV = 0;
700
701 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000702 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000703 if (GlobalValue *GVal = M->getNamedValue(Name)) {
704 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
705 return Error(NameLoc, "redefinition of global '@" + Name + "'");
706 GV = cast<GlobalVariable>(GVal);
707 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000708 } else {
709 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
710 I = ForwardRefValIDs.find(NumberedVals.size());
711 if (I != ForwardRefValIDs.end()) {
712 GV = cast<GlobalVariable>(I->second.first);
713 ForwardRefValIDs.erase(I);
714 }
715 }
716
717 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000719 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000720 } else {
721 if (GV->getType()->getElementType() != Ty)
722 return Error(TyLoc,
723 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000724
Chris Lattnerdf986172009-01-02 07:01:27 +0000725 // Move the forward-reference to the correct spot in the module.
726 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
727 }
728
729 if (Name.empty())
730 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731
Chris Lattnerdf986172009-01-02 07:01:27 +0000732 // Set the parsed properties on the global.
733 if (Init)
734 GV->setInitializer(Init);
735 GV->setConstant(IsConstant);
736 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
737 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
738 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000739 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000740
Chris Lattnerdf986172009-01-02 07:01:27 +0000741 // Parse attributes on the global.
742 while (Lex.getKind() == lltok::comma) {
743 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattnerdf986172009-01-02 07:01:27 +0000745 if (Lex.getKind() == lltok::kw_section) {
746 Lex.Lex();
747 GV->setSection(Lex.getStrVal());
748 if (ParseToken(lltok::StringConstant, "expected global section string"))
749 return true;
750 } else if (Lex.getKind() == lltok::kw_align) {
751 unsigned Alignment;
752 if (ParseOptionalAlignment(Alignment)) return true;
753 GV->setAlignment(Alignment);
754 } else {
755 TokError("unknown global variable property!");
756 }
757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 return false;
760}
761
762
763//===----------------------------------------------------------------------===//
764// GlobalValue Reference/Resolution Routines.
765//===----------------------------------------------------------------------===//
766
767/// GetGlobalVal - Get a value with the specified name or ID, creating a
768/// forward reference record if needed. This can return null if the value
769/// exists but does not have the right type.
770GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
771 LocTy Loc) {
772 const PointerType *PTy = dyn_cast<PointerType>(Ty);
773 if (PTy == 0) {
774 Error(Loc, "global variable reference must have pointer type");
775 return 0;
776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattnerdf986172009-01-02 07:01:27 +0000778 // Look this name up in the normal function symbol table.
779 GlobalValue *Val =
780 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 // If this is a forward reference for the value, see if we already created a
783 // forward ref record.
784 if (Val == 0) {
785 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefVals.find(Name);
787 if (I != ForwardRefVals.end())
788 Val = I->second.first;
789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000790
Chris Lattnerdf986172009-01-02 07:01:27 +0000791 // If we have the value in the symbol table or fwd-ref table, return it.
792 if (Val) {
793 if (Val->getType() == Ty) return Val;
794 Error(Loc, "'@" + Name + "' defined with type '" +
795 Val->getType()->getDescription() + "'");
796 return 0;
797 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerdf986172009-01-02 07:01:27 +0000799 // Otherwise, create a new forward reference for this value and remember it.
800 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000801 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
802 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000803 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000804 Error(Loc, "function may not return opaque type");
805 return 0;
806 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000808 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000809 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000810 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
811 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattnerdf986172009-01-02 07:01:27 +0000814 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
815 return FwdVal;
816}
817
818GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
819 const PointerType *PTy = dyn_cast<PointerType>(Ty);
820 if (PTy == 0) {
821 Error(Loc, "global variable reference must have pointer type");
822 return 0;
823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Chris Lattnerdf986172009-01-02 07:01:27 +0000825 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Chris Lattnerdf986172009-01-02 07:01:27 +0000827 // If this is a forward reference for the value, see if we already created a
828 // forward ref record.
829 if (Val == 0) {
830 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
831 I = ForwardRefValIDs.find(ID);
832 if (I != ForwardRefValIDs.end())
833 Val = I->second.first;
834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000835
Chris Lattnerdf986172009-01-02 07:01:27 +0000836 // If we have the value in the symbol table or fwd-ref table, return it.
837 if (Val) {
838 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000839 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +0000840 Val->getType()->getDescription() + "'");
841 return 0;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Chris Lattnerdf986172009-01-02 07:01:27 +0000844 // Otherwise, create a new forward reference for this value and remember it.
845 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000846 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
847 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000848 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000849 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000850 return 0;
851 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000852 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000853 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000854 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
855 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000857
Chris Lattnerdf986172009-01-02 07:01:27 +0000858 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
859 return FwdVal;
860}
861
862
863//===----------------------------------------------------------------------===//
864// Helper Routines.
865//===----------------------------------------------------------------------===//
866
867/// ParseToken - If the current token has the specified kind, eat it and return
868/// success. Otherwise, emit the specified error and return failure.
869bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
870 if (Lex.getKind() != T)
871 return TokError(ErrMsg);
872 Lex.Lex();
873 return false;
874}
875
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000876/// ParseStringConstant
877/// ::= StringConstant
878bool LLParser::ParseStringConstant(std::string &Result) {
879 if (Lex.getKind() != lltok::StringConstant)
880 return TokError("expected string constant");
881 Result = Lex.getStrVal();
882 Lex.Lex();
883 return false;
884}
885
886/// ParseUInt32
887/// ::= uint32
888bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000889 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
890 return TokError("expected integer");
891 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
892 if (Val64 != unsigned(Val64))
893 return TokError("expected 32-bit integer (too large)");
894 Val = Val64;
895 Lex.Lex();
896 return false;
897}
898
899
900/// ParseOptionalAddrSpace
901/// := /*empty*/
902/// := 'addrspace' '(' uint32 ')'
903bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
904 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000905 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000906 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000907 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000908 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000909 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000910}
Chris Lattnerdf986172009-01-02 07:01:27 +0000911
912/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
913/// indicates what kind of attribute list this is: 0: function arg, 1: result,
914/// 2: function attr.
915bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
916 Attrs = Attribute::None;
917 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000918
Chris Lattnerdf986172009-01-02 07:01:27 +0000919 while (1) {
920 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000921 default: // End of attributes.
922 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
923 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000924
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000925 // As a hack, we allow "align 2" on functions as a synonym for
926 // "alignstack 2".
927 if (AttrKind == 2 &&
928 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
929 return Error(AttrLoc, "invalid use of attribute on a function");
930
931 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000933
Chris Lattnerdf986172009-01-02 07:01:27 +0000934 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000935 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
936 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
937 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
938 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
939 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
940 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
941 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
942 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000943
Devang Patel578efa92009-06-05 21:57:13 +0000944 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
945 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000946 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000947 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
948 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
949 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000950 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000951 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
952 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
953 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
954 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
955 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
956 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000957 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000958 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000959 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000960
Charles Davis1e063d12010-02-12 00:31:15 +0000961 case lltok::kw_alignstack: {
962 unsigned Alignment;
963 if (ParseOptionalStackAlignment(Alignment))
964 return true;
965 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
966 continue;
967 }
968
Chris Lattnerdf986172009-01-02 07:01:27 +0000969 case lltok::kw_align: {
970 unsigned Alignment;
971 if (ParseOptionalAlignment(Alignment))
972 return true;
973 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
974 continue;
975 }
Charles Davis1e063d12010-02-12 00:31:15 +0000976
Chris Lattnerdf986172009-01-02 07:01:27 +0000977 }
978 Lex.Lex();
979 }
980}
981
982/// ParseOptionalLinkage
983/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000984/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000985/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000986/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000987/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000988/// ::= 'internal'
989/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000990/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000991/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000992/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000993/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000994/// ::= 'appending'
995/// ::= 'dllexport'
996/// ::= 'common'
997/// ::= 'dllimport'
998/// ::= 'extern_weak'
999/// ::= 'external'
1000bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1001 HasLinkage = false;
1002 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001003 default: Res=GlobalValue::ExternalLinkage; return false;
1004 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1005 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001006 case lltok::kw_linker_private_weak:
1007 Res = GlobalValue::LinkerPrivateWeakLinkage;
1008 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001009 case lltok::kw_linker_private_weak_def_auto:
1010 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1011 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001012 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1013 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1014 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1015 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1016 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001017 case lltok::kw_available_externally:
1018 Res = GlobalValue::AvailableExternallyLinkage;
1019 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001020 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1021 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1022 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1023 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1024 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1025 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001026 }
1027 Lex.Lex();
1028 HasLinkage = true;
1029 return false;
1030}
1031
1032/// ParseOptionalVisibility
1033/// ::= /*empty*/
1034/// ::= 'default'
1035/// ::= 'hidden'
1036/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001037///
Chris Lattnerdf986172009-01-02 07:01:27 +00001038bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1039 switch (Lex.getKind()) {
1040 default: Res = GlobalValue::DefaultVisibility; return false;
1041 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1042 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1043 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1044 }
1045 Lex.Lex();
1046 return false;
1047}
1048
1049/// ParseOptionalCallingConv
1050/// ::= /*empty*/
1051/// ::= 'ccc'
1052/// ::= 'fastcc'
1053/// ::= 'coldcc'
1054/// ::= 'x86_stdcallcc'
1055/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001056/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001057/// ::= 'arm_apcscc'
1058/// ::= 'arm_aapcscc'
1059/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001060/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001061/// ::= 'ptx_kernel'
1062/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001063/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001064///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001065bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001066 switch (Lex.getKind()) {
1067 default: CC = CallingConv::C; return false;
1068 case lltok::kw_ccc: CC = CallingConv::C; break;
1069 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1070 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1071 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1072 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001073 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001074 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1075 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1076 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001077 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001078 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1079 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001080 case lltok::kw_cc: {
1081 unsigned ArbitraryCC;
1082 Lex.Lex();
1083 if (ParseUInt32(ArbitraryCC)) {
1084 return true;
1085 } else
1086 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1087 return false;
1088 }
1089 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001091
Chris Lattnerdf986172009-01-02 07:01:27 +00001092 Lex.Lex();
1093 return false;
1094}
1095
Chris Lattnerb8c46862009-12-30 05:31:19 +00001096/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001097/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001098bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1099 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001100 do {
1101 if (Lex.getKind() != lltok::MetadataVar)
1102 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001103
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001104 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001105 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001106 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001107
Chris Lattner442ffa12009-12-29 21:53:55 +00001108 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001109 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001110
1111 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001112 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Dan Gohman68261142010-08-24 14:35:45 +00001114 // This code is similar to that of ParseMetadataValue, however it needs to
1115 // have special-case code for a forward reference; see the comments on
1116 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1117 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001118 if (Lex.getKind() == lltok::lbrace) {
1119 ValID ID;
1120 if (ParseMetadataListValue(ID, PFS))
1121 return true;
1122 assert(ID.Kind == ValID::t_MDNode);
1123 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001124 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001125 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001126 if (ParseMDNodeID(Node, NodeID))
1127 return true;
1128 if (Node) {
1129 // If we got the node, add it to the instruction.
1130 Inst->setMetadata(MDK, Node);
1131 } else {
1132 MDRef R = { Loc, MDK, NodeID };
1133 // Otherwise, remember that this should be resolved later.
1134 ForwardRefInstMetadata[Inst].push_back(R);
1135 }
Chris Lattner449c3102010-04-01 05:14:45 +00001136 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001137
1138 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001139 } while (EatIfPresent(lltok::comma));
1140 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001141}
1142
Chris Lattnerdf986172009-01-02 07:01:27 +00001143/// ParseOptionalAlignment
1144/// ::= /* empty */
1145/// ::= 'align' 4
1146bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1147 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001148 if (!EatIfPresent(lltok::kw_align))
1149 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001150 LocTy AlignLoc = Lex.getLoc();
1151 if (ParseUInt32(Alignment)) return true;
1152 if (!isPowerOf2_32(Alignment))
1153 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001154 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001155 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001156 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001157}
1158
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001159/// ParseOptionalCommaAlign
1160/// ::=
1161/// ::= ',' align 4
1162///
1163/// This returns with AteExtraComma set to true if it ate an excess comma at the
1164/// end.
1165bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1166 bool &AteExtraComma) {
1167 AteExtraComma = false;
1168 while (EatIfPresent(lltok::comma)) {
1169 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001170 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001171 AteExtraComma = true;
1172 return false;
1173 }
1174
Chris Lattner093eed12010-04-23 00:50:50 +00001175 if (Lex.getKind() != lltok::kw_align)
1176 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001177
Chris Lattner093eed12010-04-23 00:50:50 +00001178 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001180
Devang Patelf633a062009-09-17 23:04:48 +00001181 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001182}
1183
Charles Davis1e063d12010-02-12 00:31:15 +00001184/// ParseOptionalStackAlignment
1185/// ::= /* empty */
1186/// ::= 'alignstack' '(' 4 ')'
1187bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1188 Alignment = 0;
1189 if (!EatIfPresent(lltok::kw_alignstack))
1190 return false;
1191 LocTy ParenLoc = Lex.getLoc();
1192 if (!EatIfPresent(lltok::lparen))
1193 return Error(ParenLoc, "expected '('");
1194 LocTy AlignLoc = Lex.getLoc();
1195 if (ParseUInt32(Alignment)) return true;
1196 ParenLoc = Lex.getLoc();
1197 if (!EatIfPresent(lltok::rparen))
1198 return Error(ParenLoc, "expected ')'");
1199 if (!isPowerOf2_32(Alignment))
1200 return Error(AlignLoc, "stack alignment is not a power of two");
1201 return false;
1202}
Devang Patelf633a062009-09-17 23:04:48 +00001203
Chris Lattner628c13a2009-12-30 05:14:00 +00001204/// ParseIndexList - This parses the index list for an insert/extractvalue
1205/// instruction. This sets AteExtraComma in the case where we eat an extra
1206/// comma at the end of the line and find that it is followed by metadata.
1207/// Clients that don't allow metadata can call the version of this function that
1208/// only takes one argument.
1209///
Chris Lattnerdf986172009-01-02 07:01:27 +00001210/// ParseIndexList
1211/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001212///
1213bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1214 bool &AteExtraComma) {
1215 AteExtraComma = false;
1216
Chris Lattnerdf986172009-01-02 07:01:27 +00001217 if (Lex.getKind() != lltok::comma)
1218 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001220 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001221 if (Lex.getKind() == lltok::MetadataVar) {
1222 AteExtraComma = true;
1223 return false;
1224 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001225 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001226 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001227 Indices.push_back(Idx);
1228 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001229
Chris Lattnerdf986172009-01-02 07:01:27 +00001230 return false;
1231}
1232
1233//===----------------------------------------------------------------------===//
1234// Type Parsing.
1235//===----------------------------------------------------------------------===//
1236
1237/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001238bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1239 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001241
Chris Lattnerdf986172009-01-02 07:01:27 +00001242 // Verify no unresolved uprefs.
1243 if (!UpRefs.empty())
1244 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001245
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001246 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001247 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001248
Chris Lattnerdf986172009-01-02 07:01:27 +00001249 return false;
1250}
1251
1252/// HandleUpRefs - Every time we finish a new layer of types, this function is
1253/// called. It loops through the UpRefs vector, which is a list of the
1254/// currently active types. For each type, if the up-reference is contained in
1255/// the newly completed type, we decrement the level count. When the level
1256/// count reaches zero, the up-referenced type is the type that is passed in:
1257/// thus we can complete the cycle.
1258///
1259PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1260 // If Ty isn't abstract, or if there are no up-references in it, then there is
1261 // nothing to resolve here.
1262 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001263
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 PATypeHolder Ty(ty);
1265#if 0
David Greene0e28d762009-12-23 23:38:28 +00001266 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 << "' newly formed. Resolving upreferences.\n"
1268 << UpRefs.size() << " upreferences active!\n";
1269#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001270
Chris Lattnerdf986172009-01-02 07:01:27 +00001271 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1272 // to zero), we resolve them all together before we resolve them to Ty. At
1273 // the end of the loop, if there is anything to resolve to Ty, it will be in
1274 // this variable.
1275 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001276
Chris Lattnerdf986172009-01-02 07:01:27 +00001277 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1278 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1279 bool ContainsType =
1280 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1281 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattnerdf986172009-01-02 07:01:27 +00001283#if 0
David Greene0e28d762009-12-23 23:38:28 +00001284 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1286 << (ContainsType ? "true" : "false")
1287 << " level=" << UpRefs[i].NestingLevel << "\n";
1288#endif
1289 if (!ContainsType)
1290 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 // Decrement level of upreference
1293 unsigned Level = --UpRefs[i].NestingLevel;
1294 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001295
Chris Lattnerdf986172009-01-02 07:01:27 +00001296 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1297 if (Level != 0)
1298 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001299
Chris Lattnerdf986172009-01-02 07:01:27 +00001300#if 0
David Greene0e28d762009-12-23 23:38:28 +00001301 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001302#endif
1303 if (!TypeToResolve)
1304 TypeToResolve = UpRefs[i].UpRefTy;
1305 else
1306 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1307 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1308 --i; // Do not skip the next element.
1309 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 if (TypeToResolve)
1312 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001313
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 return Ty;
1315}
1316
1317
1318/// ParseTypeRec - The recursive function used to process the internal
1319/// implementation details of types.
1320bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1321 switch (Lex.getKind()) {
1322 default:
1323 return TokError("expected type");
1324 case lltok::Type:
1325 // TypeRec ::= 'float' | 'void' (etc)
1326 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001327 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 break;
1329 case lltok::kw_opaque:
1330 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001331 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001332 Lex.Lex();
1333 break;
1334 case lltok::lbrace:
1335 // TypeRec ::= '{' ... '}'
1336 if (ParseStructType(Result, false))
1337 return true;
1338 break;
1339 case lltok::lsquare:
1340 // TypeRec ::= '[' ... ']'
1341 Lex.Lex(); // eat the lsquare.
1342 if (ParseArrayVectorType(Result, false))
1343 return true;
1344 break;
1345 case lltok::less: // Either vector or packed struct.
1346 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001347 Lex.Lex();
1348 if (Lex.getKind() == lltok::lbrace) {
1349 if (ParseStructType(Result, true) ||
1350 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001351 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001352 } else if (ParseArrayVectorType(Result, true))
1353 return true;
1354 break;
1355 case lltok::LocalVar:
1356 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1357 // TypeRec ::= %foo
1358 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1359 Result = T;
1360 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001361 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1363 std::make_pair(Result,
1364 Lex.getLoc())));
1365 M->addTypeName(Lex.getStrVal(), Result.get());
1366 }
1367 Lex.Lex();
1368 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001369
Chris Lattnerdf986172009-01-02 07:01:27 +00001370 case lltok::LocalVarID:
1371 // TypeRec ::= %4
1372 if (Lex.getUIntVal() < NumberedTypes.size())
1373 Result = NumberedTypes[Lex.getUIntVal()];
1374 else {
1375 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1376 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1377 if (I != ForwardRefTypeIDs.end())
1378 Result = I->second.first;
1379 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001380 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001381 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1382 std::make_pair(Result,
1383 Lex.getLoc())));
1384 }
1385 }
1386 Lex.Lex();
1387 break;
1388 case lltok::backslash: {
1389 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001391 unsigned Val;
1392 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001393 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1395 Result = OT;
1396 break;
1397 }
1398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
1400 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 while (1) {
1402 switch (Lex.getKind()) {
1403 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001405
1406 // TypeRec ::= TypeRec '*'
1407 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001408 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001410 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001411 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001412 if (!PointerType::isValidElementType(Result.get()))
1413 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001414 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 Lex.Lex();
1416 break;
1417
1418 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1419 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001420 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001422 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001423 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001424 if (!PointerType::isValidElementType(Result.get()))
1425 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 unsigned AddrSpace;
1427 if (ParseOptionalAddrSpace(AddrSpace) ||
1428 ParseToken(lltok::star, "expected '*' in address space"))
1429 return true;
1430
Owen Andersondebcb012009-07-29 22:17:13 +00001431 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 break;
1433 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001434
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1436 case lltok::lparen:
1437 if (ParseFunctionType(Result))
1438 return true;
1439 break;
1440 }
1441 }
1442}
1443
1444/// ParseParameterList
1445/// ::= '(' ')'
1446/// ::= '(' Arg (',' Arg)* ')'
1447/// Arg
1448/// ::= Type OptionalAttributes Value OptionalAttributes
1449bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1450 PerFunctionState &PFS) {
1451 if (ParseToken(lltok::lparen, "expected '(' in call"))
1452 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattnerdf986172009-01-02 07:01:27 +00001454 while (Lex.getKind() != lltok::rparen) {
1455 // If this isn't the first argument, we need a comma.
1456 if (!ArgList.empty() &&
1457 ParseToken(lltok::comma, "expected ',' in argument list"))
1458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 // Parse the argument.
1461 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001462 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001463 unsigned ArgAttrs1 = Attribute::None;
1464 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001465 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001466 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001467 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001468
Chris Lattner287881d2009-12-30 02:11:14 +00001469 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001470 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001471 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1473 }
1474
1475 Lex.Lex(); // Lex the ')'.
1476 return false;
1477}
1478
1479
1480
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001481/// ParseArgumentList - Parse the argument list for a function type or function
1482/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001483/// ::= '(' ArgTypeListI ')'
1484/// ArgTypeListI
1485/// ::= /*empty*/
1486/// ::= '...'
1487/// ::= ArgTypeList ',' '...'
1488/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001489///
Chris Lattnerdf986172009-01-02 07:01:27 +00001490bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001491 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001492 isVarArg = false;
1493 assert(Lex.getKind() == lltok::lparen);
1494 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001495
Chris Lattnerdf986172009-01-02 07:01:27 +00001496 if (Lex.getKind() == lltok::rparen) {
1497 // empty
1498 } else if (Lex.getKind() == lltok::dotdotdot) {
1499 isVarArg = true;
1500 Lex.Lex();
1501 } else {
1502 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001503 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001504 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001505 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001507 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1508 // types (such as a function returning a pointer to itself). If parsing a
1509 // function prototype, we require fully resolved types.
1510 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001511 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001513 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001514 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001515
Chris Lattnerdf986172009-01-02 07:01:27 +00001516 if (Lex.getKind() == lltok::LocalVar ||
1517 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1518 Name = Lex.getStrVal();
1519 Lex.Lex();
1520 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001521
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001522 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001523 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001524
Chris Lattnerdf986172009-01-02 07:01:27 +00001525 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001527 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001528 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001529 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001530 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001531 break;
1532 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 // Otherwise must be an argument type.
1535 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001536 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001537 ParseOptionalAttrs(Attrs, 0)) return true;
1538
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001539 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001540 return Error(TypeLoc, "argument can not have void type");
1541
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 if (Lex.getKind() == lltok::LocalVar ||
1543 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1544 Name = Lex.getStrVal();
1545 Lex.Lex();
1546 } else {
1547 Name = "";
1548 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549
Duncan Sands47c51882010-02-16 14:50:09 +00001550 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001551 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001552
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1554 }
1555 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001557 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001558}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001559
Chris Lattnerdf986172009-01-02 07:01:27 +00001560/// ParseFunctionType
1561/// ::= Type ArgumentList OptionalAttrs
1562bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1563 assert(Lex.getKind() == lltok::lparen);
1564
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001565 if (!FunctionType::isValidReturnType(Result))
1566 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattnerdf986172009-01-02 07:01:27 +00001568 std::vector<ArgInfo> ArgList;
1569 bool isVarArg;
1570 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001571 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 // FIXME: Allow, but ignore attributes on function types!
1573 // FIXME: Remove in LLVM 3.0
1574 ParseOptionalAttrs(Attrs, 2))
1575 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattnerdf986172009-01-02 07:01:27 +00001577 // Reject names on the arguments lists.
1578 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1579 if (!ArgList[i].Name.empty())
1580 return Error(ArgList[i].Loc, "argument name invalid in function type");
1581 if (!ArgList[i].Attrs != 0) {
1582 // Allow but ignore attributes on function types; this permits
1583 // auto-upgrade.
1584 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1585 }
1586 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001587
Chris Lattnerdf986172009-01-02 07:01:27 +00001588 std::vector<const Type*> ArgListTy;
1589 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1590 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001591
Owen Andersondebcb012009-07-29 22:17:13 +00001592 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001593 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001594 return false;
1595}
1596
1597/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1598/// TypeRec
1599/// ::= '{' '}'
1600/// ::= '{' TypeRec (',' TypeRec)* '}'
1601/// ::= '<' '{' '}' '>'
1602/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1603bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1604 assert(Lex.getKind() == lltok::lbrace);
1605 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001606
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001607 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001608 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001609 return false;
1610 }
1611
1612 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001613 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001614 if (ParseTypeRec(Result)) return true;
1615 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001617 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001618 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001619 if (!StructType::isValidElementType(Result))
1620 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001622 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001623 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001624 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001626 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001627 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001628 if (!StructType::isValidElementType(Result))
1629 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001630
Chris Lattnerdf986172009-01-02 07:01:27 +00001631 ParamsList.push_back(Result);
1632 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001634 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1635 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001636
Chris Lattnerdf986172009-01-02 07:01:27 +00001637 std::vector<const Type*> ParamsListTy;
1638 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1639 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001640 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001641 return false;
1642}
1643
1644/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1645/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001646/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001647/// ::= '[' APSINTVAL 'x' Types ']'
1648/// ::= '<' APSINTVAL 'x' Types '>'
1649bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1650 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1651 Lex.getAPSIntVal().getBitWidth() > 64)
1652 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001653
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 LocTy SizeLoc = Lex.getLoc();
1655 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001656 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001658 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1659 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001660
1661 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001662 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001663 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001665 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001666 return Error(TypeLoc, "array and vector element type cannot be void");
1667
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001668 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1669 "expected end of sequential type"))
1670 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671
Chris Lattnerdf986172009-01-02 07:01:27 +00001672 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001673 if (Size == 0)
1674 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001675 if ((unsigned)Size != Size)
1676 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001677 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001678 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001679 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001680 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001681 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001682 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001683 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001684 }
1685 return false;
1686}
1687
1688//===----------------------------------------------------------------------===//
1689// Function Semantic Analysis.
1690//===----------------------------------------------------------------------===//
1691
Chris Lattner09d9ef42009-10-28 03:39:23 +00001692LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1693 int functionNumber)
1694 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001695
1696 // Insert unnamed arguments into the NumberedVals list.
1697 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1698 AI != E; ++AI)
1699 if (!AI->hasName())
1700 NumberedVals.push_back(AI);
1701}
1702
1703LLParser::PerFunctionState::~PerFunctionState() {
1704 // If there were any forward referenced non-basicblock values, delete them.
1705 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1706 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1707 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001708 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001709 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 delete I->second.first;
1711 I->second.first = 0;
1712 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1715 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1716 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001717 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001718 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001719 delete I->second.first;
1720 I->second.first = 0;
1721 }
1722}
1723
Chris Lattner09d9ef42009-10-28 03:39:23 +00001724bool LLParser::PerFunctionState::FinishFunction() {
1725 // Check to see if someone took the address of labels in this block.
1726 if (!P.ForwardRefBlockAddresses.empty()) {
1727 ValID FunctionID;
1728 if (!F.getName().empty()) {
1729 FunctionID.Kind = ValID::t_GlobalName;
1730 FunctionID.StrVal = F.getName();
1731 } else {
1732 FunctionID.Kind = ValID::t_GlobalID;
1733 FunctionID.UIntVal = FunctionNumber;
1734 }
1735
1736 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1737 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1738 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1739 // Resolve all these references.
1740 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1741 return true;
1742
1743 P.ForwardRefBlockAddresses.erase(FRBAI);
1744 }
1745 }
1746
Chris Lattnerdf986172009-01-02 07:01:27 +00001747 if (!ForwardRefVals.empty())
1748 return P.Error(ForwardRefVals.begin()->second.second,
1749 "use of undefined value '%" + ForwardRefVals.begin()->first +
1750 "'");
1751 if (!ForwardRefValIDs.empty())
1752 return P.Error(ForwardRefValIDs.begin()->second.second,
1753 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001754 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001755 return false;
1756}
1757
1758
1759/// GetVal - Get a value with the specified name or ID, creating a
1760/// forward reference record if needed. This can return null if the value
1761/// exists but does not have the right type.
1762Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1763 const Type *Ty, LocTy Loc) {
1764 // Look this name up in the normal function symbol table.
1765 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001766
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 // If this is a forward reference for the value, see if we already created a
1768 // forward ref record.
1769 if (Val == 0) {
1770 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1771 I = ForwardRefVals.find(Name);
1772 if (I != ForwardRefVals.end())
1773 Val = I->second.first;
1774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001775
Chris Lattnerdf986172009-01-02 07:01:27 +00001776 // If we have the value in the symbol table or fwd-ref table, return it.
1777 if (Val) {
1778 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001779 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001780 P.Error(Loc, "'%" + Name + "' is not a basic block");
1781 else
1782 P.Error(Loc, "'%" + Name + "' defined with type '" +
1783 Val->getType()->getDescription() + "'");
1784 return 0;
1785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001786
Chris Lattnerdf986172009-01-02 07:01:27 +00001787 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001788 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001789 P.Error(Loc, "invalid use of a non-first-class type");
1790 return 0;
1791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001792
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 // Otherwise, create a new forward reference for this value and remember it.
1794 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001795 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001796 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 else
1798 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001799
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1801 return FwdVal;
1802}
1803
1804Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1805 LocTy Loc) {
1806 // Look this name up in the normal function symbol table.
1807 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001808
Chris Lattnerdf986172009-01-02 07:01:27 +00001809 // If this is a forward reference for the value, see if we already created a
1810 // forward ref record.
1811 if (Val == 0) {
1812 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1813 I = ForwardRefValIDs.find(ID);
1814 if (I != ForwardRefValIDs.end())
1815 Val = I->second.first;
1816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001817
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 // If we have the value in the symbol table or fwd-ref table, return it.
1819 if (Val) {
1820 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001821 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001822 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001823 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001824 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001825 Val->getType()->getDescription() + "'");
1826 return 0;
1827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Duncan Sands47c51882010-02-16 14:50:09 +00001829 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001830 P.Error(Loc, "invalid use of a non-first-class type");
1831 return 0;
1832 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001833
Chris Lattnerdf986172009-01-02 07:01:27 +00001834 // Otherwise, create a new forward reference for this value and remember it.
1835 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001836 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001837 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 else
1839 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840
Chris Lattnerdf986172009-01-02 07:01:27 +00001841 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1842 return FwdVal;
1843}
1844
1845/// SetInstName - After an instruction is parsed and inserted into its
1846/// basic block, this installs its name.
1847bool LLParser::PerFunctionState::SetInstName(int NameID,
1848 const std::string &NameStr,
1849 LocTy NameLoc, Instruction *Inst) {
1850 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001851 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001852 if (NameID != -1 || !NameStr.empty())
1853 return P.Error(NameLoc, "instructions returning void cannot have a name");
1854 return false;
1855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattnerdf986172009-01-02 07:01:27 +00001857 // If this was a numbered instruction, verify that the instruction is the
1858 // expected value and resolve any forward references.
1859 if (NameStr.empty()) {
1860 // If neither a name nor an ID was specified, just use the next ID.
1861 if (NameID == -1)
1862 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 if (unsigned(NameID) != NumberedVals.size())
1865 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001866 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1869 ForwardRefValIDs.find(NameID);
1870 if (FI != ForwardRefValIDs.end()) {
1871 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001872 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001873 FI->second.first->getType()->getDescription() + "'");
1874 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001875 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 ForwardRefValIDs.erase(FI);
1877 }
1878
1879 NumberedVals.push_back(Inst);
1880 return false;
1881 }
1882
1883 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1884 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1885 FI = ForwardRefVals.find(NameStr);
1886 if (FI != ForwardRefVals.end()) {
1887 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001889 FI->second.first->getType()->getDescription() + "'");
1890 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001891 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001892 ForwardRefVals.erase(FI);
1893 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 // Set the name on the instruction.
1896 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897
Benjamin Krameraf812352010-10-16 11:28:23 +00001898 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001899 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001900 NameStr + "'");
1901 return false;
1902}
1903
1904/// GetBB - Get a basic block with the specified name or ID, creating a
1905/// forward reference record if needed.
1906BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1907 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001908 return cast_or_null<BasicBlock>(GetVal(Name,
1909 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001910}
1911
1912BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001913 return cast_or_null<BasicBlock>(GetVal(ID,
1914 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001915}
1916
1917/// DefineBB - Define the specified basic block, which is either named or
1918/// unnamed. If there is an error, this returns null otherwise it returns
1919/// the block being defined.
1920BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1921 LocTy Loc) {
1922 BasicBlock *BB;
1923 if (Name.empty())
1924 BB = GetBB(NumberedVals.size(), Loc);
1925 else
1926 BB = GetBB(Name, Loc);
1927 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928
Chris Lattnerdf986172009-01-02 07:01:27 +00001929 // Move the block to the end of the function. Forward ref'd blocks are
1930 // inserted wherever they happen to be referenced.
1931 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 // Remove the block from forward ref sets.
1934 if (Name.empty()) {
1935 ForwardRefValIDs.erase(NumberedVals.size());
1936 NumberedVals.push_back(BB);
1937 } else {
1938 // BB forward references are already in the function symbol table.
1939 ForwardRefVals.erase(Name);
1940 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001941
Chris Lattnerdf986172009-01-02 07:01:27 +00001942 return BB;
1943}
1944
1945//===----------------------------------------------------------------------===//
1946// Constants.
1947//===----------------------------------------------------------------------===//
1948
1949/// ParseValID - Parse an abstract value that doesn't necessarily have a
1950/// type implied. For example, if we parse "4" we don't know what integer type
1951/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001952/// sanity. PFS is used to convert function-local operands of metadata (since
1953/// metadata operands are not just parsed here but also converted to values).
1954/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001955bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001956 ID.Loc = Lex.getLoc();
1957 switch (Lex.getKind()) {
1958 default: return TokError("expected value token");
1959 case lltok::GlobalID: // @42
1960 ID.UIntVal = Lex.getUIntVal();
1961 ID.Kind = ValID::t_GlobalID;
1962 break;
1963 case lltok::GlobalVar: // @foo
1964 ID.StrVal = Lex.getStrVal();
1965 ID.Kind = ValID::t_GlobalName;
1966 break;
1967 case lltok::LocalVarID: // %42
1968 ID.UIntVal = Lex.getUIntVal();
1969 ID.Kind = ValID::t_LocalID;
1970 break;
1971 case lltok::LocalVar: // %foo
1972 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1973 ID.StrVal = Lex.getStrVal();
1974 ID.Kind = ValID::t_LocalName;
1975 break;
Dan Gohman83448032010-07-14 18:26:50 +00001976 case lltok::exclaim: // !42, !{...}, or !"foo"
1977 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001978 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001979 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001980 ID.Kind = ValID::t_APSInt;
1981 break;
1982 case lltok::APFloat:
1983 ID.APFloatVal = Lex.getAPFloatVal();
1984 ID.Kind = ValID::t_APFloat;
1985 break;
1986 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001987 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001988 ID.Kind = ValID::t_Constant;
1989 break;
1990 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001991 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001992 ID.Kind = ValID::t_Constant;
1993 break;
1994 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1995 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1996 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001997
Chris Lattnerdf986172009-01-02 07:01:27 +00001998 case lltok::lbrace: {
1999 // ValID ::= '{' ConstVector '}'
2000 Lex.Lex();
2001 SmallVector<Constant*, 16> Elts;
2002 if (ParseGlobalValueVector(Elts) ||
2003 ParseToken(lltok::rbrace, "expected end of struct constant"))
2004 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002005
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002006 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2007 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 ID.Kind = ValID::t_Constant;
2009 return false;
2010 }
2011 case lltok::less: {
2012 // ValID ::= '<' ConstVector '>' --> Vector.
2013 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2014 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002015 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 SmallVector<Constant*, 16> Elts;
2018 LocTy FirstEltLoc = Lex.getLoc();
2019 if (ParseGlobalValueVector(Elts) ||
2020 (isPackedStruct &&
2021 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2022 ParseToken(lltok::greater, "expected end of constant"))
2023 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Chris Lattnerdf986172009-01-02 07:01:27 +00002025 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002026 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002027 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002028 ID.Kind = ValID::t_Constant;
2029 return false;
2030 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002031
Chris Lattnerdf986172009-01-02 07:01:27 +00002032 if (Elts.empty())
2033 return Error(ID.Loc, "constant vector must not be empty");
2034
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002035 if (!Elts[0]->getType()->isIntegerTy() &&
2036 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002037 return Error(FirstEltLoc,
2038 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002039
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 // Verify that all the vector elements have the same type.
2041 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2042 if (Elts[i]->getType() != Elts[0]->getType())
2043 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002044 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002045 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Chris Lattner2ca5c862011-02-15 00:14:00 +00002047 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002048 ID.Kind = ValID::t_Constant;
2049 return false;
2050 }
2051 case lltok::lsquare: { // Array Constant
2052 Lex.Lex();
2053 SmallVector<Constant*, 16> Elts;
2054 LocTy FirstEltLoc = Lex.getLoc();
2055 if (ParseGlobalValueVector(Elts) ||
2056 ParseToken(lltok::rsquare, "expected end of array constant"))
2057 return true;
2058
2059 // Handle empty element.
2060 if (Elts.empty()) {
2061 // Use undef instead of an array because it's inconvenient to determine
2062 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002063 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002064 return false;
2065 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066
Chris Lattnerdf986172009-01-02 07:01:27 +00002067 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002068 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002069 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002070
Owen Andersondebcb012009-07-29 22:17:13 +00002071 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002072
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002074 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 if (Elts[i]->getType() != Elts[0]->getType())
2076 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002077 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002078 " is not of type '" +Elts[0]->getType()->getDescription());
2079 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002080
Owen Anderson1fd70962009-07-28 18:32:17 +00002081 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 ID.Kind = ValID::t_Constant;
2083 return false;
2084 }
2085 case lltok::kw_c: // c "foo"
2086 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002087 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002088 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2089 ID.Kind = ValID::t_Constant;
2090 return false;
2091
2092 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002093 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2094 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002095 Lex.Lex();
2096 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002097 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002098 ParseStringConstant(ID.StrVal) ||
2099 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 ParseToken(lltok::StringConstant, "expected constraint string"))
2101 return true;
2102 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002103 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002104 ID.Kind = ValID::t_InlineAsm;
2105 return false;
2106 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107
Chris Lattner09d9ef42009-10-28 03:39:23 +00002108 case lltok::kw_blockaddress: {
2109 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2110 Lex.Lex();
2111
2112 ValID Fn, Label;
2113 LocTy FnLoc, LabelLoc;
2114
2115 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2116 ParseValID(Fn) ||
2117 ParseToken(lltok::comma, "expected comma in block address expression")||
2118 ParseValID(Label) ||
2119 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2120 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002121
Chris Lattner09d9ef42009-10-28 03:39:23 +00002122 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2123 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002124 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002125 return Error(Label.Loc, "expected basic block name in blockaddress");
2126
2127 // Make a global variable as a placeholder for this reference.
2128 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2129 false, GlobalValue::InternalLinkage,
2130 0, "");
2131 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2132 ID.ConstantVal = FwdRef;
2133 ID.Kind = ValID::t_Constant;
2134 return false;
2135 }
2136
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 case lltok::kw_trunc:
2138 case lltok::kw_zext:
2139 case lltok::kw_sext:
2140 case lltok::kw_fptrunc:
2141 case lltok::kw_fpext:
2142 case lltok::kw_bitcast:
2143 case lltok::kw_uitofp:
2144 case lltok::kw_sitofp:
2145 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002146 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002147 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002149 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002150 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002151 Constant *SrcVal;
2152 Lex.Lex();
2153 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2154 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002155 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 ParseType(DestTy) ||
2157 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2158 return true;
2159 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2160 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2161 SrcVal->getType()->getDescription() + "' to '" +
2162 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002164 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002165 ID.Kind = ValID::t_Constant;
2166 return false;
2167 }
2168 case lltok::kw_extractvalue: {
2169 Lex.Lex();
2170 Constant *Val;
2171 SmallVector<unsigned, 4> Indices;
2172 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2173 ParseGlobalTypeAndValue(Val) ||
2174 ParseIndexList(Indices) ||
2175 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2176 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002177
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002178 if (!Val->getType()->isAggregateType())
2179 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2181 Indices.end()))
2182 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002183 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002184 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 ID.Kind = ValID::t_Constant;
2186 return false;
2187 }
2188 case lltok::kw_insertvalue: {
2189 Lex.Lex();
2190 Constant *Val0, *Val1;
2191 SmallVector<unsigned, 4> Indices;
2192 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2193 ParseGlobalTypeAndValue(Val0) ||
2194 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2195 ParseGlobalTypeAndValue(Val1) ||
2196 ParseIndexList(Indices) ||
2197 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2198 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002199 if (!Val0->getType()->isAggregateType())
2200 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002201 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2202 Indices.end()))
2203 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002204 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002205 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002206 ID.Kind = ValID::t_Constant;
2207 return false;
2208 }
2209 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002210 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 unsigned PredVal, Opc = Lex.getUIntVal();
2212 Constant *Val0, *Val1;
2213 Lex.Lex();
2214 if (ParseCmpPredicate(PredVal, Opc) ||
2215 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2216 ParseGlobalTypeAndValue(Val0) ||
2217 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2218 ParseGlobalTypeAndValue(Val1) ||
2219 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2220 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 if (Val0->getType() != Val1->getType())
2223 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002224
Chris Lattnerdf986172009-01-02 07:01:27 +00002225 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002226
Chris Lattnerdf986172009-01-02 07:01:27 +00002227 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002228 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002229 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002230 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002231 } else {
2232 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002233 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002234 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002235 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002236 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002237 }
2238 ID.Kind = ValID::t_Constant;
2239 return false;
2240 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002241
Chris Lattnerdf986172009-01-02 07:01:27 +00002242 // Binary Operators.
2243 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002244 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002245 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002246 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002247 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002248 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 case lltok::kw_udiv:
2250 case lltok::kw_sdiv:
2251 case lltok::kw_fdiv:
2252 case lltok::kw_urem:
2253 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002254 case lltok::kw_frem:
2255 case lltok::kw_shl:
2256 case lltok::kw_lshr:
2257 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002258 bool NUW = false;
2259 bool NSW = false;
2260 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 unsigned Opc = Lex.getUIntVal();
2262 Constant *Val0, *Val1;
2263 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002264 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002265 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2266 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002267 if (EatIfPresent(lltok::kw_nuw))
2268 NUW = true;
2269 if (EatIfPresent(lltok::kw_nsw)) {
2270 NSW = true;
2271 if (EatIfPresent(lltok::kw_nuw))
2272 NUW = true;
2273 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002274 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2275 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002276 if (EatIfPresent(lltok::kw_exact))
2277 Exact = true;
2278 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2280 ParseGlobalTypeAndValue(Val0) ||
2281 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2282 ParseGlobalTypeAndValue(Val1) ||
2283 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2284 return true;
2285 if (Val0->getType() != Val1->getType())
2286 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002287 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002288 if (NUW)
2289 return Error(ModifierLoc, "nuw only applies to integer operations");
2290 if (NSW)
2291 return Error(ModifierLoc, "nsw only applies to integer operations");
2292 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002293 // Check that the type is valid for the operator.
2294 switch (Opc) {
2295 case Instruction::Add:
2296 case Instruction::Sub:
2297 case Instruction::Mul:
2298 case Instruction::UDiv:
2299 case Instruction::SDiv:
2300 case Instruction::URem:
2301 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002302 case Instruction::Shl:
2303 case Instruction::AShr:
2304 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002305 if (!Val0->getType()->isIntOrIntVectorTy())
2306 return Error(ID.Loc, "constexpr requires integer operands");
2307 break;
2308 case Instruction::FAdd:
2309 case Instruction::FSub:
2310 case Instruction::FMul:
2311 case Instruction::FDiv:
2312 case Instruction::FRem:
2313 if (!Val0->getType()->isFPOrFPVectorTy())
2314 return Error(ID.Loc, "constexpr requires fp operands");
2315 break;
2316 default: llvm_unreachable("Unknown binary operator!");
2317 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002318 unsigned Flags = 0;
2319 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2320 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002321 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002322 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002323 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002324 ID.Kind = ValID::t_Constant;
2325 return false;
2326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002327
Chris Lattnerdf986172009-01-02 07:01:27 +00002328 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002329 case lltok::kw_and:
2330 case lltok::kw_or:
2331 case lltok::kw_xor: {
2332 unsigned Opc = Lex.getUIntVal();
2333 Constant *Val0, *Val1;
2334 Lex.Lex();
2335 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2336 ParseGlobalTypeAndValue(Val0) ||
2337 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2338 ParseGlobalTypeAndValue(Val1) ||
2339 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2340 return true;
2341 if (Val0->getType() != Val1->getType())
2342 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002343 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 return Error(ID.Loc,
2345 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002346 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002347 ID.Kind = ValID::t_Constant;
2348 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002349 }
2350
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 case lltok::kw_getelementptr:
2352 case lltok::kw_shufflevector:
2353 case lltok::kw_insertelement:
2354 case lltok::kw_extractelement:
2355 case lltok::kw_select: {
2356 unsigned Opc = Lex.getUIntVal();
2357 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002358 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002359 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002360 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002361 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002362 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2363 ParseGlobalValueVector(Elts) ||
2364 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2365 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002366
Chris Lattnerdf986172009-01-02 07:01:27 +00002367 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002368 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002369 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002370
Chris Lattnerdf986172009-01-02 07:01:27 +00002371 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002372 (Value**)(Elts.data() + 1),
2373 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002374 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002375 ID.ConstantVal = InBounds ?
2376 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2377 Elts.data() + 1,
2378 Elts.size() - 1) :
2379 ConstantExpr::getGetElementPtr(Elts[0],
2380 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002381 } else if (Opc == Instruction::Select) {
2382 if (Elts.size() != 3)
2383 return Error(ID.Loc, "expected three operands to select");
2384 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2385 Elts[2]))
2386 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002387 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002388 } else if (Opc == Instruction::ShuffleVector) {
2389 if (Elts.size() != 3)
2390 return Error(ID.Loc, "expected three operands to shufflevector");
2391 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2392 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002393 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002394 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002395 } else if (Opc == Instruction::ExtractElement) {
2396 if (Elts.size() != 2)
2397 return Error(ID.Loc, "expected two operands to extractelement");
2398 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2399 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002400 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002401 } else {
2402 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2403 if (Elts.size() != 3)
2404 return Error(ID.Loc, "expected three operands to insertelement");
2405 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2406 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002407 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002408 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdf986172009-01-02 07:01:27 +00002411 ID.Kind = ValID::t_Constant;
2412 return false;
2413 }
2414 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 Lex.Lex();
2417 return false;
2418}
2419
2420/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002421bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2422 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002424 Value *V = NULL;
2425 bool Parsed = ParseValID(ID) ||
2426 ConvertValIDToValue(Ty, ID, V, NULL);
2427 if (V && !(C = dyn_cast<Constant>(V)))
2428 return Error(ID.Loc, "global values must be constants");
2429 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002430}
2431
Victor Hernandez92f238d2010-01-11 22:31:58 +00002432bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2433 PATypeHolder Type(Type::getVoidTy(Context));
2434 return ParseType(Type) ||
2435 ParseGlobalValue(Type, V);
2436}
2437
2438/// ParseGlobalValueVector
2439/// ::= /*empty*/
2440/// ::= TypeAndValue (',' TypeAndValue)*
2441bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2442 // Empty list.
2443 if (Lex.getKind() == lltok::rbrace ||
2444 Lex.getKind() == lltok::rsquare ||
2445 Lex.getKind() == lltok::greater ||
2446 Lex.getKind() == lltok::rparen)
2447 return false;
2448
2449 Constant *C;
2450 if (ParseGlobalTypeAndValue(C)) return true;
2451 Elts.push_back(C);
2452
2453 while (EatIfPresent(lltok::comma)) {
2454 if (ParseGlobalTypeAndValue(C)) return true;
2455 Elts.push_back(C);
2456 }
2457
2458 return false;
2459}
2460
Dan Gohman309b3af2010-08-24 02:24:03 +00002461bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2462 assert(Lex.getKind() == lltok::lbrace);
2463 Lex.Lex();
2464
2465 SmallVector<Value*, 16> Elts;
2466 if (ParseMDNodeVector(Elts, PFS) ||
2467 ParseToken(lltok::rbrace, "expected end of metadata node"))
2468 return true;
2469
Jay Foadec9186b2011-04-21 19:59:31 +00002470 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002471 ID.Kind = ValID::t_MDNode;
2472 return false;
2473}
2474
Dan Gohman83448032010-07-14 18:26:50 +00002475/// ParseMetadataValue
2476/// ::= !42
2477/// ::= !{...}
2478/// ::= !"string"
2479bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2480 assert(Lex.getKind() == lltok::exclaim);
2481 Lex.Lex();
2482
2483 // MDNode:
2484 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002485 if (Lex.getKind() == lltok::lbrace)
2486 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002487
2488 // Standalone metadata reference
2489 // !42
2490 if (Lex.getKind() == lltok::APSInt) {
2491 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2492 ID.Kind = ValID::t_MDNode;
2493 return false;
2494 }
2495
2496 // MDString:
2497 // ::= '!' STRINGCONSTANT
2498 if (ParseMDString(ID.MDStringVal)) return true;
2499 ID.Kind = ValID::t_MDString;
2500 return false;
2501}
2502
Victor Hernandez92f238d2010-01-11 22:31:58 +00002503
2504//===----------------------------------------------------------------------===//
2505// Function Parsing.
2506//===----------------------------------------------------------------------===//
2507
2508bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2509 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002510 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002511 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002512
Chris Lattnerdf986172009-01-02 07:01:27 +00002513 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002514 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002515 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002516 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2517 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2518 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002520 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2521 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2522 return (V == 0);
2523 case ValID::t_InlineAsm: {
2524 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2525 const FunctionType *FTy =
2526 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2527 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2528 return Error(ID.Loc, "invalid type for inline asm constraint string");
2529 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2530 return false;
2531 }
2532 case ValID::t_MDNode:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2535 V = ID.MDNodeVal;
2536 return false;
2537 case ValID::t_MDString:
2538 if (!Ty->isMetadataTy())
2539 return Error(ID.Loc, "metadata value must have metadata type");
2540 V = ID.MDStringVal;
2541 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002542 case ValID::t_GlobalName:
2543 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2544 return V == 0;
2545 case ValID::t_GlobalID:
2546 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2547 return V == 0;
2548 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002549 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002550 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002551 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002552 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002553 return false;
2554 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002555 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002556 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2557 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002558
Chris Lattnerdf986172009-01-02 07:01:27 +00002559 // The lexer has no type info, so builds all float and double FP constants
2560 // as double. Fix this here. Long double does not need this.
2561 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002562 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002563 bool Ignored;
2564 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2565 &Ignored);
2566 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002567 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002568
Chris Lattner959873d2009-01-05 18:24:23 +00002569 if (V->getType() != Ty)
2570 return Error(ID.Loc, "floating point constant does not have type '" +
2571 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Chris Lattnerdf986172009-01-02 07:01:27 +00002573 return false;
2574 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002575 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002576 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002577 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002578 return false;
2579 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002580 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002581 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002582 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002583 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002584 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002586 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002587 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002588 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002589 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002590 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002592 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002593 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002595 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002596 return false;
2597 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002598 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002599 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002600
Chris Lattnerdf986172009-01-02 07:01:27 +00002601 V = ID.ConstantVal;
2602 return false;
2603 }
2604}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002605
Chris Lattnerdf986172009-01-02 07:01:27 +00002606bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2607 V = 0;
2608 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002609 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002610 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002611}
2612
2613bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002614 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002615 return ParseType(T) ||
2616 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002617}
2618
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002619bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2620 PerFunctionState &PFS) {
2621 Value *V;
2622 Loc = Lex.getLoc();
2623 if (ParseTypeAndValue(V, PFS)) return true;
2624 if (!isa<BasicBlock>(V))
2625 return Error(Loc, "expected a basic block");
2626 BB = cast<BasicBlock>(V);
2627 return false;
2628}
2629
2630
Chris Lattnerdf986172009-01-02 07:01:27 +00002631/// FunctionHeader
2632/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002633/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002634/// OptionalAlign OptGC
2635bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2636 // Parse the linkage.
2637 LocTy LinkageLoc = Lex.getLoc();
2638 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002639
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002640 unsigned Visibility, RetAttrs;
2641 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002642 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002643 LocTy RetTypeLoc = Lex.getLoc();
2644 if (ParseOptionalLinkage(Linkage) ||
2645 ParseOptionalVisibility(Visibility) ||
2646 ParseOptionalCallingConv(CC) ||
2647 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002648 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 return true;
2650
2651 // Verify that the linkage is ok.
2652 switch ((GlobalValue::LinkageTypes)Linkage) {
2653 case GlobalValue::ExternalLinkage:
2654 break; // always ok.
2655 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002656 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002657 if (isDefine)
2658 return Error(LinkageLoc, "invalid linkage for function definition");
2659 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002660 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002661 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002662 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002663 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002664 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002665 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002666 case GlobalValue::LinkOnceAnyLinkage:
2667 case GlobalValue::LinkOnceODRLinkage:
2668 case GlobalValue::WeakAnyLinkage:
2669 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002670 case GlobalValue::DLLExportLinkage:
2671 if (!isDefine)
2672 return Error(LinkageLoc, "invalid linkage for function declaration");
2673 break;
2674 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002675 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 return Error(LinkageLoc, "invalid function linkage type");
2677 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002678
Chris Lattner99bb3152009-01-05 08:00:30 +00002679 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002680 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002681 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002682
Chris Lattnerdf986172009-01-02 07:01:27 +00002683 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002684
2685 std::string FunctionName;
2686 if (Lex.getKind() == lltok::GlobalVar) {
2687 FunctionName = Lex.getStrVal();
2688 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2689 unsigned NameID = Lex.getUIntVal();
2690
2691 if (NameID != NumberedVals.size())
2692 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002693 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002694 } else {
2695 return TokError("expected function name");
2696 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002698 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002700 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002701 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002702
Chris Lattnerdf986172009-01-02 07:01:27 +00002703 std::vector<ArgInfo> ArgList;
2704 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002705 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002707 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002708 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002709 bool UnnamedAddr;
2710 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002711
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002712 if (ParseArgumentList(ArgList, isVarArg, false) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002713 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2714 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002715 ParseOptionalAttrs(FuncAttrs, 2) ||
2716 (EatIfPresent(lltok::kw_section) &&
2717 ParseStringConstant(Section)) ||
2718 ParseOptionalAlignment(Alignment) ||
2719 (EatIfPresent(lltok::kw_gc) &&
2720 ParseStringConstant(GC)))
2721 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002722
2723 // If the alignment was parsed as an attribute, move to the alignment field.
2724 if (FuncAttrs & Attribute::Alignment) {
2725 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2726 FuncAttrs &= ~Attribute::Alignment;
2727 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Chris Lattnerdf986172009-01-02 07:01:27 +00002729 // Okay, if we got here, the function is syntactically valid. Convert types
2730 // and do semantic checks.
2731 std::vector<const Type*> ParamTypeList;
2732 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002733
Chris Lattnerdf986172009-01-02 07:01:27 +00002734 if (RetAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002736
Chris Lattnerdf986172009-01-02 07:01:27 +00002737 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2738 ParamTypeList.push_back(ArgList[i].Type);
2739 if (ArgList[i].Attrs != Attribute::None)
2740 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2741 }
2742
2743 if (FuncAttrs != Attribute::None)
2744 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2745
2746 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002747
Benjamin Kramerf0127052010-01-05 13:12:22 +00002748 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002749 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2750
Owen Andersonfba933c2009-07-01 23:57:11 +00002751 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002752 FunctionType::get(RetType, ParamTypeList, isVarArg);
2753 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002754
2755 Fn = 0;
2756 if (!FunctionName.empty()) {
2757 // If this was a definition of a forward reference, remove the definition
2758 // from the forward reference table and fill in the forward ref.
2759 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2760 ForwardRefVals.find(FunctionName);
2761 if (FRVI != ForwardRefVals.end()) {
2762 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002763 if (Fn->getType() != PFT)
2764 return Error(FRVI->second.second, "invalid forward reference to "
2765 "function '" + FunctionName + "' with wrong type!");
2766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 ForwardRefVals.erase(FRVI);
2768 } else if ((Fn = M->getFunction(FunctionName))) {
2769 // If this function already exists in the symbol table, then it is
2770 // multiply defined. We accept a few cases for old backwards compat.
2771 // FIXME: Remove this stuff for LLVM 3.0.
2772 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2773 (!Fn->isDeclaration() && isDefine)) {
2774 // If the redefinition has different type or different attributes,
2775 // reject it. If both have bodies, reject it.
2776 return Error(NameLoc, "invalid redefinition of function '" +
2777 FunctionName + "'");
2778 } else if (Fn->isDeclaration()) {
2779 // Make sure to strip off any argument names so we can't get conflicts.
2780 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2781 AI != AE; ++AI)
2782 AI->setName("");
2783 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002784 } else if (M->getNamedValue(FunctionName)) {
2785 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002786 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002787
Dan Gohman41905542009-08-29 23:37:49 +00002788 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 // If this is a definition of a forward referenced function, make sure the
2790 // types agree.
2791 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2792 = ForwardRefValIDs.find(NumberedVals.size());
2793 if (I != ForwardRefValIDs.end()) {
2794 Fn = cast<Function>(I->second.first);
2795 if (Fn->getType() != PFT)
2796 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002797 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 ForwardRefValIDs.erase(I);
2799 }
2800 }
2801
2802 if (Fn == 0)
2803 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2804 else // Move the forward-reference to the correct spot in the module.
2805 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2806
2807 if (FunctionName.empty())
2808 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2811 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2812 Fn->setCallingConv(CC);
2813 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002814 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 Fn->setAlignment(Alignment);
2816 Fn->setSection(Section);
2817 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002818
Chris Lattnerdf986172009-01-02 07:01:27 +00002819 // Add all of the arguments we parsed to the function.
2820 Function::arg_iterator ArgIt = Fn->arg_begin();
2821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002822 // If we run out of arguments in the Function prototype, exit early.
2823 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2824 if (ArgIt == Fn->arg_end()) break;
2825
Chris Lattnerdf986172009-01-02 07:01:27 +00002826 // If the argument has a name, insert it into the argument symbol table.
2827 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattnerdf986172009-01-02 07:01:27 +00002829 // Set the name, if it conflicted, it will be auto-renamed.
2830 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002831
Benjamin Krameraf812352010-10-16 11:28:23 +00002832 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002833 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2834 ArgList[i].Name + "'");
2835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002836
Chris Lattnerdf986172009-01-02 07:01:27 +00002837 return false;
2838}
2839
2840
2841/// ParseFunctionBody
2842/// ::= '{' BasicBlock+ '}'
2843/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2844///
2845bool LLParser::ParseFunctionBody(Function &Fn) {
2846 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2847 return TokError("expected '{' in function body");
2848 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002849
Chris Lattner09d9ef42009-10-28 03:39:23 +00002850 int FunctionNumber = -1;
2851 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2852
2853 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002854
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002855 // We need at least one basic block.
2856 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2857 return TokError("function body requires at least one basic block");
2858
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2860 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002861
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 // Eat the }.
2863 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002864
Chris Lattnerdf986172009-01-02 07:01:27 +00002865 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002866 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002867}
2868
2869/// ParseBasicBlock
2870/// ::= LabelStr? Instruction*
2871bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2872 // If this basic block starts out with a name, remember it.
2873 std::string Name;
2874 LocTy NameLoc = Lex.getLoc();
2875 if (Lex.getKind() == lltok::LabelStr) {
2876 Name = Lex.getStrVal();
2877 Lex.Lex();
2878 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002879
Chris Lattnerdf986172009-01-02 07:01:27 +00002880 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2881 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882
Chris Lattnerdf986172009-01-02 07:01:27 +00002883 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002884
Chris Lattnerdf986172009-01-02 07:01:27 +00002885 // Parse the instructions in this block until we get a terminator.
2886 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002887 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002888 do {
2889 // This instruction may have three possibilities for a name: a) none
2890 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2891 LocTy NameLoc = Lex.getLoc();
2892 int NameID = -1;
2893 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 if (Lex.getKind() == lltok::LocalVarID) {
2896 NameID = Lex.getUIntVal();
2897 Lex.Lex();
2898 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2899 return true;
2900 } else if (Lex.getKind() == lltok::LocalVar ||
2901 // FIXME: REMOVE IN LLVM 3.0
2902 Lex.getKind() == lltok::StringConstant) {
2903 NameStr = Lex.getStrVal();
2904 Lex.Lex();
2905 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2906 return true;
2907 }
Devang Patelf633a062009-09-17 23:04:48 +00002908
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002909 switch (ParseInstruction(Inst, BB, PFS)) {
2910 default: assert(0 && "Unknown ParseInstruction result!");
2911 case InstError: return true;
2912 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002913 BB->getInstList().push_back(Inst);
2914
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002915 // With a normal result, we check to see if the instruction is followed by
2916 // a comma and metadata.
2917 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002918 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002919 return true;
2920 break;
2921 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002922 BB->getInstList().push_back(Inst);
2923
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002924 // If the instruction parser ate an extra comma at the end of it, it
2925 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002926 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002927 return true;
2928 break;
2929 }
Devang Patelf633a062009-09-17 23:04:48 +00002930
Chris Lattnerdf986172009-01-02 07:01:27 +00002931 // Set the name on the instruction.
2932 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2933 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002934
Chris Lattnerdf986172009-01-02 07:01:27 +00002935 return false;
2936}
2937
2938//===----------------------------------------------------------------------===//
2939// Instruction Parsing.
2940//===----------------------------------------------------------------------===//
2941
2942/// ParseInstruction - Parse one of the many different instructions.
2943///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002944int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2945 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002946 lltok::Kind Token = Lex.getKind();
2947 if (Token == lltok::Eof)
2948 return TokError("found end of file when expecting more instructions");
2949 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002950 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002951 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002952
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 switch (Token) {
2954 default: return Error(Loc, "expected instruction opcode");
2955 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002956 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2957 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2959 case lltok::kw_br: return ParseBr(Inst, PFS);
2960 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002961 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2963 // Binary Operators.
2964 case lltok::kw_add:
2965 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002966 case lltok::kw_mul:
2967 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002968 bool NUW = EatIfPresent(lltok::kw_nuw);
2969 bool NSW = EatIfPresent(lltok::kw_nsw);
2970 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2971
2972 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2973
2974 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2975 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2976 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002977 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002978 case lltok::kw_fadd:
2979 case lltok::kw_fsub:
2980 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2981
Chris Lattner35bda892011-02-06 21:44:57 +00002982 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002983 case lltok::kw_udiv:
2984 case lltok::kw_lshr:
2985 case lltok::kw_ashr: {
2986 bool Exact = EatIfPresent(lltok::kw_exact);
2987
2988 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2989 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2990 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002991 }
2992
Chris Lattnerdf986172009-01-02 07:01:27 +00002993 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002994 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002995 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002996 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002997 case lltok::kw_and:
2998 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002999 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003000 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003001 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003002 // Casts.
3003 case lltok::kw_trunc:
3004 case lltok::kw_zext:
3005 case lltok::kw_sext:
3006 case lltok::kw_fptrunc:
3007 case lltok::kw_fpext:
3008 case lltok::kw_bitcast:
3009 case lltok::kw_uitofp:
3010 case lltok::kw_sitofp:
3011 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003012 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003014 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003015 // Other.
3016 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003017 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003018 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3019 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3020 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3021 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3022 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3023 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3024 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003025 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003026 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3027 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3028 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003029 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003030 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003031 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003033 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003034 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3036 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3037 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3038 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3039 }
3040}
3041
3042/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3043bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003044 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003045 switch (Lex.getKind()) {
3046 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3047 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3048 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3049 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3050 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3051 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3052 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3053 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3054 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3055 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3056 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3057 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3058 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3059 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3060 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3061 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3062 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3063 }
3064 } else {
3065 switch (Lex.getKind()) {
3066 default: TokError("expected icmp predicate (e.g. 'eq')");
3067 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3068 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3069 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3070 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3071 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3072 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3073 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3074 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3075 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3076 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3077 }
3078 }
3079 Lex.Lex();
3080 return false;
3081}
3082
3083//===----------------------------------------------------------------------===//
3084// Terminator Instructions.
3085//===----------------------------------------------------------------------===//
3086
3087/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003088/// ::= 'ret' void (',' !dbg, !1)*
3089/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3090/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003091/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003092int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3093 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003094 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003095 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003096
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003097 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003098 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 return false;
3100 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003101
Chris Lattnerdf986172009-01-02 07:01:27 +00003102 Value *RV;
3103 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003104
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003105 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003106 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003107 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003108 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003109 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003110 } else {
3111 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003112 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3113 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003114 SmallVector<Value*, 8> RVs;
3115 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003116
Devang Patelf633a062009-09-17 23:04:48 +00003117 do {
Devang Patel0475c912009-09-29 00:01:14 +00003118 // If optional custom metadata, e.g. !dbg is seen then this is the
3119 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003120 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003121 break;
3122 if (ParseTypeAndValue(RV, PFS)) return true;
3123 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003124 } while (EatIfPresent(lltok::comma));
3125
3126 RV = UndefValue::get(PFS.getFunction().getReturnType());
3127 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003128 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3129 BB->getInstList().push_back(I);
3130 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003131 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003132 }
3133 }
Devang Patelf633a062009-09-17 23:04:48 +00003134
Owen Anderson1d0be152009-08-13 21:58:54 +00003135 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003136 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003137}
3138
3139
3140/// ParseBr
3141/// ::= 'br' TypeAndValue
3142/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3143bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3144 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003145 Value *Op0;
3146 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003147 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerdf986172009-01-02 07:01:27 +00003149 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3150 Inst = BranchInst::Create(BB);
3151 return false;
3152 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003153
Owen Anderson1d0be152009-08-13 21:58:54 +00003154 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003155 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003156
Chris Lattnerdf986172009-01-02 07:01:27 +00003157 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003158 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003159 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003160 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003161 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003162
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003163 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003164 return false;
3165}
3166
3167/// ParseSwitch
3168/// Instruction
3169/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3170/// JumpTable
3171/// ::= (TypeAndValue ',' TypeAndValue)*
3172bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3173 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003174 Value *Cond;
3175 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003176 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3177 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003178 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003179 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3180 return true;
3181
Duncan Sands1df98592010-02-16 11:11:14 +00003182 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003184
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 // Parse the jump table pairs.
3186 SmallPtrSet<Value*, 32> SeenCases;
3187 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3188 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003189 Value *Constant;
3190 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003191
Chris Lattnerdf986172009-01-02 07:01:27 +00003192 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3193 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003194 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003195 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003196
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 if (!SeenCases.insert(Constant))
3198 return Error(CondLoc, "duplicate case value in switch");
3199 if (!isa<ConstantInt>(Constant))
3200 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003202 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003203 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003204
Chris Lattnerdf986172009-01-02 07:01:27 +00003205 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003206
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003207 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003208 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3209 SI->addCase(Table[i].first, Table[i].second);
3210 Inst = SI;
3211 return false;
3212}
3213
Chris Lattnerab21db72009-10-28 00:19:10 +00003214/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003215/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003216/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3217bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003218 LocTy AddrLoc;
3219 Value *Address;
3220 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003221 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3222 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223 return true;
3224
Duncan Sands1df98592010-02-16 11:11:14 +00003225 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003226 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003227
3228 // Parse the destination list.
3229 SmallVector<BasicBlock*, 16> DestList;
3230
3231 if (Lex.getKind() != lltok::rsquare) {
3232 BasicBlock *DestBB;
3233 if (ParseTypeAndBasicBlock(DestBB, PFS))
3234 return true;
3235 DestList.push_back(DestBB);
3236
3237 while (EatIfPresent(lltok::comma)) {
3238 if (ParseTypeAndBasicBlock(DestBB, PFS))
3239 return true;
3240 DestList.push_back(DestBB);
3241 }
3242 }
3243
3244 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3245 return true;
3246
Chris Lattnerab21db72009-10-28 00:19:10 +00003247 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003248 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3249 IBI->addDestination(DestList[i]);
3250 Inst = IBI;
3251 return false;
3252}
3253
3254
Chris Lattnerdf986172009-01-02 07:01:27 +00003255/// ParseInvoke
3256/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3257/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3258bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3259 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003260 unsigned RetAttrs, FnAttrs;
3261 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003262 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 LocTy RetTypeLoc;
3264 ValID CalleeID;
3265 SmallVector<ParamInfo, 16> ArgList;
3266
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 if (ParseOptionalCallingConv(CC) ||
3269 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003270 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003271 ParseValID(CalleeID) ||
3272 ParseParameterList(ArgList, PFS) ||
3273 ParseOptionalAttrs(FnAttrs, 2) ||
3274 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003275 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003277 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003278 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003279
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 // If RetType is a non-function pointer type, then this is the short syntax
3281 // for the call, which means that RetType is just the return type. Infer the
3282 // rest of the function argument types from the arguments that are present.
3283 const PointerType *PFTy = 0;
3284 const FunctionType *Ty = 0;
3285 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3286 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3287 // Pull out the types of all of the arguments...
3288 std::vector<const Type*> ParamTypes;
3289 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3290 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003291
Chris Lattnerdf986172009-01-02 07:01:27 +00003292 if (!FunctionType::isValidReturnType(RetType))
3293 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003294
Owen Andersondebcb012009-07-29 22:17:13 +00003295 Ty = FunctionType::get(RetType, ParamTypes, false);
3296 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003297 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003298
Chris Lattnerdf986172009-01-02 07:01:27 +00003299 // Look up the callee.
3300 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003301 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003302
Chris Lattnerdf986172009-01-02 07:01:27 +00003303 // Set up the Attributes for the function.
3304 SmallVector<AttributeWithIndex, 8> Attrs;
3305 if (RetAttrs != Attribute::None)
3306 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003307
Chris Lattnerdf986172009-01-02 07:01:27 +00003308 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003309
Chris Lattnerdf986172009-01-02 07:01:27 +00003310 // Loop through FunctionType's arguments and ensure they are specified
3311 // correctly. Also, gather any parameter attributes.
3312 FunctionType::param_iterator I = Ty->param_begin();
3313 FunctionType::param_iterator E = Ty->param_end();
3314 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3315 const Type *ExpectedTy = 0;
3316 if (I != E) {
3317 ExpectedTy = *I++;
3318 } else if (!Ty->isVarArg()) {
3319 return Error(ArgList[i].Loc, "too many arguments specified");
3320 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003321
Chris Lattnerdf986172009-01-02 07:01:27 +00003322 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3323 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3324 ExpectedTy->getDescription() + "'");
3325 Args.push_back(ArgList[i].V);
3326 if (ArgList[i].Attrs != Attribute::None)
3327 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003329
Chris Lattnerdf986172009-01-02 07:01:27 +00003330 if (I != E)
3331 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 if (FnAttrs != Attribute::None)
3334 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003335
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 // Finish off the Attributes and check them
3337 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003338
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003339 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003340 Args.begin(), Args.end());
3341 II->setCallingConv(CC);
3342 II->setAttributes(PAL);
3343 Inst = II;
3344 return false;
3345}
3346
3347
3348
3349//===----------------------------------------------------------------------===//
3350// Binary Operators.
3351//===----------------------------------------------------------------------===//
3352
3353/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003354/// ::= ArithmeticOps TypeAndValue ',' Value
3355///
3356/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3357/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003358bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003359 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003360 LocTy Loc; Value *LHS, *RHS;
3361 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3362 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3363 ParseValue(LHS->getType(), RHS, PFS))
3364 return true;
3365
Chris Lattnere914b592009-01-05 08:24:46 +00003366 bool Valid;
3367 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003368 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003369 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003370 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3371 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003372 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003373 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3374 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003376
Chris Lattnere914b592009-01-05 08:24:46 +00003377 if (!Valid)
3378 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003379
Chris Lattnerdf986172009-01-02 07:01:27 +00003380 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3381 return false;
3382}
3383
3384/// ParseLogical
3385/// ::= ArithmeticOps TypeAndValue ',' Value {
3386bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3387 unsigned Opc) {
3388 LocTy Loc; Value *LHS, *RHS;
3389 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3390 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3391 ParseValue(LHS->getType(), RHS, PFS))
3392 return true;
3393
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003394 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 return Error(Loc,"instruction requires integer or integer vector operands");
3396
3397 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3398 return false;
3399}
3400
3401
3402/// ParseCompare
3403/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3404/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003405bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3406 unsigned Opc) {
3407 // Parse the integer/fp comparison predicate.
3408 LocTy Loc;
3409 unsigned Pred;
3410 Value *LHS, *RHS;
3411 if (ParseCmpPredicate(Pred, Opc) ||
3412 ParseTypeAndValue(LHS, Loc, PFS) ||
3413 ParseToken(lltok::comma, "expected ',' after compare value") ||
3414 ParseValue(LHS->getType(), RHS, PFS))
3415 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003416
Chris Lattnerdf986172009-01-02 07:01:27 +00003417 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003418 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003419 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003421 } else {
3422 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003423 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003424 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003426 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003427 }
3428 return false;
3429}
3430
3431//===----------------------------------------------------------------------===//
3432// Other Instructions.
3433//===----------------------------------------------------------------------===//
3434
3435
3436/// ParseCast
3437/// ::= CastOpc TypeAndValue 'to' Type
3438bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3439 unsigned Opc) {
3440 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003441 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 if (ParseTypeAndValue(Op, Loc, PFS) ||
3443 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3444 ParseType(DestTy))
3445 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003446
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003447 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3448 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003449 return Error(Loc, "invalid cast opcode for cast from '" +
3450 Op->getType()->getDescription() + "' to '" +
3451 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003452 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003453 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3454 return false;
3455}
3456
3457/// ParseSelect
3458/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3459bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3460 LocTy Loc;
3461 Value *Op0, *Op1, *Op2;
3462 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3463 ParseToken(lltok::comma, "expected ',' after select condition") ||
3464 ParseTypeAndValue(Op1, PFS) ||
3465 ParseToken(lltok::comma, "expected ',' after select value") ||
3466 ParseTypeAndValue(Op2, PFS))
3467 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003468
Chris Lattnerdf986172009-01-02 07:01:27 +00003469 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3470 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003471
Chris Lattnerdf986172009-01-02 07:01:27 +00003472 Inst = SelectInst::Create(Op0, Op1, Op2);
3473 return false;
3474}
3475
Chris Lattner0088a5c2009-01-05 08:18:44 +00003476/// ParseVA_Arg
3477/// ::= 'va_arg' TypeAndValue ',' Type
3478bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003479 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003480 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003481 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003482 if (ParseTypeAndValue(Op, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003484 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003485 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003486
Chris Lattner0088a5c2009-01-05 08:18:44 +00003487 if (!EltTy->isFirstClassType())
3488 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003489
3490 Inst = new VAArgInst(Op, EltTy);
3491 return false;
3492}
3493
3494/// ParseExtractElement
3495/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3496bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3497 LocTy Loc;
3498 Value *Op0, *Op1;
3499 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after extract value") ||
3501 ParseTypeAndValue(Op1, PFS))
3502 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003503
Chris Lattnerdf986172009-01-02 07:01:27 +00003504 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3505 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003506
Eric Christophera3500da2009-07-25 02:28:41 +00003507 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003508 return false;
3509}
3510
3511/// ParseInsertElement
3512/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3514 LocTy Loc;
3515 Value *Op0, *Op1, *Op2;
3516 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3518 ParseTypeAndValue(Op1, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3520 ParseTypeAndValue(Op2, PFS))
3521 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003522
Chris Lattnerdf986172009-01-02 07:01:27 +00003523 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003524 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003525
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3527 return false;
3528}
3529
3530/// ParseShuffleVector
3531/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3532bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3533 LocTy Loc;
3534 Value *Op0, *Op1, *Op2;
3535 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3537 ParseTypeAndValue(Op1, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3539 ParseTypeAndValue(Op2, PFS))
3540 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003541
Chris Lattnerdf986172009-01-02 07:01:27 +00003542 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3543 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3546 return false;
3547}
3548
3549/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003550/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003551int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003552 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003553 Value *Op0, *Op1;
3554 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003555
Chris Lattnerdf986172009-01-02 07:01:27 +00003556 if (ParseType(Ty) ||
3557 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3558 ParseValue(Ty, Op0, PFS) ||
3559 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003560 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003561 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3562 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003563
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003564 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003565 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3566 while (1) {
3567 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003568
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003569 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003570 break;
3571
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003572 if (Lex.getKind() == lltok::MetadataVar) {
3573 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003574 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003575 }
Devang Patela43d46f2009-10-16 18:45:49 +00003576
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003577 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 ParseValue(Ty, Op0, PFS) ||
3579 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003580 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3582 return true;
3583 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003584
Chris Lattnerdf986172009-01-02 07:01:27 +00003585 if (!Ty->isFirstClassType())
3586 return Error(TypeLoc, "phi node must have first class type");
3587
Jay Foad3ecfc862011-03-30 11:28:46 +00003588 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003589 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3590 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3591 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003592 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003593}
3594
3595/// ParseCall
3596/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3597/// ParameterList OptionalAttrs
3598bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3599 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003600 unsigned RetAttrs, FnAttrs;
3601 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003602 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 LocTy RetTypeLoc;
3604 ValID CalleeID;
3605 SmallVector<ParamInfo, 16> ArgList;
3606 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003607
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3609 ParseOptionalCallingConv(CC) ||
3610 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003611 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003612 ParseValID(CalleeID) ||
3613 ParseParameterList(ArgList, PFS) ||
3614 ParseOptionalAttrs(FnAttrs, 2))
3615 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003616
Chris Lattnerdf986172009-01-02 07:01:27 +00003617 // If RetType is a non-function pointer type, then this is the short syntax
3618 // for the call, which means that RetType is just the return type. Infer the
3619 // rest of the function argument types from the arguments that are present.
3620 const PointerType *PFTy = 0;
3621 const FunctionType *Ty = 0;
3622 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3623 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3624 // Pull out the types of all of the arguments...
3625 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003626 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3627 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003628
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 if (!FunctionType::isValidReturnType(RetType))
3630 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003631
Owen Andersondebcb012009-07-29 22:17:13 +00003632 Ty = FunctionType::get(RetType, ParamTypes, false);
3633 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003635
Chris Lattnerdf986172009-01-02 07:01:27 +00003636 // Look up the callee.
3637 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003638 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003639
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 // Set up the Attributes for the function.
3641 SmallVector<AttributeWithIndex, 8> Attrs;
3642 if (RetAttrs != Attribute::None)
3643 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003644
Chris Lattnerdf986172009-01-02 07:01:27 +00003645 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003646
Chris Lattnerdf986172009-01-02 07:01:27 +00003647 // Loop through FunctionType's arguments and ensure they are specified
3648 // correctly. Also, gather any parameter attributes.
3649 FunctionType::param_iterator I = Ty->param_begin();
3650 FunctionType::param_iterator E = Ty->param_end();
3651 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3652 const Type *ExpectedTy = 0;
3653 if (I != E) {
3654 ExpectedTy = *I++;
3655 } else if (!Ty->isVarArg()) {
3656 return Error(ArgList[i].Loc, "too many arguments specified");
3657 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003658
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3660 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3661 ExpectedTy->getDescription() + "'");
3662 Args.push_back(ArgList[i].V);
3663 if (ArgList[i].Attrs != Attribute::None)
3664 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3665 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003666
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 if (I != E)
3668 return Error(CallLoc, "not enough parameters specified for call");
3669
3670 if (FnAttrs != Attribute::None)
3671 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3672
3673 // Finish off the Attributes and check them
3674 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003675
Chris Lattnerdf986172009-01-02 07:01:27 +00003676 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3677 CI->setTailCall(isTail);
3678 CI->setCallingConv(CC);
3679 CI->setAttributes(PAL);
3680 Inst = CI;
3681 return false;
3682}
3683
3684//===----------------------------------------------------------------------===//
3685// Memory Instructions.
3686//===----------------------------------------------------------------------===//
3687
3688/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003689/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003690int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003691 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003692 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003693 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003694 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003695 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003696
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003697 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003698 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003699 if (Lex.getKind() == lltok::kw_align) {
3700 if (ParseOptionalAlignment(Alignment)) return true;
3701 } else if (Lex.getKind() == lltok::MetadataVar) {
3702 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003703 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003704 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3705 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3706 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003707 }
3708 }
3709
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003710 if (Size && !Size->getType()->isIntegerTy())
3711 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003712
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003713 Inst = new AllocaInst(Ty, Size, Alignment);
3714 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003715}
3716
3717/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003718/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003719int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3720 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003721 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003722 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003723 bool AteExtraComma = false;
3724 if (ParseTypeAndValue(Val, Loc, PFS) ||
3725 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3726 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003727
Duncan Sands1df98592010-02-16 11:11:14 +00003728 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3730 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003731
Chris Lattnerdf986172009-01-02 07:01:27 +00003732 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003733 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003734}
3735
3736/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003737/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003738int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3739 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003740 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003741 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003742 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003743 if (ParseTypeAndValue(Val, Loc, PFS) ||
3744 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003745 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3746 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003747 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003748
Duncan Sands1df98592010-02-16 11:11:14 +00003749 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003750 return Error(PtrLoc, "store operand must be a pointer");
3751 if (!Val->getType()->isFirstClassType())
3752 return Error(Loc, "store operand must be a first class value");
3753 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3754 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003755
Chris Lattnerdf986172009-01-02 07:01:27 +00003756 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003757 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003758}
3759
3760/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003761/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003762/// FIXME: Remove support for getresult in LLVM 3.0
3763bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3764 Value *Val; LocTy ValLoc, EltLoc;
3765 unsigned Element;
3766 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3767 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003768 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003769 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003770
Duncan Sands1df98592010-02-16 11:11:14 +00003771 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003772 return Error(ValLoc, "getresult inst requires an aggregate operand");
3773 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3774 return Error(EltLoc, "invalid getresult index for value");
3775 Inst = ExtractValueInst::Create(Val, Element);
3776 return false;
3777}
3778
3779/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003780/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003781int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003782 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003783
Dan Gohmandcb40a32009-07-29 15:58:36 +00003784 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003785
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003786 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003787
Duncan Sands1df98592010-02-16 11:11:14 +00003788 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003789 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003790
Chris Lattnerdf986172009-01-02 07:01:27 +00003791 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003792 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003793 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003794 if (Lex.getKind() == lltok::MetadataVar) {
3795 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003796 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003797 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003798 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003799 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003800 return Error(EltLoc, "getelementptr index must be an integer");
3801 Indices.push_back(Val);
3802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003803
Chris Lattnerdf986172009-01-02 07:01:27 +00003804 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3805 Indices.begin(), Indices.end()))
3806 return Error(Loc, "invalid getelementptr indices");
3807 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003808 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003809 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003810 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003811}
3812
3813/// ParseExtractValue
3814/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003815int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003816 Value *Val; LocTy Loc;
3817 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003818 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003819 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003820 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003821 return true;
3822
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003823 if (!Val->getType()->isAggregateType())
3824 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003825
3826 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3827 Indices.end()))
3828 return Error(Loc, "invalid indices for extractvalue");
3829 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003830 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003831}
3832
3833/// ParseInsertValue
3834/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003835int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003836 Value *Val0, *Val1; LocTy Loc0, Loc1;
3837 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003838 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003839 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3840 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3841 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003842 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003843 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003844
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003845 if (!Val0->getType()->isAggregateType())
3846 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003847
Chris Lattnerdf986172009-01-02 07:01:27 +00003848 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3849 Indices.end()))
3850 return Error(Loc0, "invalid indices for insertvalue");
3851 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003852 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003853}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003854
3855//===----------------------------------------------------------------------===//
3856// Embedded metadata.
3857//===----------------------------------------------------------------------===//
3858
3859/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003860/// ::= Element (',' Element)*
3861/// Element
3862/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003863bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003864 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003865 // Check for an empty list.
3866 if (Lex.getKind() == lltok::rbrace)
3867 return false;
3868
Nick Lewycky21cc4462009-04-04 07:22:01 +00003869 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003870 // Null is a special case since it is typeless.
3871 if (EatIfPresent(lltok::kw_null)) {
3872 Elts.push_back(0);
3873 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003874 }
Chris Lattnera7352392009-12-30 04:42:57 +00003875
3876 Value *V = 0;
3877 PATypeHolder Ty(Type::getVoidTy(Context));
3878 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003879 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003880 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003881 return true;
3882
Nick Lewyckycb337992009-05-10 20:57:05 +00003883 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003884 } while (EatIfPresent(lltok::comma));
3885
3886 return false;
3887}