blob: f0fb310614ab37d5d2b968b0d4b6b96888d0cad6 [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
Victor Hernandez68afa542009-10-21 19:11:40 +000062 // Update auto-upgraded malloc calls to "malloc".
Chris Lattnercf4d2f12009-10-18 05:09:15 +000063 // FIXME: Remove in LLVM 3.0.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000064 if (MallocF) {
65 MallocF->setName("malloc");
66 // If setName() does not set the name to "malloc", then there is already a
67 // declaration of "malloc". In that case, iterate over all calls to MallocF
68 // and get them to call the declared "malloc" instead.
69 if (MallocF->getName() != "malloc") {
Chris Lattner09d9ef42009-10-28 03:39:23 +000070 Constant *RealMallocF = M->getFunction("malloc");
Victor Hernandez68afa542009-10-21 19:11:40 +000071 if (RealMallocF->getType() != MallocF->getType())
72 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
73 MallocF->replaceAllUsesWith(RealMallocF);
Victor Hernandez13ad5aa2009-10-17 00:00:19 +000074 MallocF->eraseFromParent();
75 MallocF = NULL;
76 }
77 }
Chris Lattner09d9ef42009-10-28 03:39:23 +000078
79
80 // If there are entries in ForwardRefBlockAddresses at this point, they are
81 // references after the function was defined. Resolve those now.
82 while (!ForwardRefBlockAddresses.empty()) {
83 // Okay, we are referencing an already-parsed function, resolve them now.
84 Function *TheFn = 0;
85 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
86 if (Fn.Kind == ValID::t_GlobalName)
87 TheFn = M->getFunction(Fn.StrVal);
88 else if (Fn.UIntVal < NumberedVals.size())
89 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
90
91 if (TheFn == 0)
92 return Error(Fn.Loc, "unknown function referenced by blockaddress");
93
94 // Resolve all these references.
95 if (ResolveForwardRefBlockAddresses(TheFn,
96 ForwardRefBlockAddresses.begin()->second,
97 0))
98 return true;
99
100 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
101 }
102
103
Chris Lattnerdf986172009-01-02 07:01:27 +0000104 if (!ForwardRefTypes.empty())
105 return Error(ForwardRefTypes.begin()->second.second,
106 "use of undefined type named '" +
107 ForwardRefTypes.begin()->first + "'");
108 if (!ForwardRefTypeIDs.empty())
109 return Error(ForwardRefTypeIDs.begin()->second.second,
110 "use of undefined type '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000111 Twine(ForwardRefTypeIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Chris Lattnerdf986172009-01-02 07:01:27 +0000113 if (!ForwardRefVals.empty())
114 return Error(ForwardRefVals.begin()->second.second,
115 "use of undefined value '@" + ForwardRefVals.begin()->first +
116 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Chris Lattnerdf986172009-01-02 07:01:27 +0000118 if (!ForwardRefValIDs.empty())
119 return Error(ForwardRefValIDs.begin()->second.second,
120 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000121 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Devang Patel1c7eea62009-07-08 19:23:54 +0000123 if (!ForwardRefMDNodes.empty())
124 return Error(ForwardRefMDNodes.begin()->second.second,
125 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000126 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000127
Devang Patel1c7eea62009-07-08 19:23:54 +0000128
Chris Lattnerdf986172009-01-02 07:01:27 +0000129 // Look for intrinsic functions and CallInst that need to be upgraded
130 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
131 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000132
Devang Patele4b27562009-08-28 23:24:31 +0000133 // Check debug info intrinsics.
134 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000135 return false;
136}
137
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
139 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
140 PerFunctionState *PFS) {
141 // Loop over all the references, resolving them.
142 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
143 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000144 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000145 if (Refs[i].first.Kind == ValID::t_LocalName)
146 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000147 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000148 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
149 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
150 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000151 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000152 } else {
153 Res = dyn_cast_or_null<BasicBlock>(
154 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
155 }
156
Chris Lattnercdfc9402009-11-01 01:27:45 +0000157 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000158 return Error(Refs[i].first.Loc,
159 "referenced value is not a basic block");
160
161 // Get the BlockAddress for this and update references to use it.
162 BlockAddress *BA = BlockAddress::get(TheFn, Res);
163 Refs[i].second->replaceAllUsesWith(BA);
164 Refs[i].second->eraseFromParent();
165 }
166 return false;
167}
168
169
Chris Lattnerdf986172009-01-02 07:01:27 +0000170//===----------------------------------------------------------------------===//
171// Top-Level Entities
172//===----------------------------------------------------------------------===//
173
174bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 while (1) {
176 switch (Lex.getKind()) {
177 default: return TokError("expected top-level entity");
178 case lltok::Eof: return false;
179 //case lltok::kw_define:
180 case lltok::kw_declare: if (ParseDeclare()) return true; break;
181 case lltok::kw_define: if (ParseDefine()) return true; break;
182 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
183 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
184 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
185 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000186 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000187 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
188 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000189 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000190 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000191 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000192 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000193
194 // The Global variable production with no name can have many different
195 // optional leading prefixes, the production is:
196 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000197 // OptionalAddrSpace OptionalUnNammedAddr
198 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000202 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000203 case lltok::kw_internal: // OptionalLinkage
204 case lltok::kw_weak: // OptionalLinkage
205 case lltok::kw_weak_odr: // OptionalLinkage
206 case lltok::kw_linkonce: // OptionalLinkage
207 case lltok::kw_linkonce_odr: // OptionalLinkage
208 case lltok::kw_appending: // OptionalLinkage
209 case lltok::kw_dllexport: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_dllimport: // OptionalLinkage
212 case lltok::kw_extern_weak: // OptionalLinkage
213 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 unsigned Linkage, Visibility;
215 if (ParseOptionalLinkage(Linkage) ||
216 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000217 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 return true;
219 break;
220 }
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: { // OptionalVisibility
224 unsigned Visibility;
225 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000226 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000227 return true;
228 break;
229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattnerdf986172009-01-02 07:01:27 +0000231 case lltok::kw_thread_local: // OptionalThreadLocal
232 case lltok::kw_addrspace: // OptionalAddrSpace
233 case lltok::kw_constant: // GlobalType
234 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000235 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000236 break;
237 }
238 }
239}
240
241
242/// toplevelentity
243/// ::= 'module' 'asm' STRINGCONSTANT
244bool LLParser::ParseModuleAsm() {
245 assert(Lex.getKind() == lltok::kw_module);
246 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
248 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000249 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000251
Chris Lattnerdf986172009-01-02 07:01:27 +0000252 const std::string &AsmSoFar = M->getModuleInlineAsm();
253 if (AsmSoFar.empty())
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 else
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258}
259
260/// toplevelentity
261/// ::= 'target' 'triple' '=' STRINGCONSTANT
262/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000265 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000266 switch (Lex.Lex()) {
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
269 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000272 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000273 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000274 return false;
275 case lltok::kw_datalayout:
276 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000279 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000280 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000281 return false;
282 }
283}
284
285/// toplevelentity
286/// ::= 'deplibs' '=' '[' ']'
287/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288bool LLParser::ParseDepLibs() {
289 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000290 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000291 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
292 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
293 return true;
294
295 if (EatIfPresent(lltok::rsquare))
296 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000298 std::string Str;
299 if (ParseStringConstant(Str)) return true;
300 M->addLibrary(Str);
301
302 while (EatIfPresent(lltok::comma)) {
303 if (ParseStringConstant(Str)) return true;
304 M->addLibrary(Str);
305 }
306
307 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000308}
309
Dan Gohman3845e502009-08-12 23:32:33 +0000310/// ParseUnnamedType:
Chris Lattnerdf986172009-01-02 07:01:27 +0000311/// ::= 'type' type
Dan Gohman3845e502009-08-12 23:32:33 +0000312/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000313bool LLParser::ParseUnnamedType() {
Dan Gohman3845e502009-08-12 23:32:33 +0000314 unsigned TypeID = NumberedTypes.size();
315
316 // Handle the LocalVarID form.
317 if (Lex.getKind() == lltok::LocalVarID) {
318 if (Lex.getUIntVal() != TypeID)
319 return Error(Lex.getLoc(), "type expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000320 Twine(TypeID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000321 Lex.Lex(); // eat LocalVarID;
322
323 if (ParseToken(lltok::equal, "expected '=' after name"))
324 return true;
325 }
326
Chris Lattnerdf986172009-01-02 07:01:27 +0000327 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerf7240de2010-04-10 18:01:25 +0000328 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000329
Owen Anderson1d0be152009-08-13 21:58:54 +0000330 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000331 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000332
Chris Lattnerdf986172009-01-02 07:01:27 +0000333 // See if this type was previously referenced.
334 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
335 FI = ForwardRefTypeIDs.find(TypeID);
336 if (FI != ForwardRefTypeIDs.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000337 if (FI->second.first.get() == Ty)
338 return Error(TypeLoc, "self referential type is invalid");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339
Chris Lattnerdf986172009-01-02 07:01:27 +0000340 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
341 Ty = FI->second.first.get();
342 ForwardRefTypeIDs.erase(FI);
343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344
Chris Lattnerdf986172009-01-02 07:01:27 +0000345 NumberedTypes.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000346
Chris Lattnerdf986172009-01-02 07:01:27 +0000347 return false;
348}
349
350/// toplevelentity
351/// ::= LocalVar '=' 'type' type
352bool LLParser::ParseNamedType() {
353 std::string Name = Lex.getStrVal();
354 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000355 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000356
Owen Anderson1d0be152009-08-13 21:58:54 +0000357 PATypeHolder Ty(Type::getVoidTy(Context));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000358
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after name") ||
361 ParseType(Ty))
362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000363
Chris Lattnerdf986172009-01-02 07:01:27 +0000364 // Set the type name, checking for conflicts as we do so.
365 bool AlreadyExists = M->addTypeName(Name, Ty);
366 if (!AlreadyExists) return false;
367
368 // See if this type is a forward reference. We need to eagerly resolve
369 // types to allow recursive type redefinitions below.
370 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
371 FI = ForwardRefTypes.find(Name);
372 if (FI != ForwardRefTypes.end()) {
Chris Lattnerc38daba2009-01-05 18:19:46 +0000373 if (FI->second.first.get() == Ty)
374 return Error(NameLoc, "self referential type is invalid");
375
Chris Lattnerdf986172009-01-02 07:01:27 +0000376 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
377 Ty = FI->second.first.get();
378 ForwardRefTypes.erase(FI);
379 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 // Inserting a name that is already defined, get the existing name.
382 const Type *Existing = M->getTypeByName(Name);
383 assert(Existing && "Conflict but no matching type?!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Chris Lattnerdf986172009-01-02 07:01:27 +0000385 // Otherwise, this is an attempt to redefine a type. That's okay if
386 // the redefinition is identical to the original.
387 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
388 if (Existing == Ty) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Chris Lattnerdf986172009-01-02 07:01:27 +0000390 // Any other kind of (non-equivalent) redefinition is an error.
391 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
392 Ty->getDescription() + "'");
393}
394
395
396/// toplevelentity
397/// ::= 'declare' FunctionHeader
398bool LLParser::ParseDeclare() {
399 assert(Lex.getKind() == lltok::kw_declare);
400 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Chris Lattnerdf986172009-01-02 07:01:27 +0000402 Function *F;
403 return ParseFunctionHeader(F, false);
404}
405
406/// toplevelentity
407/// ::= 'define' FunctionHeader '{' ...
408bool LLParser::ParseDefine() {
409 assert(Lex.getKind() == lltok::kw_define);
410 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Chris Lattnerdf986172009-01-02 07:01:27 +0000412 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000413 return ParseFunctionHeader(F, true) ||
414 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000415}
416
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000417/// ParseGlobalType
418/// ::= 'constant'
419/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000420bool LLParser::ParseGlobalType(bool &IsConstant) {
421 if (Lex.getKind() == lltok::kw_constant)
422 IsConstant = true;
423 else if (Lex.getKind() == lltok::kw_global)
424 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000425 else {
426 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000427 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000428 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000429 Lex.Lex();
430 return false;
431}
432
Dan Gohman3845e502009-08-12 23:32:33 +0000433/// ParseUnnamedGlobal:
434/// OptionalVisibility ALIAS ...
435/// OptionalLinkage OptionalVisibility ... -> global variable
436/// GlobalID '=' OptionalVisibility ALIAS ...
437/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
438bool LLParser::ParseUnnamedGlobal() {
439 unsigned VarID = NumberedVals.size();
440 std::string Name;
441 LocTy NameLoc = Lex.getLoc();
442
443 // Handle the GlobalID form.
444 if (Lex.getKind() == lltok::GlobalID) {
445 if (Lex.getUIntVal() != VarID)
446 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000447 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000448 Lex.Lex(); // eat GlobalID;
449
450 if (ParseToken(lltok::equal, "expected '=' after name"))
451 return true;
452 }
453
454 bool HasLinkage;
455 unsigned Linkage, Visibility;
456 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
457 ParseOptionalVisibility(Visibility))
458 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Dan Gohman3845e502009-08-12 23:32:33 +0000460 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
461 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
462 return ParseAlias(Name, NameLoc, Visibility);
463}
464
Chris Lattnerdf986172009-01-02 07:01:27 +0000465/// ParseNamedGlobal:
466/// GlobalVar '=' OptionalVisibility ALIAS ...
467/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
468bool LLParser::ParseNamedGlobal() {
469 assert(Lex.getKind() == lltok::GlobalVar);
470 LocTy NameLoc = Lex.getLoc();
471 std::string Name = Lex.getStrVal();
472 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000473
Chris Lattnerdf986172009-01-02 07:01:27 +0000474 bool HasLinkage;
475 unsigned Linkage, Visibility;
476 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
477 ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility))
479 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000480
Chris Lattnerdf986172009-01-02 07:01:27 +0000481 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
482 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
483 return ParseAlias(Name, NameLoc, Visibility);
484}
485
Devang Patel256be962009-07-20 19:00:08 +0000486// MDString:
487// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000488bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000489 std::string Str;
490 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000491 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000492 return false;
493}
494
495// MDNode:
496// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000497//
498/// This version of ParseMDNodeID returns the slot number and null in the case
499/// of a forward reference.
500bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
501 // !{ ..., !42, ... }
502 if (ParseUInt32(SlotNo)) return true;
503
504 // Check existing MDNode.
505 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
506 Result = NumberedMetadata[SlotNo];
507 else
508 Result = 0;
509 return false;
510}
511
Chris Lattner4a72efc2009-12-30 04:15:23 +0000512bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000513 // !{ ..., !42, ... }
514 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000515 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000516
Chris Lattner449c3102010-04-01 05:14:45 +0000517 // If not a forward reference, just return it now.
518 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000519
Chris Lattner449c3102010-04-01 05:14:45 +0000520 // Otherwise, create MDNode forward reference.
Dan Gohman489b29b2010-08-20 22:02:26 +0000521 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
Devang Patel256be962009-07-20 19:00:08 +0000522 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000523
524 if (NumberedMetadata.size() <= MID)
525 NumberedMetadata.resize(MID+1);
526 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000527 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000528 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529}
Devang Patel256be962009-07-20 19:00:08 +0000530
Chris Lattner84d03b12009-12-29 22:35:39 +0000531/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000532/// !foo = !{ !1, !2 }
533bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000534 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000535 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000536 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000537
Chris Lattner84d03b12009-12-29 22:35:39 +0000538 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000539 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000540 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000541 return true;
542
Dan Gohman17aa92c2010-07-21 23:38:33 +0000543 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000544 if (Lex.getKind() != lltok::rbrace)
545 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000546 if (ParseToken(lltok::exclaim, "Expected '!' here"))
547 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000548
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000549 MDNode *N = 0;
550 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000551 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000552 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000553
554 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
555 return true;
556
Devang Pateleff2ab62009-07-29 00:34:02 +0000557 return false;
558}
559
Devang Patel923078c2009-07-01 19:21:12 +0000560/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000562bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000563 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000564 Lex.Lex();
565 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000566
567 LocTy TyLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 PATypeHolder Ty(Type::getVoidTy(Context));
Devang Patel104cf9e2009-07-23 01:07:34 +0000569 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000570 if (ParseUInt32(MetadataID) ||
571 ParseToken(lltok::equal, "expected '=' here") ||
572 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000573 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000574 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000575 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000576 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000577 return true;
578
Owen Anderson647e3012009-07-31 21:35:40 +0000579 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000580
581 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000582 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000583 FI = ForwardRefMDNodes.find(MetadataID);
584 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000585 MDNode *Temp = FI->second.first;
586 Temp->replaceAllUsesWith(Init);
587 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000588 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000589
590 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
591 } else {
592 if (MetadataID >= NumberedMetadata.size())
593 NumberedMetadata.resize(MetadataID+1);
594
595 if (NumberedMetadata[MetadataID] != 0)
596 return TokError("Metadata id is already used");
597 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000598 }
599
Devang Patel923078c2009-07-01 19:21:12 +0000600 return false;
601}
602
Chris Lattnerdf986172009-01-02 07:01:27 +0000603/// ParseAlias:
604/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
605/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000606/// ::= TypeAndValue
607/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000608/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000609///
610/// Everything through visibility has already been parsed.
611///
612bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
613 unsigned Visibility) {
614 assert(Lex.getKind() == lltok::kw_alias);
615 Lex.Lex();
616 unsigned Linkage;
617 LocTy LinkageLoc = Lex.getLoc();
618 if (ParseOptionalLinkage(Linkage))
619 return true;
620
621 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000622 Linkage != GlobalValue::WeakAnyLinkage &&
623 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000624 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000625 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000626 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000627 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 Constant *Aliasee;
632 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
636 } else {
637 // The bitcast dest type is not present, it is implied by the dest type.
638 ValID ID;
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
643 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Duncan Sands1df98592010-02-16 11:11:14 +0000645 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000646 return Error(AliaseeLoc, "alias must have pointer type");
647
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
651 Aliasee);
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattnerdf986172009-01-02 07:01:27 +0000654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000656 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 // See if this was a redefinition. If so, there is no entry in
658 // ForwardRefVals.
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
663
664 // Otherwise, this was a definition of forward ref. Verify that types
665 // agree.
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000669
Chris Lattnerdf986172009-01-02 07:01:27 +0000670 // If they agree, just RAUW the old value with the alias and remove the
671 // forward ref info.
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
675 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattnerdf986172009-01-02 07:01:27 +0000677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000679 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000680
Chris Lattnerdf986172009-01-02 07:01:27 +0000681 return false;
682}
683
684/// ParseGlobal
685/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000686/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000687/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000688/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000689///
690/// Everything through visibility has been parsed already.
691///
692bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
695 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000696 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000697 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000698 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000699
Owen Anderson1d0be152009-08-13 21:58:54 +0000700 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +0000701 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
702 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000703 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
704 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000705 ParseGlobalType(IsConstant) ||
706 ParseType(Ty, TyLoc))
707 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000708
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 // If the linkage is specified and is external, then no initializer is
710 // present.
711 Constant *Init = 0;
712 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000713 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000714 Linkage != GlobalValue::ExternalLinkage)) {
715 if (ParseGlobalValue(Ty, Init))
716 return true;
717 }
718
Rafael Espindolad72479c2011-01-13 01:30:30 +0000719 if (!Init && UnnamedAddr)
720 return Error(UnnamedAddrLoc, "only definitions can have unnamed_addr");
721
Duncan Sands1df98592010-02-16 11:11:14 +0000722 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000723 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000724
Chris Lattnerdf986172009-01-02 07:01:27 +0000725 GlobalVariable *GV = 0;
726
727 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000728 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000729 if (GlobalValue *GVal = M->getNamedValue(Name)) {
730 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
731 return Error(NameLoc, "redefinition of global '@" + Name + "'");
732 GV = cast<GlobalVariable>(GVal);
733 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000734 } else {
735 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
736 I = ForwardRefValIDs.find(NumberedVals.size());
737 if (I != ForwardRefValIDs.end()) {
738 GV = cast<GlobalVariable>(I->second.first);
739 ForwardRefValIDs.erase(I);
740 }
741 }
742
743 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000745 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 } else {
747 if (GV->getType()->getElementType() != Ty)
748 return Error(TyLoc,
749 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattnerdf986172009-01-02 07:01:27 +0000751 // Move the forward-reference to the correct spot in the module.
752 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
753 }
754
755 if (Name.empty())
756 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattnerdf986172009-01-02 07:01:27 +0000758 // Set the parsed properties on the global.
759 if (Init)
760 GV->setInitializer(Init);
761 GV->setConstant(IsConstant);
762 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
763 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
764 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000765 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Chris Lattnerdf986172009-01-02 07:01:27 +0000767 // Parse attributes on the global.
768 while (Lex.getKind() == lltok::comma) {
769 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Chris Lattnerdf986172009-01-02 07:01:27 +0000771 if (Lex.getKind() == lltok::kw_section) {
772 Lex.Lex();
773 GV->setSection(Lex.getStrVal());
774 if (ParseToken(lltok::StringConstant, "expected global section string"))
775 return true;
776 } else if (Lex.getKind() == lltok::kw_align) {
777 unsigned Alignment;
778 if (ParseOptionalAlignment(Alignment)) return true;
779 GV->setAlignment(Alignment);
780 } else {
781 TokError("unknown global variable property!");
782 }
783 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Chris Lattnerdf986172009-01-02 07:01:27 +0000785 return false;
786}
787
788
789//===----------------------------------------------------------------------===//
790// GlobalValue Reference/Resolution Routines.
791//===----------------------------------------------------------------------===//
792
793/// GetGlobalVal - Get a value with the specified name or ID, creating a
794/// forward reference record if needed. This can return null if the value
795/// exists but does not have the right type.
796GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
797 LocTy Loc) {
798 const PointerType *PTy = dyn_cast<PointerType>(Ty);
799 if (PTy == 0) {
800 Error(Loc, "global variable reference must have pointer type");
801 return 0;
802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Chris Lattnerdf986172009-01-02 07:01:27 +0000804 // Look this name up in the normal function symbol table.
805 GlobalValue *Val =
806 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattnerdf986172009-01-02 07:01:27 +0000808 // If this is a forward reference for the value, see if we already created a
809 // forward ref record.
810 if (Val == 0) {
811 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
812 I = ForwardRefVals.find(Name);
813 if (I != ForwardRefVals.end())
814 Val = I->second.first;
815 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000816
Chris Lattnerdf986172009-01-02 07:01:27 +0000817 // If we have the value in the symbol table or fwd-ref table, return it.
818 if (Val) {
819 if (Val->getType() == Ty) return Val;
820 Error(Loc, "'@" + Name + "' defined with type '" +
821 Val->getType()->getDescription() + "'");
822 return 0;
823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Chris Lattnerdf986172009-01-02 07:01:27 +0000825 // Otherwise, create a new forward reference for this value and remember it.
826 GlobalValue *FwdVal;
Chris Lattner1e407c32009-01-08 19:05:36 +0000827 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
828 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000829 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner1e407c32009-01-08 19:05:36 +0000830 Error(Loc, "function may not return opaque type");
831 return 0;
832 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000833
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000834 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1e407c32009-01-08 19:05:36 +0000835 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000836 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
837 GlobalValue::ExternalWeakLinkage, 0, Name);
Chris Lattner1e407c32009-01-08 19:05:36 +0000838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Chris Lattnerdf986172009-01-02 07:01:27 +0000840 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
841 return FwdVal;
842}
843
844GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
845 const PointerType *PTy = dyn_cast<PointerType>(Ty);
846 if (PTy == 0) {
847 Error(Loc, "global variable reference must have pointer type");
848 return 0;
849 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000850
Chris Lattnerdf986172009-01-02 07:01:27 +0000851 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000852
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 // If this is a forward reference for the value, see if we already created a
854 // forward ref record.
855 if (Val == 0) {
856 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
857 I = ForwardRefValIDs.find(ID);
858 if (I != ForwardRefValIDs.end())
859 Val = I->second.first;
860 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861
Chris Lattnerdf986172009-01-02 07:01:27 +0000862 // If we have the value in the symbol table or fwd-ref table, return it.
863 if (Val) {
864 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000865 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +0000866 Val->getType()->getDescription() + "'");
867 return 0;
868 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000869
Chris Lattnerdf986172009-01-02 07:01:27 +0000870 // Otherwise, create a new forward reference for this value and remember it.
871 GlobalValue *FwdVal;
Chris Lattner830703b2009-01-05 18:27:50 +0000872 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
873 // Function types can return opaque but functions can't.
Duncan Sands47c51882010-02-16 14:50:09 +0000874 if (FT->getReturnType()->isOpaqueTy()) {
Chris Lattner0d8484f2009-01-05 18:56:52 +0000875 Error(Loc, "function may not return opaque type");
Chris Lattner830703b2009-01-05 18:27:50 +0000876 return 0;
877 }
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000878 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner830703b2009-01-05 18:27:50 +0000879 } else {
Owen Andersone9b11b42009-07-08 19:03:57 +0000880 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
881 GlobalValue::ExternalWeakLinkage, 0, "");
Chris Lattner830703b2009-01-05 18:27:50 +0000882 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883
Chris Lattnerdf986172009-01-02 07:01:27 +0000884 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
885 return FwdVal;
886}
887
888
889//===----------------------------------------------------------------------===//
890// Helper Routines.
891//===----------------------------------------------------------------------===//
892
893/// ParseToken - If the current token has the specified kind, eat it and return
894/// success. Otherwise, emit the specified error and return failure.
895bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
896 if (Lex.getKind() != T)
897 return TokError(ErrMsg);
898 Lex.Lex();
899 return false;
900}
901
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000902/// ParseStringConstant
903/// ::= StringConstant
904bool LLParser::ParseStringConstant(std::string &Result) {
905 if (Lex.getKind() != lltok::StringConstant)
906 return TokError("expected string constant");
907 Result = Lex.getStrVal();
908 Lex.Lex();
909 return false;
910}
911
912/// ParseUInt32
913/// ::= uint32
914bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000915 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
916 return TokError("expected integer");
917 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
918 if (Val64 != unsigned(Val64))
919 return TokError("expected 32-bit integer (too large)");
920 Val = Val64;
921 Lex.Lex();
922 return false;
923}
924
925
926/// ParseOptionalAddrSpace
927/// := /*empty*/
928/// := 'addrspace' '(' uint32 ')'
929bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
930 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000931 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000934 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000935 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936}
Chris Lattnerdf986172009-01-02 07:01:27 +0000937
938/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
939/// indicates what kind of attribute list this is: 0: function arg, 1: result,
940/// 2: function attr.
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000941/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
Chris Lattnerdf986172009-01-02 07:01:27 +0000942bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
943 Attrs = Attribute::None;
944 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000945
Chris Lattnerdf986172009-01-02 07:01:27 +0000946 while (1) {
947 switch (Lex.getKind()) {
948 case lltok::kw_sext:
949 case lltok::kw_zext:
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000950 // Treat these as signext/zeroext if they occur in the argument list after
951 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
952 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
953 // expr.
Chris Lattnerdf986172009-01-02 07:01:27 +0000954 // FIXME: REMOVE THIS IN LLVM 3.0
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000955 if (AttrKind == 3) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000956 if (Lex.getKind() == lltok::kw_sext)
957 Attrs |= Attribute::SExt;
958 else
959 Attrs |= Attribute::ZExt;
960 break;
961 }
962 // FALL THROUGH.
963 default: // End of attributes.
964 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
965 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000966
Chris Lattnerad9ad7c2009-03-25 06:36:36 +0000967 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000968 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000969
Chris Lattnerdf986172009-01-02 07:01:27 +0000970 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000971 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
972 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
973 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
974 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
975 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
976 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
977 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
978 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000979
Devang Patel578efa92009-06-05 21:57:13 +0000980 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
981 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
982 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
983 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
984 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000985 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000986 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
987 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
988 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
989 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
990 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
991 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000992 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000993 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000994
Charles Davis1e063d12010-02-12 00:31:15 +0000995 case lltok::kw_alignstack: {
996 unsigned Alignment;
997 if (ParseOptionalStackAlignment(Alignment))
998 return true;
999 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
1000 continue;
1001 }
1002
Chris Lattnerdf986172009-01-02 07:01:27 +00001003 case lltok::kw_align: {
1004 unsigned Alignment;
1005 if (ParseOptionalAlignment(Alignment))
1006 return true;
1007 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1008 continue;
1009 }
Charles Davis1e063d12010-02-12 00:31:15 +00001010
Chris Lattnerdf986172009-01-02 07:01:27 +00001011 }
1012 Lex.Lex();
1013 }
1014}
1015
1016/// ParseOptionalLinkage
1017/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +00001018/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001019/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +00001020/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +00001021/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +00001022/// ::= 'internal'
1023/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +00001024/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +00001025/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +00001026/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +00001027/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +00001028/// ::= 'appending'
1029/// ::= 'dllexport'
1030/// ::= 'common'
1031/// ::= 'dllimport'
1032/// ::= 'extern_weak'
1033/// ::= 'external'
1034bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1035 HasLinkage = false;
1036 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001037 default: Res=GlobalValue::ExternalLinkage; return false;
1038 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1039 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001040 case lltok::kw_linker_private_weak:
1041 Res = GlobalValue::LinkerPrivateWeakLinkage;
1042 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001043 case lltok::kw_linker_private_weak_def_auto:
1044 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1045 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001046 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1047 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1048 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1049 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1050 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001051 case lltok::kw_available_externally:
1052 Res = GlobalValue::AvailableExternallyLinkage;
1053 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001054 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1055 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1056 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1057 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1058 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1059 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001060 }
1061 Lex.Lex();
1062 HasLinkage = true;
1063 return false;
1064}
1065
1066/// ParseOptionalVisibility
1067/// ::= /*empty*/
1068/// ::= 'default'
1069/// ::= 'hidden'
1070/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001071///
Chris Lattnerdf986172009-01-02 07:01:27 +00001072bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1073 switch (Lex.getKind()) {
1074 default: Res = GlobalValue::DefaultVisibility; return false;
1075 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1076 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1077 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1078 }
1079 Lex.Lex();
1080 return false;
1081}
1082
1083/// ParseOptionalCallingConv
1084/// ::= /*empty*/
1085/// ::= 'ccc'
1086/// ::= 'fastcc'
1087/// ::= 'coldcc'
1088/// ::= 'x86_stdcallcc'
1089/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001090/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001091/// ::= 'arm_apcscc'
1092/// ::= 'arm_aapcscc'
1093/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001094/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001095/// ::= 'ptx_kernel'
1096/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001097/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001098///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001099bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001100 switch (Lex.getKind()) {
1101 default: CC = CallingConv::C; return false;
1102 case lltok::kw_ccc: CC = CallingConv::C; break;
1103 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1104 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1105 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1106 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001107 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001108 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1109 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1110 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001111 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001112 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1113 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001114 case lltok::kw_cc: {
1115 unsigned ArbitraryCC;
1116 Lex.Lex();
1117 if (ParseUInt32(ArbitraryCC)) {
1118 return true;
1119 } else
1120 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1121 return false;
1122 }
1123 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001124 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001125
Chris Lattnerdf986172009-01-02 07:01:27 +00001126 Lex.Lex();
1127 return false;
1128}
1129
Chris Lattnerb8c46862009-12-30 05:31:19 +00001130/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001131/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001132bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1133 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001134 do {
1135 if (Lex.getKind() != lltok::MetadataVar)
1136 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001137
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001138 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001139 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001140 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001141
Chris Lattner442ffa12009-12-29 21:53:55 +00001142 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001143 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001144
1145 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001146 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001147
Dan Gohman68261142010-08-24 14:35:45 +00001148 // This code is similar to that of ParseMetadataValue, however it needs to
1149 // have special-case code for a forward reference; see the comments on
1150 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1151 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001152 if (Lex.getKind() == lltok::lbrace) {
1153 ValID ID;
1154 if (ParseMetadataListValue(ID, PFS))
1155 return true;
1156 assert(ID.Kind == ValID::t_MDNode);
1157 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001158 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001159 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001160 if (ParseMDNodeID(Node, NodeID))
1161 return true;
1162 if (Node) {
1163 // If we got the node, add it to the instruction.
1164 Inst->setMetadata(MDK, Node);
1165 } else {
1166 MDRef R = { Loc, MDK, NodeID };
1167 // Otherwise, remember that this should be resolved later.
1168 ForwardRefInstMetadata[Inst].push_back(R);
1169 }
Chris Lattner449c3102010-04-01 05:14:45 +00001170 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001171
1172 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001173 } while (EatIfPresent(lltok::comma));
1174 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001175}
1176
Chris Lattnerdf986172009-01-02 07:01:27 +00001177/// ParseOptionalAlignment
1178/// ::= /* empty */
1179/// ::= 'align' 4
1180bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1181 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001182 if (!EatIfPresent(lltok::kw_align))
1183 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001184 LocTy AlignLoc = Lex.getLoc();
1185 if (ParseUInt32(Alignment)) return true;
1186 if (!isPowerOf2_32(Alignment))
1187 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001188 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001189 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001190 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001191}
1192
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001193/// ParseOptionalCommaAlign
1194/// ::=
1195/// ::= ',' align 4
1196///
1197/// This returns with AteExtraComma set to true if it ate an excess comma at the
1198/// end.
1199bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1200 bool &AteExtraComma) {
1201 AteExtraComma = false;
1202 while (EatIfPresent(lltok::comma)) {
1203 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001204 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001205 AteExtraComma = true;
1206 return false;
1207 }
1208
Chris Lattner093eed12010-04-23 00:50:50 +00001209 if (Lex.getKind() != lltok::kw_align)
1210 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001211
Chris Lattner093eed12010-04-23 00:50:50 +00001212 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001214
Devang Patelf633a062009-09-17 23:04:48 +00001215 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001216}
1217
Charles Davis1e063d12010-02-12 00:31:15 +00001218/// ParseOptionalStackAlignment
1219/// ::= /* empty */
1220/// ::= 'alignstack' '(' 4 ')'
1221bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1222 Alignment = 0;
1223 if (!EatIfPresent(lltok::kw_alignstack))
1224 return false;
1225 LocTy ParenLoc = Lex.getLoc();
1226 if (!EatIfPresent(lltok::lparen))
1227 return Error(ParenLoc, "expected '('");
1228 LocTy AlignLoc = Lex.getLoc();
1229 if (ParseUInt32(Alignment)) return true;
1230 ParenLoc = Lex.getLoc();
1231 if (!EatIfPresent(lltok::rparen))
1232 return Error(ParenLoc, "expected ')'");
1233 if (!isPowerOf2_32(Alignment))
1234 return Error(AlignLoc, "stack alignment is not a power of two");
1235 return false;
1236}
Devang Patelf633a062009-09-17 23:04:48 +00001237
Chris Lattner628c13a2009-12-30 05:14:00 +00001238/// ParseIndexList - This parses the index list for an insert/extractvalue
1239/// instruction. This sets AteExtraComma in the case where we eat an extra
1240/// comma at the end of the line and find that it is followed by metadata.
1241/// Clients that don't allow metadata can call the version of this function that
1242/// only takes one argument.
1243///
Chris Lattnerdf986172009-01-02 07:01:27 +00001244/// ParseIndexList
1245/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001246///
1247bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1248 bool &AteExtraComma) {
1249 AteExtraComma = false;
1250
Chris Lattnerdf986172009-01-02 07:01:27 +00001251 if (Lex.getKind() != lltok::comma)
1252 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001253
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001254 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001255 if (Lex.getKind() == lltok::MetadataVar) {
1256 AteExtraComma = true;
1257 return false;
1258 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001259 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001260 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001261 Indices.push_back(Idx);
1262 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001263
Chris Lattnerdf986172009-01-02 07:01:27 +00001264 return false;
1265}
1266
1267//===----------------------------------------------------------------------===//
1268// Type Parsing.
1269//===----------------------------------------------------------------------===//
1270
1271/// ParseType - Parse and resolve a full type.
Chris Lattnera9a9e072009-03-09 04:49:14 +00001272bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1273 LocTy TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001274 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 // Verify no unresolved uprefs.
1277 if (!UpRefs.empty())
1278 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001279
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001280 if (!AllowVoid && Result.get()->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001281 return Error(TypeLoc, "void type only allowed for function results");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattnerdf986172009-01-02 07:01:27 +00001283 return false;
1284}
1285
1286/// HandleUpRefs - Every time we finish a new layer of types, this function is
1287/// called. It loops through the UpRefs vector, which is a list of the
1288/// currently active types. For each type, if the up-reference is contained in
1289/// the newly completed type, we decrement the level count. When the level
1290/// count reaches zero, the up-referenced type is the type that is passed in:
1291/// thus we can complete the cycle.
1292///
1293PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1294 // If Ty isn't abstract, or if there are no up-references in it, then there is
1295 // nothing to resolve here.
1296 if (!ty->isAbstract() || UpRefs.empty()) return ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerdf986172009-01-02 07:01:27 +00001298 PATypeHolder Ty(ty);
1299#if 0
David Greene0e28d762009-12-23 23:38:28 +00001300 dbgs() << "Type '" << Ty->getDescription()
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 << "' newly formed. Resolving upreferences.\n"
1302 << UpRefs.size() << " upreferences active!\n";
1303#endif
Daniel Dunbara279bc32009-09-20 02:20:51 +00001304
Chris Lattnerdf986172009-01-02 07:01:27 +00001305 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1306 // to zero), we resolve them all together before we resolve them to Ty. At
1307 // the end of the loop, if there is anything to resolve to Ty, it will be in
1308 // this variable.
1309 OpaqueType *TypeToResolve = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
Chris Lattnerdf986172009-01-02 07:01:27 +00001311 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1312 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1313 bool ContainsType =
1314 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1315 UpRefs[i].LastContainedTy) != Ty->subtype_end();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001316
Chris Lattnerdf986172009-01-02 07:01:27 +00001317#if 0
David Greene0e28d762009-12-23 23:38:28 +00001318 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
Chris Lattnerdf986172009-01-02 07:01:27 +00001319 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1320 << (ContainsType ? "true" : "false")
1321 << " level=" << UpRefs[i].NestingLevel << "\n";
1322#endif
1323 if (!ContainsType)
1324 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001325
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 // Decrement level of upreference
1327 unsigned Level = --UpRefs[i].NestingLevel;
1328 UpRefs[i].LastContainedTy = Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1331 if (Level != 0)
1332 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattnerdf986172009-01-02 07:01:27 +00001334#if 0
David Greene0e28d762009-12-23 23:38:28 +00001335 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
Chris Lattnerdf986172009-01-02 07:01:27 +00001336#endif
1337 if (!TypeToResolve)
1338 TypeToResolve = UpRefs[i].UpRefTy;
1339 else
1340 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1341 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1342 --i; // Do not skip the next element.
1343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001344
Chris Lattnerdf986172009-01-02 07:01:27 +00001345 if (TypeToResolve)
1346 TypeToResolve->refineAbstractTypeTo(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001347
Chris Lattnerdf986172009-01-02 07:01:27 +00001348 return Ty;
1349}
1350
1351
1352/// ParseTypeRec - The recursive function used to process the internal
1353/// implementation details of types.
1354bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1355 switch (Lex.getKind()) {
1356 default:
1357 return TokError("expected type");
1358 case lltok::Type:
1359 // TypeRec ::= 'float' | 'void' (etc)
1360 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001361 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 break;
1363 case lltok::kw_opaque:
1364 // TypeRec ::= 'opaque'
Owen Anderson0e275dc2009-08-13 23:27:32 +00001365 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 Lex.Lex();
1367 break;
1368 case lltok::lbrace:
1369 // TypeRec ::= '{' ... '}'
1370 if (ParseStructType(Result, false))
1371 return true;
1372 break;
1373 case lltok::lsquare:
1374 // TypeRec ::= '[' ... ']'
1375 Lex.Lex(); // eat the lsquare.
1376 if (ParseArrayVectorType(Result, false))
1377 return true;
1378 break;
1379 case lltok::less: // Either vector or packed struct.
1380 // TypeRec ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001381 Lex.Lex();
1382 if (Lex.getKind() == lltok::lbrace) {
1383 if (ParseStructType(Result, true) ||
1384 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001385 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 } else if (ParseArrayVectorType(Result, true))
1387 return true;
1388 break;
1389 case lltok::LocalVar:
1390 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1391 // TypeRec ::= %foo
1392 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1393 Result = T;
1394 } else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001395 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001396 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1397 std::make_pair(Result,
1398 Lex.getLoc())));
1399 M->addTypeName(Lex.getStrVal(), Result.get());
1400 }
1401 Lex.Lex();
1402 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
Chris Lattnerdf986172009-01-02 07:01:27 +00001404 case lltok::LocalVarID:
1405 // TypeRec ::= %4
1406 if (Lex.getUIntVal() < NumberedTypes.size())
1407 Result = NumberedTypes[Lex.getUIntVal()];
1408 else {
1409 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1410 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1411 if (I != ForwardRefTypeIDs.end())
1412 Result = I->second.first;
1413 else {
Owen Anderson0e275dc2009-08-13 23:27:32 +00001414 Result = OpaqueType::get(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1416 std::make_pair(Result,
1417 Lex.getLoc())));
1418 }
1419 }
1420 Lex.Lex();
1421 break;
1422 case lltok::backslash: {
1423 // TypeRec ::= '\' 4
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001425 unsigned Val;
1426 if (ParseUInt32(Val)) return true;
Owen Anderson0e275dc2009-08-13 23:27:32 +00001427 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
Chris Lattnerdf986172009-01-02 07:01:27 +00001428 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1429 Result = OT;
1430 break;
1431 }
1432 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001433
1434 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001435 while (1) {
1436 switch (Lex.getKind()) {
1437 // End of type.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001438 default: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001439
1440 // TypeRec ::= TypeRec '*'
1441 case lltok::star:
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001442 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001443 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001444 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001445 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001446 if (!PointerType::isValidElementType(Result.get()))
1447 return TokError("pointer to this type is invalid");
Owen Andersondebcb012009-07-29 22:17:13 +00001448 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001449 Lex.Lex();
1450 break;
1451
1452 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1453 case lltok::kw_addrspace: {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001454 if (Result.get()->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001455 return TokError("basic block pointers are invalid");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001456 if (Result.get()->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001457 return TokError("pointers to void are invalid; use i8* instead");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001458 if (!PointerType::isValidElementType(Result.get()))
1459 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 unsigned AddrSpace;
1461 if (ParseOptionalAddrSpace(AddrSpace) ||
1462 ParseToken(lltok::star, "expected '*' in address space"))
1463 return true;
1464
Owen Andersondebcb012009-07-29 22:17:13 +00001465 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
Chris Lattnerdf986172009-01-02 07:01:27 +00001466 break;
1467 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001468
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1470 case lltok::lparen:
1471 if (ParseFunctionType(Result))
1472 return true;
1473 break;
1474 }
1475 }
1476}
1477
1478/// ParseParameterList
1479/// ::= '(' ')'
1480/// ::= '(' Arg (',' Arg)* ')'
1481/// Arg
1482/// ::= Type OptionalAttributes Value OptionalAttributes
1483bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1484 PerFunctionState &PFS) {
1485 if (ParseToken(lltok::lparen, "expected '(' in call"))
1486 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnerdf986172009-01-02 07:01:27 +00001488 while (Lex.getKind() != lltok::rparen) {
1489 // If this isn't the first argument, we need a comma.
1490 if (!ArgList.empty() &&
1491 ParseToken(lltok::comma, "expected ',' in argument list"))
1492 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001493
Chris Lattnerdf986172009-01-02 07:01:27 +00001494 // Parse the argument.
1495 LocTy ArgLoc;
Owen Anderson1d0be152009-08-13 21:58:54 +00001496 PATypeHolder ArgTy(Type::getVoidTy(Context));
Victor Hernandez19715562009-12-03 23:40:58 +00001497 unsigned ArgAttrs1 = Attribute::None;
1498 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001500 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001502
Chris Lattner287881d2009-12-30 02:11:14 +00001503 // Otherwise, handle normal operands.
1504 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1505 ParseValue(ArgTy, V, PFS) ||
1506 // FIXME: Should not allow attributes after the argument, remove this
1507 // in LLVM 3.0.
1508 ParseOptionalAttrs(ArgAttrs2, 3))
1509 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001510 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1511 }
1512
1513 Lex.Lex(); // Lex the ')'.
1514 return false;
1515}
1516
1517
1518
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001519/// ParseArgumentList - Parse the argument list for a function type or function
1520/// prototype. If 'inType' is true then we are parsing a FunctionType.
Chris Lattnerdf986172009-01-02 07:01:27 +00001521/// ::= '(' ArgTypeListI ')'
1522/// ArgTypeListI
1523/// ::= /*empty*/
1524/// ::= '...'
1525/// ::= ArgTypeList ',' '...'
1526/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001527///
Chris Lattnerdf986172009-01-02 07:01:27 +00001528bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001529 bool &isVarArg, bool inType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001530 isVarArg = false;
1531 assert(Lex.getKind() == lltok::lparen);
1532 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattnerdf986172009-01-02 07:01:27 +00001534 if (Lex.getKind() == lltok::rparen) {
1535 // empty
1536 } else if (Lex.getKind() == lltok::dotdotdot) {
1537 isVarArg = true;
1538 Lex.Lex();
1539 } else {
1540 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001541 PATypeHolder ArgTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001542 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001543 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001544
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001545 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1546 // types (such as a function returning a pointer to itself). If parsing a
1547 // function prototype, we require fully resolved types.
1548 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001549 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001551 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001552 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001553
Chris Lattnerdf986172009-01-02 07:01:27 +00001554 if (Lex.getKind() == lltok::LocalVar ||
1555 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1556 Name = Lex.getStrVal();
1557 Lex.Lex();
1558 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001559
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001560 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001561 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnerdf986172009-01-02 07:01:27 +00001563 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001565 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001566 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001567 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001568 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001569 break;
1570 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001571
Chris Lattnerdf986172009-01-02 07:01:27 +00001572 // Otherwise must be an argument type.
1573 TypeLoc = Lex.getLoc();
Chris Lattnera9a9e072009-03-09 04:49:14 +00001574 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001575 ParseOptionalAttrs(Attrs, 0)) return true;
1576
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001577 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001578 return Error(TypeLoc, "argument can not have void type");
1579
Chris Lattnerdf986172009-01-02 07:01:27 +00001580 if (Lex.getKind() == lltok::LocalVar ||
1581 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1582 Name = Lex.getStrVal();
1583 Lex.Lex();
1584 } else {
1585 Name = "";
1586 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001587
Duncan Sands47c51882010-02-16 14:50:09 +00001588 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001589 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001590
Chris Lattnerdf986172009-01-02 07:01:27 +00001591 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1592 }
1593 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001595 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001596}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnerdf986172009-01-02 07:01:27 +00001598/// ParseFunctionType
1599/// ::= Type ArgumentList OptionalAttrs
1600bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1601 assert(Lex.getKind() == lltok::lparen);
1602
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001603 if (!FunctionType::isValidReturnType(Result))
1604 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001605
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 std::vector<ArgInfo> ArgList;
1607 bool isVarArg;
1608 unsigned Attrs;
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001609 if (ParseArgumentList(ArgList, isVarArg, true) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00001610 // FIXME: Allow, but ignore attributes on function types!
1611 // FIXME: Remove in LLVM 3.0
1612 ParseOptionalAttrs(Attrs, 2))
1613 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001614
Chris Lattnerdf986172009-01-02 07:01:27 +00001615 // Reject names on the arguments lists.
1616 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1617 if (!ArgList[i].Name.empty())
1618 return Error(ArgList[i].Loc, "argument name invalid in function type");
1619 if (!ArgList[i].Attrs != 0) {
1620 // Allow but ignore attributes on function types; this permits
1621 // auto-upgrade.
1622 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1623 }
1624 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625
Chris Lattnerdf986172009-01-02 07:01:27 +00001626 std::vector<const Type*> ArgListTy;
1627 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1628 ArgListTy.push_back(ArgList[i].Type);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Owen Andersondebcb012009-07-29 22:17:13 +00001630 Result = HandleUpRefs(FunctionType::get(Result.get(),
Owen Andersonfba933c2009-07-01 23:57:11 +00001631 ArgListTy, isVarArg));
Chris Lattnerdf986172009-01-02 07:01:27 +00001632 return false;
1633}
1634
1635/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1636/// TypeRec
1637/// ::= '{' '}'
1638/// ::= '{' TypeRec (',' TypeRec)* '}'
1639/// ::= '<' '{' '}' '>'
1640/// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1641bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1642 assert(Lex.getKind() == lltok::lbrace);
1643 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001645 if (EatIfPresent(lltok::rbrace)) {
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001646 Result = StructType::get(Context, Packed);
Chris Lattnerdf986172009-01-02 07:01:27 +00001647 return false;
1648 }
1649
1650 std::vector<PATypeHolder> ParamsList;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001651 LocTy EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001652 if (ParseTypeRec(Result)) return true;
1653 ParamsList.push_back(Result);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001654
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001655 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001656 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001657 if (!StructType::isValidElementType(Result))
1658 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001659
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001660 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001661 EltTyLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001662 if (ParseTypeRec(Result)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001664 if (Result->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001665 return Error(EltTyLoc, "struct element can not have void type");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001666 if (!StructType::isValidElementType(Result))
1667 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001668
Chris Lattnerdf986172009-01-02 07:01:27 +00001669 ParamsList.push_back(Result);
1670 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001672 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1673 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001674
Chris Lattnerdf986172009-01-02 07:01:27 +00001675 std::vector<const Type*> ParamsListTy;
1676 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1677 ParamsListTy.push_back(ParamsList[i].get());
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001678 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
Chris Lattnerdf986172009-01-02 07:01:27 +00001679 return false;
1680}
1681
1682/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1683/// token has already been consumed.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684/// TypeRec
Chris Lattnerdf986172009-01-02 07:01:27 +00001685/// ::= '[' APSINTVAL 'x' Types ']'
1686/// ::= '<' APSINTVAL 'x' Types '>'
1687bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1688 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1689 Lex.getAPSIntVal().getBitWidth() > 64)
1690 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691
Chris Lattnerdf986172009-01-02 07:01:27 +00001692 LocTy SizeLoc = Lex.getLoc();
1693 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001694 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001695
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001696 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1697 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001698
1699 LocTy TypeLoc = Lex.getLoc();
Owen Anderson1d0be152009-08-13 21:58:54 +00001700 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 if (ParseTypeRec(EltTy)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001703 if (EltTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001704 return Error(TypeLoc, "array and vector element type cannot be void");
1705
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001706 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1707 "expected end of sequential type"))
1708 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001711 if (Size == 0)
1712 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001713 if ((unsigned)Size != Size)
1714 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001715 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001716 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001717 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001719 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001720 return Error(TypeLoc, "invalid array element type");
Owen Andersondebcb012009-07-29 22:17:13 +00001721 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001722 }
1723 return false;
1724}
1725
1726//===----------------------------------------------------------------------===//
1727// Function Semantic Analysis.
1728//===----------------------------------------------------------------------===//
1729
Chris Lattner09d9ef42009-10-28 03:39:23 +00001730LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1731 int functionNumber)
1732 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001733
1734 // Insert unnamed arguments into the NumberedVals list.
1735 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1736 AI != E; ++AI)
1737 if (!AI->hasName())
1738 NumberedVals.push_back(AI);
1739}
1740
1741LLParser::PerFunctionState::~PerFunctionState() {
1742 // If there were any forward referenced non-basicblock values, delete them.
1743 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1744 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1745 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001746 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001747 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001748 delete I->second.first;
1749 I->second.first = 0;
1750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1753 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1754 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001755 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001756 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 delete I->second.first;
1758 I->second.first = 0;
1759 }
1760}
1761
Chris Lattner09d9ef42009-10-28 03:39:23 +00001762bool LLParser::PerFunctionState::FinishFunction() {
1763 // Check to see if someone took the address of labels in this block.
1764 if (!P.ForwardRefBlockAddresses.empty()) {
1765 ValID FunctionID;
1766 if (!F.getName().empty()) {
1767 FunctionID.Kind = ValID::t_GlobalName;
1768 FunctionID.StrVal = F.getName();
1769 } else {
1770 FunctionID.Kind = ValID::t_GlobalID;
1771 FunctionID.UIntVal = FunctionNumber;
1772 }
1773
1774 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1775 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1776 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1777 // Resolve all these references.
1778 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1779 return true;
1780
1781 P.ForwardRefBlockAddresses.erase(FRBAI);
1782 }
1783 }
1784
Chris Lattnerdf986172009-01-02 07:01:27 +00001785 if (!ForwardRefVals.empty())
1786 return P.Error(ForwardRefVals.begin()->second.second,
1787 "use of undefined value '%" + ForwardRefVals.begin()->first +
1788 "'");
1789 if (!ForwardRefValIDs.empty())
1790 return P.Error(ForwardRefValIDs.begin()->second.second,
1791 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001792 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001793 return false;
1794}
1795
1796
1797/// GetVal - Get a value with the specified name or ID, creating a
1798/// forward reference record if needed. This can return null if the value
1799/// exists but does not have the right type.
1800Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1801 const Type *Ty, LocTy Loc) {
1802 // Look this name up in the normal function symbol table.
1803 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001804
Chris Lattnerdf986172009-01-02 07:01:27 +00001805 // If this is a forward reference for the value, see if we already created a
1806 // forward ref record.
1807 if (Val == 0) {
1808 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1809 I = ForwardRefVals.find(Name);
1810 if (I != ForwardRefVals.end())
1811 Val = I->second.first;
1812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001813
Chris Lattnerdf986172009-01-02 07:01:27 +00001814 // If we have the value in the symbol table or fwd-ref table, return it.
1815 if (Val) {
1816 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001817 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001818 P.Error(Loc, "'%" + Name + "' is not a basic block");
1819 else
1820 P.Error(Loc, "'%" + Name + "' defined with type '" +
1821 Val->getType()->getDescription() + "'");
1822 return 0;
1823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001824
Chris Lattnerdf986172009-01-02 07:01:27 +00001825 // Don't make placeholders with invalid type.
Duncan Sands47c51882010-02-16 14:50:09 +00001826 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001827 P.Error(Loc, "invalid use of a non-first-class type");
1828 return 0;
1829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 // Otherwise, create a new forward reference for this value and remember it.
1832 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001833 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001834 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001835 else
1836 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1839 return FwdVal;
1840}
1841
1842Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1843 LocTy Loc) {
1844 // Look this name up in the normal function symbol table.
1845 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846
Chris Lattnerdf986172009-01-02 07:01:27 +00001847 // If this is a forward reference for the value, see if we already created a
1848 // forward ref record.
1849 if (Val == 0) {
1850 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1851 I = ForwardRefValIDs.find(ID);
1852 if (I != ForwardRefValIDs.end())
1853 Val = I->second.first;
1854 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001855
Chris Lattnerdf986172009-01-02 07:01:27 +00001856 // If we have the value in the symbol table or fwd-ref table, return it.
1857 if (Val) {
1858 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001859 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001860 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001861 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001862 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 Val->getType()->getDescription() + "'");
1864 return 0;
1865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Duncan Sands47c51882010-02-16 14:50:09 +00001867 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001868 P.Error(Loc, "invalid use of a non-first-class type");
1869 return 0;
1870 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871
Chris Lattnerdf986172009-01-02 07:01:27 +00001872 // Otherwise, create a new forward reference for this value and remember it.
1873 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001874 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001875 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 else
1877 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattnerdf986172009-01-02 07:01:27 +00001879 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1880 return FwdVal;
1881}
1882
1883/// SetInstName - After an instruction is parsed and inserted into its
1884/// basic block, this installs its name.
1885bool LLParser::PerFunctionState::SetInstName(int NameID,
1886 const std::string &NameStr,
1887 LocTy NameLoc, Instruction *Inst) {
1888 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001889 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 if (NameID != -1 || !NameStr.empty())
1891 return P.Error(NameLoc, "instructions returning void cannot have a name");
1892 return false;
1893 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattnerdf986172009-01-02 07:01:27 +00001895 // If this was a numbered instruction, verify that the instruction is the
1896 // expected value and resolve any forward references.
1897 if (NameStr.empty()) {
1898 // If neither a name nor an ID was specified, just use the next ID.
1899 if (NameID == -1)
1900 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001901
Chris Lattnerdf986172009-01-02 07:01:27 +00001902 if (unsigned(NameID) != NumberedVals.size())
1903 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001904 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001905
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1907 ForwardRefValIDs.find(NameID);
1908 if (FI != ForwardRefValIDs.end()) {
1909 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001911 FI->second.first->getType()->getDescription() + "'");
1912 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001913 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001914 ForwardRefValIDs.erase(FI);
1915 }
1916
1917 NumberedVals.push_back(Inst);
1918 return false;
1919 }
1920
1921 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1922 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1923 FI = ForwardRefVals.find(NameStr);
1924 if (FI != ForwardRefVals.end()) {
1925 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001927 FI->second.first->getType()->getDescription() + "'");
1928 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001929 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 ForwardRefVals.erase(FI);
1931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Chris Lattnerdf986172009-01-02 07:01:27 +00001933 // Set the name on the instruction.
1934 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001935
Benjamin Krameraf812352010-10-16 11:28:23 +00001936 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001937 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001938 NameStr + "'");
1939 return false;
1940}
1941
1942/// GetBB - Get a basic block with the specified name or ID, creating a
1943/// forward reference record if needed.
1944BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1945 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001946 return cast_or_null<BasicBlock>(GetVal(Name,
1947 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001948}
1949
1950BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001951 return cast_or_null<BasicBlock>(GetVal(ID,
1952 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001953}
1954
1955/// DefineBB - Define the specified basic block, which is either named or
1956/// unnamed. If there is an error, this returns null otherwise it returns
1957/// the block being defined.
1958BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1959 LocTy Loc) {
1960 BasicBlock *BB;
1961 if (Name.empty())
1962 BB = GetBB(NumberedVals.size(), Loc);
1963 else
1964 BB = GetBB(Name, Loc);
1965 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001966
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 // Move the block to the end of the function. Forward ref'd blocks are
1968 // inserted wherever they happen to be referenced.
1969 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 // Remove the block from forward ref sets.
1972 if (Name.empty()) {
1973 ForwardRefValIDs.erase(NumberedVals.size());
1974 NumberedVals.push_back(BB);
1975 } else {
1976 // BB forward references are already in the function symbol table.
1977 ForwardRefVals.erase(Name);
1978 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001979
Chris Lattnerdf986172009-01-02 07:01:27 +00001980 return BB;
1981}
1982
1983//===----------------------------------------------------------------------===//
1984// Constants.
1985//===----------------------------------------------------------------------===//
1986
1987/// ParseValID - Parse an abstract value that doesn't necessarily have a
1988/// type implied. For example, if we parse "4" we don't know what integer type
1989/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001990/// sanity. PFS is used to convert function-local operands of metadata (since
1991/// metadata operands are not just parsed here but also converted to values).
1992/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001993bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001994 ID.Loc = Lex.getLoc();
1995 switch (Lex.getKind()) {
1996 default: return TokError("expected value token");
1997 case lltok::GlobalID: // @42
1998 ID.UIntVal = Lex.getUIntVal();
1999 ID.Kind = ValID::t_GlobalID;
2000 break;
2001 case lltok::GlobalVar: // @foo
2002 ID.StrVal = Lex.getStrVal();
2003 ID.Kind = ValID::t_GlobalName;
2004 break;
2005 case lltok::LocalVarID: // %42
2006 ID.UIntVal = Lex.getUIntVal();
2007 ID.Kind = ValID::t_LocalID;
2008 break;
2009 case lltok::LocalVar: // %foo
2010 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2011 ID.StrVal = Lex.getStrVal();
2012 ID.Kind = ValID::t_LocalName;
2013 break;
Dan Gohman83448032010-07-14 18:26:50 +00002014 case lltok::exclaim: // !42, !{...}, or !"foo"
2015 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002017 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002018 ID.Kind = ValID::t_APSInt;
2019 break;
2020 case lltok::APFloat:
2021 ID.APFloatVal = Lex.getAPFloatVal();
2022 ID.Kind = ValID::t_APFloat;
2023 break;
2024 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00002025 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002026 ID.Kind = ValID::t_Constant;
2027 break;
2028 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00002029 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 ID.Kind = ValID::t_Constant;
2031 break;
2032 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2033 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2034 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002035
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 case lltok::lbrace: {
2037 // ValID ::= '{' ConstVector '}'
2038 Lex.Lex();
2039 SmallVector<Constant*, 16> Elts;
2040 if (ParseGlobalValueVector(Elts) ||
2041 ParseToken(lltok::rbrace, "expected end of struct constant"))
2042 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002044 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2045 Elts.size(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002046 ID.Kind = ValID::t_Constant;
2047 return false;
2048 }
2049 case lltok::less: {
2050 // ValID ::= '<' ConstVector '>' --> Vector.
2051 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2052 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002053 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 SmallVector<Constant*, 16> Elts;
2056 LocTy FirstEltLoc = Lex.getLoc();
2057 if (ParseGlobalValueVector(Elts) ||
2058 (isPackedStruct &&
2059 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2060 ParseToken(lltok::greater, "expected end of constant"))
2061 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002062
Chris Lattnerdf986172009-01-02 07:01:27 +00002063 if (isPackedStruct) {
Owen Andersonfba933c2009-07-01 23:57:11 +00002064 ID.ConstantVal =
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002065 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
Chris Lattnerdf986172009-01-02 07:01:27 +00002066 ID.Kind = ValID::t_Constant;
2067 return false;
2068 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002069
Chris Lattnerdf986172009-01-02 07:01:27 +00002070 if (Elts.empty())
2071 return Error(ID.Loc, "constant vector must not be empty");
2072
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002073 if (!Elts[0]->getType()->isIntegerTy() &&
2074 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002075 return Error(FirstEltLoc,
2076 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002077
Chris Lattnerdf986172009-01-02 07:01:27 +00002078 // Verify that all the vector elements have the same type.
2079 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2080 if (Elts[i]->getType() != Elts[0]->getType())
2081 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002082 "vector element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002083 " is not of type '" + Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Owen Andersonaf7ec972009-07-28 21:19:26 +00002085 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 ID.Kind = ValID::t_Constant;
2087 return false;
2088 }
2089 case lltok::lsquare: { // Array Constant
2090 Lex.Lex();
2091 SmallVector<Constant*, 16> Elts;
2092 LocTy FirstEltLoc = Lex.getLoc();
2093 if (ParseGlobalValueVector(Elts) ||
2094 ParseToken(lltok::rsquare, "expected end of array constant"))
2095 return true;
2096
2097 // Handle empty element.
2098 if (Elts.empty()) {
2099 // Use undef instead of an array because it's inconvenient to determine
2100 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002101 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002102 return false;
2103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Chris Lattnerdf986172009-01-02 07:01:27 +00002105 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002106 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattnerdf986172009-01-02 07:01:27 +00002107 Elts[0]->getType()->getDescription());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002108
Owen Andersondebcb012009-07-29 22:17:13 +00002109 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Chris Lattnerdf986172009-01-02 07:01:27 +00002111 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002112 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002113 if (Elts[i]->getType() != Elts[0]->getType())
2114 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002115 "array element #" + Twine(i) +
Chris Lattnerdf986172009-01-02 07:01:27 +00002116 " is not of type '" +Elts[0]->getType()->getDescription());
2117 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002118
Owen Anderson1fd70962009-07-28 18:32:17 +00002119 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002120 ID.Kind = ValID::t_Constant;
2121 return false;
2122 }
2123 case lltok::kw_c: // c "foo"
2124 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002125 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2127 ID.Kind = ValID::t_Constant;
2128 return false;
2129
2130 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002131 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2132 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 Lex.Lex();
2134 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002135 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002136 ParseStringConstant(ID.StrVal) ||
2137 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 ParseToken(lltok::StringConstant, "expected constraint string"))
2139 return true;
2140 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002141 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 ID.Kind = ValID::t_InlineAsm;
2143 return false;
2144 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145
Chris Lattner09d9ef42009-10-28 03:39:23 +00002146 case lltok::kw_blockaddress: {
2147 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2148 Lex.Lex();
2149
2150 ValID Fn, Label;
2151 LocTy FnLoc, LabelLoc;
2152
2153 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2154 ParseValID(Fn) ||
2155 ParseToken(lltok::comma, "expected comma in block address expression")||
2156 ParseValID(Label) ||
2157 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2158 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002159
Chris Lattner09d9ef42009-10-28 03:39:23 +00002160 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2161 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002162 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002163 return Error(Label.Loc, "expected basic block name in blockaddress");
2164
2165 // Make a global variable as a placeholder for this reference.
2166 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2167 false, GlobalValue::InternalLinkage,
2168 0, "");
2169 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2170 ID.ConstantVal = FwdRef;
2171 ID.Kind = ValID::t_Constant;
2172 return false;
2173 }
2174
Chris Lattnerdf986172009-01-02 07:01:27 +00002175 case lltok::kw_trunc:
2176 case lltok::kw_zext:
2177 case lltok::kw_sext:
2178 case lltok::kw_fptrunc:
2179 case lltok::kw_fpext:
2180 case lltok::kw_bitcast:
2181 case lltok::kw_uitofp:
2182 case lltok::kw_sitofp:
2183 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002184 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002185 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002187 unsigned Opc = Lex.getUIntVal();
Owen Anderson1d0be152009-08-13 21:58:54 +00002188 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002189 Constant *SrcVal;
2190 Lex.Lex();
2191 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2192 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002193 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002194 ParseType(DestTy) ||
2195 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2196 return true;
2197 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2198 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2199 SrcVal->getType()->getDescription() + "' to '" +
2200 DestTy->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002201 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002202 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002203 ID.Kind = ValID::t_Constant;
2204 return false;
2205 }
2206 case lltok::kw_extractvalue: {
2207 Lex.Lex();
2208 Constant *Val;
2209 SmallVector<unsigned, 4> Indices;
2210 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2211 ParseGlobalTypeAndValue(Val) ||
2212 ParseIndexList(Indices) ||
2213 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2214 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002215
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002216 if (!Val->getType()->isAggregateType())
2217 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2219 Indices.end()))
2220 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foade3e51c02009-05-21 09:52:38 +00002221 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002222 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002223 ID.Kind = ValID::t_Constant;
2224 return false;
2225 }
2226 case lltok::kw_insertvalue: {
2227 Lex.Lex();
2228 Constant *Val0, *Val1;
2229 SmallVector<unsigned, 4> Indices;
2230 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2231 ParseGlobalTypeAndValue(Val0) ||
2232 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2233 ParseGlobalTypeAndValue(Val1) ||
2234 ParseIndexList(Indices) ||
2235 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2236 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002237 if (!Val0->getType()->isAggregateType())
2238 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00002239 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2240 Indices.end()))
2241 return Error(ID.Loc, "invalid indices for insertvalue");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002242 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
Owen Andersonfba933c2009-07-01 23:57:11 +00002243 Indices.data(), Indices.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00002244 ID.Kind = ValID::t_Constant;
2245 return false;
2246 }
2247 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002248 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002249 unsigned PredVal, Opc = Lex.getUIntVal();
2250 Constant *Val0, *Val1;
2251 Lex.Lex();
2252 if (ParseCmpPredicate(PredVal, Opc) ||
2253 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2254 ParseGlobalTypeAndValue(Val0) ||
2255 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2256 ParseGlobalTypeAndValue(Val1) ||
2257 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2258 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002259
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 if (Val0->getType() != Val1->getType())
2261 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002262
Chris Lattnerdf986172009-01-02 07:01:27 +00002263 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264
Chris Lattnerdf986172009-01-02 07:01:27 +00002265 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002266 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002267 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002268 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002269 } else {
2270 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002271 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002272 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002273 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002274 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 }
2276 ID.Kind = ValID::t_Constant;
2277 return false;
2278 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002279
Chris Lattnerdf986172009-01-02 07:01:27 +00002280 // Binary Operators.
2281 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002282 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002283 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002284 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002285 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002286 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002287 case lltok::kw_udiv:
2288 case lltok::kw_sdiv:
2289 case lltok::kw_fdiv:
2290 case lltok::kw_urem:
2291 case lltok::kw_srem:
2292 case lltok::kw_frem: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002293 bool NUW = false;
2294 bool NSW = false;
2295 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002296 unsigned Opc = Lex.getUIntVal();
2297 Constant *Val0, *Val1;
2298 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002299 LocTy ModifierLoc = Lex.getLoc();
2300 if (Opc == Instruction::Add ||
2301 Opc == Instruction::Sub ||
2302 Opc == Instruction::Mul) {
2303 if (EatIfPresent(lltok::kw_nuw))
2304 NUW = true;
2305 if (EatIfPresent(lltok::kw_nsw)) {
2306 NSW = true;
2307 if (EatIfPresent(lltok::kw_nuw))
2308 NUW = true;
2309 }
2310 } else if (Opc == Instruction::SDiv) {
2311 if (EatIfPresent(lltok::kw_exact))
2312 Exact = true;
2313 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2315 ParseGlobalTypeAndValue(Val0) ||
2316 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2317 ParseGlobalTypeAndValue(Val1) ||
2318 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2319 return true;
2320 if (Val0->getType() != Val1->getType())
2321 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002322 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002323 if (NUW)
2324 return Error(ModifierLoc, "nuw only applies to integer operations");
2325 if (NSW)
2326 return Error(ModifierLoc, "nsw only applies to integer operations");
2327 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002328 // Check that the type is valid for the operator.
2329 switch (Opc) {
2330 case Instruction::Add:
2331 case Instruction::Sub:
2332 case Instruction::Mul:
2333 case Instruction::UDiv:
2334 case Instruction::SDiv:
2335 case Instruction::URem:
2336 case Instruction::SRem:
2337 if (!Val0->getType()->isIntOrIntVectorTy())
2338 return Error(ID.Loc, "constexpr requires integer operands");
2339 break;
2340 case Instruction::FAdd:
2341 case Instruction::FSub:
2342 case Instruction::FMul:
2343 case Instruction::FDiv:
2344 case Instruction::FRem:
2345 if (!Val0->getType()->isFPOrFPVectorTy())
2346 return Error(ID.Loc, "constexpr requires fp operands");
2347 break;
2348 default: llvm_unreachable("Unknown binary operator!");
2349 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002350 unsigned Flags = 0;
2351 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2352 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2353 if (Exact) Flags |= SDivOperator::IsExact;
2354 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002355 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002356 ID.Kind = ValID::t_Constant;
2357 return false;
2358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002359
Chris Lattnerdf986172009-01-02 07:01:27 +00002360 // Logical Operations
2361 case lltok::kw_shl:
2362 case lltok::kw_lshr:
2363 case lltok::kw_ashr:
2364 case lltok::kw_and:
2365 case lltok::kw_or:
2366 case lltok::kw_xor: {
2367 unsigned Opc = Lex.getUIntVal();
2368 Constant *Val0, *Val1;
2369 Lex.Lex();
2370 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2371 ParseGlobalTypeAndValue(Val0) ||
2372 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2373 ParseGlobalTypeAndValue(Val1) ||
2374 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2375 return true;
2376 if (Val0->getType() != Val1->getType())
2377 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002378 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002379 return Error(ID.Loc,
2380 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002381 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002382 ID.Kind = ValID::t_Constant;
2383 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002384 }
2385
Chris Lattnerdf986172009-01-02 07:01:27 +00002386 case lltok::kw_getelementptr:
2387 case lltok::kw_shufflevector:
2388 case lltok::kw_insertelement:
2389 case lltok::kw_extractelement:
2390 case lltok::kw_select: {
2391 unsigned Opc = Lex.getUIntVal();
2392 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002393 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002394 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002395 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002396 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002397 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2398 ParseGlobalValueVector(Elts) ||
2399 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2400 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Chris Lattnerdf986172009-01-02 07:01:27 +00002402 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002403 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002404 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattnerdf986172009-01-02 07:01:27 +00002406 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
Eli Friedman4e9bac32009-07-24 21:56:17 +00002407 (Value**)(Elts.data() + 1),
2408 Elts.size() - 1))
Chris Lattnerdf986172009-01-02 07:01:27 +00002409 return Error(ID.Loc, "invalid indices for getelementptr");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002410 ID.ConstantVal = InBounds ?
2411 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2412 Elts.data() + 1,
2413 Elts.size() - 1) :
2414 ConstantExpr::getGetElementPtr(Elts[0],
2415 Elts.data() + 1, Elts.size() - 1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002416 } else if (Opc == Instruction::Select) {
2417 if (Elts.size() != 3)
2418 return Error(ID.Loc, "expected three operands to select");
2419 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2420 Elts[2]))
2421 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002422 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002423 } else if (Opc == Instruction::ShuffleVector) {
2424 if (Elts.size() != 3)
2425 return Error(ID.Loc, "expected three operands to shufflevector");
2426 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2427 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002428 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002429 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002430 } else if (Opc == Instruction::ExtractElement) {
2431 if (Elts.size() != 2)
2432 return Error(ID.Loc, "expected two operands to extractelement");
2433 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2434 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002435 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002436 } else {
2437 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2438 if (Elts.size() != 3)
2439 return Error(ID.Loc, "expected three operands to insertelement");
2440 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2441 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002442 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002443 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 ID.Kind = ValID::t_Constant;
2447 return false;
2448 }
2449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002450
Chris Lattnerdf986172009-01-02 07:01:27 +00002451 Lex.Lex();
2452 return false;
2453}
2454
2455/// ParseGlobalValue - Parse a global value with the specified type.
Victor Hernandez92f238d2010-01-11 22:31:58 +00002456bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2457 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002458 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002459 Value *V = NULL;
2460 bool Parsed = ParseValID(ID) ||
2461 ConvertValIDToValue(Ty, ID, V, NULL);
2462 if (V && !(C = dyn_cast<Constant>(V)))
2463 return Error(ID.Loc, "global values must be constants");
2464 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002465}
2466
Victor Hernandez92f238d2010-01-11 22:31:58 +00002467bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2468 PATypeHolder Type(Type::getVoidTy(Context));
2469 return ParseType(Type) ||
2470 ParseGlobalValue(Type, V);
2471}
2472
2473/// ParseGlobalValueVector
2474/// ::= /*empty*/
2475/// ::= TypeAndValue (',' TypeAndValue)*
2476bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2477 // Empty list.
2478 if (Lex.getKind() == lltok::rbrace ||
2479 Lex.getKind() == lltok::rsquare ||
2480 Lex.getKind() == lltok::greater ||
2481 Lex.getKind() == lltok::rparen)
2482 return false;
2483
2484 Constant *C;
2485 if (ParseGlobalTypeAndValue(C)) return true;
2486 Elts.push_back(C);
2487
2488 while (EatIfPresent(lltok::comma)) {
2489 if (ParseGlobalTypeAndValue(C)) return true;
2490 Elts.push_back(C);
2491 }
2492
2493 return false;
2494}
2495
Dan Gohman309b3af2010-08-24 02:24:03 +00002496bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2497 assert(Lex.getKind() == lltok::lbrace);
2498 Lex.Lex();
2499
2500 SmallVector<Value*, 16> Elts;
2501 if (ParseMDNodeVector(Elts, PFS) ||
2502 ParseToken(lltok::rbrace, "expected end of metadata node"))
2503 return true;
2504
2505 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2506 ID.Kind = ValID::t_MDNode;
2507 return false;
2508}
2509
Dan Gohman83448032010-07-14 18:26:50 +00002510/// ParseMetadataValue
2511/// ::= !42
2512/// ::= !{...}
2513/// ::= !"string"
2514bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2515 assert(Lex.getKind() == lltok::exclaim);
2516 Lex.Lex();
2517
2518 // MDNode:
2519 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002520 if (Lex.getKind() == lltok::lbrace)
2521 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002522
2523 // Standalone metadata reference
2524 // !42
2525 if (Lex.getKind() == lltok::APSInt) {
2526 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2527 ID.Kind = ValID::t_MDNode;
2528 return false;
2529 }
2530
2531 // MDString:
2532 // ::= '!' STRINGCONSTANT
2533 if (ParseMDString(ID.MDStringVal)) return true;
2534 ID.Kind = ValID::t_MDString;
2535 return false;
2536}
2537
Victor Hernandez92f238d2010-01-11 22:31:58 +00002538
2539//===----------------------------------------------------------------------===//
2540// Function Parsing.
2541//===----------------------------------------------------------------------===//
2542
2543bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2544 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002545 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002546 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002547
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002549 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002550 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002551 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2552 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2553 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002554 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002555 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2556 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2557 return (V == 0);
2558 case ValID::t_InlineAsm: {
2559 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2560 const FunctionType *FTy =
2561 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2562 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2563 return Error(ID.Loc, "invalid type for inline asm constraint string");
2564 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2565 return false;
2566 }
2567 case ValID::t_MDNode:
2568 if (!Ty->isMetadataTy())
2569 return Error(ID.Loc, "metadata value must have metadata type");
2570 V = ID.MDNodeVal;
2571 return false;
2572 case ValID::t_MDString:
2573 if (!Ty->isMetadataTy())
2574 return Error(ID.Loc, "metadata value must have metadata type");
2575 V = ID.MDStringVal;
2576 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002577 case ValID::t_GlobalName:
2578 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2579 return V == 0;
2580 case ValID::t_GlobalID:
2581 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2582 return V == 0;
2583 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002584 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002585 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002586 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002587 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 return false;
2589 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002590 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002591 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2592 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002593
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 // The lexer has no type info, so builds all float and double FP constants
2595 // as double. Fix this here. Long double does not need this.
2596 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002597 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 bool Ignored;
2599 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2600 &Ignored);
2601 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002602 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002603
Chris Lattner959873d2009-01-05 18:24:23 +00002604 if (V->getType() != Ty)
2605 return Error(ID.Loc, "floating point constant does not have type '" +
2606 Ty->getDescription() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002607
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 return false;
2609 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002610 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002611 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002612 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002613 return false;
2614 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002615 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002616 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
Duncan Sands47c51882010-02-16 14:50:09 +00002617 !Ty->isOpaqueTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002618 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002619 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002620 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002621 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002622 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002623 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002624 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002625 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002626 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002627 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002628 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002629 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002630 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002631 return false;
2632 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002633 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002634 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002635
Chris Lattnerdf986172009-01-02 07:01:27 +00002636 V = ID.ConstantVal;
2637 return false;
2638 }
2639}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002640
Chris Lattnerdf986172009-01-02 07:01:27 +00002641bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2642 V = 0;
2643 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00002644 return ParseValID(ID, &PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00002645 ConvertValIDToValue(Ty, ID, V, &PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002646}
2647
2648bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002649 PATypeHolder T(Type::getVoidTy(Context));
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002650 return ParseType(T) ||
2651 ParseValue(T, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002652}
2653
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002654bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2655 PerFunctionState &PFS) {
2656 Value *V;
2657 Loc = Lex.getLoc();
2658 if (ParseTypeAndValue(V, PFS)) return true;
2659 if (!isa<BasicBlock>(V))
2660 return Error(Loc, "expected a basic block");
2661 BB = cast<BasicBlock>(V);
2662 return false;
2663}
2664
2665
Chris Lattnerdf986172009-01-02 07:01:27 +00002666/// FunctionHeader
2667/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002668/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002669/// OptionalAlign OptGC
2670bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2671 // Parse the linkage.
2672 LocTy LinkageLoc = Lex.getLoc();
2673 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002674
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002675 unsigned Visibility, RetAttrs;
Rafael Espindolabea46262011-01-08 16:42:36 +00002676 bool UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +00002677 LocTy UnnamedAddrLoc;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002678 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00002679 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00002680 LocTy RetTypeLoc = Lex.getLoc();
2681 if (ParseOptionalLinkage(Linkage) ||
2682 ParseOptionalVisibility(Visibility) ||
2683 ParseOptionalCallingConv(CC) ||
2684 ParseOptionalAttrs(RetAttrs, 1) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +00002685 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2686 &UnnamedAddrLoc) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002687 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002688 return true;
2689
Rafael Espindolad72479c2011-01-13 01:30:30 +00002690 if (!isDefine && UnnamedAddr)
2691 return Error(UnnamedAddrLoc, "only definitions can have unnamed_addr");
2692
Chris Lattnerdf986172009-01-02 07:01:27 +00002693 // Verify that the linkage is ok.
2694 switch ((GlobalValue::LinkageTypes)Linkage) {
2695 case GlobalValue::ExternalLinkage:
2696 break; // always ok.
2697 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002698 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002699 if (isDefine)
2700 return Error(LinkageLoc, "invalid linkage for function definition");
2701 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002702 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002703 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002704 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002705 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002706 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002707 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002708 case GlobalValue::LinkOnceAnyLinkage:
2709 case GlobalValue::LinkOnceODRLinkage:
2710 case GlobalValue::WeakAnyLinkage:
2711 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002712 case GlobalValue::DLLExportLinkage:
2713 if (!isDefine)
2714 return Error(LinkageLoc, "invalid linkage for function declaration");
2715 break;
2716 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002717 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 return Error(LinkageLoc, "invalid function linkage type");
2719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattner99bb3152009-01-05 08:00:30 +00002721 if (!FunctionType::isValidReturnType(RetType) ||
Duncan Sands47c51882010-02-16 14:50:09 +00002722 RetType->isOpaqueTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002726
2727 std::string FunctionName;
2728 if (Lex.getKind() == lltok::GlobalVar) {
2729 FunctionName = Lex.getStrVal();
2730 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2731 unsigned NameID = Lex.getUIntVal();
2732
2733 if (NameID != NumberedVals.size())
2734 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002735 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002736 } else {
2737 return TokError("expected function name");
2738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002740 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002741
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002742 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002743 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002744
Chris Lattnerdf986172009-01-02 07:01:27 +00002745 std::vector<ArgInfo> ArgList;
2746 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002749 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002750 std::string GC;
2751
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00002752 if (ParseArgumentList(ArgList, isVarArg, false) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002753 ParseOptionalAttrs(FuncAttrs, 2) ||
2754 (EatIfPresent(lltok::kw_section) &&
2755 ParseStringConstant(Section)) ||
2756 ParseOptionalAlignment(Alignment) ||
2757 (EatIfPresent(lltok::kw_gc) &&
2758 ParseStringConstant(GC)))
2759 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002760
2761 // If the alignment was parsed as an attribute, move to the alignment field.
2762 if (FuncAttrs & Attribute::Alignment) {
2763 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2764 FuncAttrs &= ~Attribute::Alignment;
2765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 // Okay, if we got here, the function is syntactically valid. Convert types
2768 // and do semantic checks.
2769 std::vector<const Type*> ParamTypeList;
2770 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002771 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
Chris Lattnerdf986172009-01-02 07:01:27 +00002772 // attributes.
2773 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2774 if (FuncAttrs & ObsoleteFuncAttrs) {
2775 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2776 FuncAttrs &= ~ObsoleteFuncAttrs;
2777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Chris Lattnerdf986172009-01-02 07:01:27 +00002779 if (RetAttrs != Attribute::None)
2780 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattnerdf986172009-01-02 07:01:27 +00002782 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2783 ParamTypeList.push_back(ArgList[i].Type);
2784 if (ArgList[i].Attrs != Attribute::None)
2785 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2786 }
2787
2788 if (FuncAttrs != Attribute::None)
2789 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2790
2791 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002792
Benjamin Kramerf0127052010-01-05 13:12:22 +00002793 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2795
Owen Andersonfba933c2009-07-01 23:57:11 +00002796 const FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002797 FunctionType::get(RetType, ParamTypeList, isVarArg);
2798 const PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002799
2800 Fn = 0;
2801 if (!FunctionName.empty()) {
2802 // If this was a definition of a forward reference, remove the definition
2803 // from the forward reference table and fill in the forward ref.
2804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2805 ForwardRefVals.find(FunctionName);
2806 if (FRVI != ForwardRefVals.end()) {
2807 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002808 if (Fn->getType() != PFT)
2809 return Error(FRVI->second.second, "invalid forward reference to "
2810 "function '" + FunctionName + "' with wrong type!");
2811
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 ForwardRefVals.erase(FRVI);
2813 } else if ((Fn = M->getFunction(FunctionName))) {
2814 // If this function already exists in the symbol table, then it is
2815 // multiply defined. We accept a few cases for old backwards compat.
2816 // FIXME: Remove this stuff for LLVM 3.0.
2817 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2818 (!Fn->isDeclaration() && isDefine)) {
2819 // If the redefinition has different type or different attributes,
2820 // reject it. If both have bodies, reject it.
2821 return Error(NameLoc, "invalid redefinition of function '" +
2822 FunctionName + "'");
2823 } else if (Fn->isDeclaration()) {
2824 // Make sure to strip off any argument names so we can't get conflicts.
2825 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2826 AI != AE; ++AI)
2827 AI->setName("");
2828 }
Chris Lattner1d871c52009-10-25 23:22:50 +00002829 } else if (M->getNamedValue(FunctionName)) {
2830 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002831 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002832
Dan Gohman41905542009-08-29 23:37:49 +00002833 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 // If this is a definition of a forward referenced function, make sure the
2835 // types agree.
2836 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2837 = ForwardRefValIDs.find(NumberedVals.size());
2838 if (I != ForwardRefValIDs.end()) {
2839 Fn = cast<Function>(I->second.first);
2840 if (Fn->getType() != PFT)
2841 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002842 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002843 ForwardRefValIDs.erase(I);
2844 }
2845 }
2846
2847 if (Fn == 0)
2848 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2849 else // Move the forward-reference to the correct spot in the module.
2850 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2851
2852 if (FunctionName.empty())
2853 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002854
Chris Lattnerdf986172009-01-02 07:01:27 +00002855 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2856 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2857 Fn->setCallingConv(CC);
2858 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002859 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 Fn->setAlignment(Alignment);
2861 Fn->setSection(Section);
2862 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002863
Chris Lattnerdf986172009-01-02 07:01:27 +00002864 // Add all of the arguments we parsed to the function.
2865 Function::arg_iterator ArgIt = Fn->arg_begin();
2866 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
Chris Lattner5bda3792009-11-26 22:48:23 +00002867 // If we run out of arguments in the Function prototype, exit early.
2868 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2869 if (ArgIt == Fn->arg_end()) break;
2870
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 // If the argument has a name, insert it into the argument symbol table.
2872 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002873
Chris Lattnerdf986172009-01-02 07:01:27 +00002874 // Set the name, if it conflicted, it will be auto-renamed.
2875 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002876
Benjamin Krameraf812352010-10-16 11:28:23 +00002877 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2879 ArgList[i].Name + "'");
2880 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002881
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 return false;
2883}
2884
2885
2886/// ParseFunctionBody
2887/// ::= '{' BasicBlock+ '}'
2888/// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2889///
2890bool LLParser::ParseFunctionBody(Function &Fn) {
2891 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2892 return TokError("expected '{' in function body");
2893 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Chris Lattner09d9ef42009-10-28 03:39:23 +00002895 int FunctionNumber = -1;
2896 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2897
2898 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002899
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002900 // We need at least one basic block.
2901 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2902 return TokError("function body requires at least one basic block");
2903
Chris Lattnerdf986172009-01-02 07:01:27 +00002904 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2905 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002906
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 // Eat the }.
2908 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002909
Chris Lattnerdf986172009-01-02 07:01:27 +00002910 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002911 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002912}
2913
2914/// ParseBasicBlock
2915/// ::= LabelStr? Instruction*
2916bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2917 // If this basic block starts out with a name, remember it.
2918 std::string Name;
2919 LocTy NameLoc = Lex.getLoc();
2920 if (Lex.getKind() == lltok::LabelStr) {
2921 Name = Lex.getStrVal();
2922 Lex.Lex();
2923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2926 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002929
Chris Lattnerdf986172009-01-02 07:01:27 +00002930 // Parse the instructions in this block until we get a terminator.
2931 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002932 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002933 do {
2934 // This instruction may have three possibilities for a name: a) none
2935 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2936 LocTy NameLoc = Lex.getLoc();
2937 int NameID = -1;
2938 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002939
Chris Lattnerdf986172009-01-02 07:01:27 +00002940 if (Lex.getKind() == lltok::LocalVarID) {
2941 NameID = Lex.getUIntVal();
2942 Lex.Lex();
2943 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2944 return true;
2945 } else if (Lex.getKind() == lltok::LocalVar ||
2946 // FIXME: REMOVE IN LLVM 3.0
2947 Lex.getKind() == lltok::StringConstant) {
2948 NameStr = Lex.getStrVal();
2949 Lex.Lex();
2950 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2951 return true;
2952 }
Devang Patelf633a062009-09-17 23:04:48 +00002953
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002954 switch (ParseInstruction(Inst, BB, PFS)) {
2955 default: assert(0 && "Unknown ParseInstruction result!");
2956 case InstError: return true;
2957 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002958 BB->getInstList().push_back(Inst);
2959
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002960 // With a normal result, we check to see if the instruction is followed by
2961 // a comma and metadata.
2962 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002963 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002964 return true;
2965 break;
2966 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002967 BB->getInstList().push_back(Inst);
2968
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002969 // If the instruction parser ate an extra comma at the end of it, it
2970 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002971 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002972 return true;
2973 break;
2974 }
Devang Patelf633a062009-09-17 23:04:48 +00002975
Chris Lattnerdf986172009-01-02 07:01:27 +00002976 // Set the name on the instruction.
2977 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2978 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002979
Chris Lattnerdf986172009-01-02 07:01:27 +00002980 return false;
2981}
2982
2983//===----------------------------------------------------------------------===//
2984// Instruction Parsing.
2985//===----------------------------------------------------------------------===//
2986
2987/// ParseInstruction - Parse one of the many different instructions.
2988///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002989int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2990 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002991 lltok::Kind Token = Lex.getKind();
2992 if (Token == lltok::Eof)
2993 return TokError("found end of file when expecting more instructions");
2994 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002995 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002996 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002997
Chris Lattnerdf986172009-01-02 07:01:27 +00002998 switch (Token) {
2999 default: return Error(Loc, "expected instruction opcode");
3000 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00003001 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3002 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003003 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3004 case lltok::kw_br: return ParseBr(Inst, PFS);
3005 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00003006 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003007 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3008 // Binary Operators.
3009 case lltok::kw_add:
3010 case lltok::kw_sub:
Dan Gohman59858cf2009-07-27 16:11:46 +00003011 case lltok::kw_mul: {
3012 bool NUW = false;
3013 bool NSW = false;
3014 LocTy ModifierLoc = Lex.getLoc();
3015 if (EatIfPresent(lltok::kw_nuw))
3016 NUW = true;
3017 if (EatIfPresent(lltok::kw_nsw)) {
3018 NSW = true;
3019 if (EatIfPresent(lltok::kw_nuw))
3020 NUW = true;
3021 }
Dan Gohman1eaac532010-05-03 22:44:19 +00003022 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
Dan Gohman59858cf2009-07-27 16:11:46 +00003023 if (!Result) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003024 if (!Inst->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00003025 if (NUW)
3026 return Error(ModifierLoc, "nuw only applies to integer operations");
3027 if (NSW)
3028 return Error(ModifierLoc, "nsw only applies to integer operations");
3029 }
3030 if (NUW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003031 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003032 if (NSW)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003033 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003034 }
3035 return Result;
3036 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003037 case lltok::kw_fadd:
3038 case lltok::kw_fsub:
3039 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3040
Dan Gohman59858cf2009-07-27 16:11:46 +00003041 case lltok::kw_sdiv: {
3042 bool Exact = false;
3043 if (EatIfPresent(lltok::kw_exact))
3044 Exact = true;
3045 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3046 if (!Result)
3047 if (Exact)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003048 cast<BinaryOperator>(Inst)->setIsExact(true);
Dan Gohman59858cf2009-07-27 16:11:46 +00003049 return Result;
3050 }
3051
Chris Lattnerdf986172009-01-02 07:01:27 +00003052 case lltok::kw_udiv:
Chris Lattnerdf986172009-01-02 07:01:27 +00003053 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003054 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00003055 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003056 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00003057 case lltok::kw_shl:
3058 case lltok::kw_lshr:
3059 case lltok::kw_ashr:
3060 case lltok::kw_and:
3061 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003062 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003063 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003064 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003065 // Casts.
3066 case lltok::kw_trunc:
3067 case lltok::kw_zext:
3068 case lltok::kw_sext:
3069 case lltok::kw_fptrunc:
3070 case lltok::kw_fpext:
3071 case lltok::kw_bitcast:
3072 case lltok::kw_uitofp:
3073 case lltok::kw_sitofp:
3074 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00003075 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003077 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00003078 // Other.
3079 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00003080 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003081 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3082 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3083 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3084 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3085 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3086 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3087 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003088 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3089 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
Victor Hernandez66284e02009-10-24 04:23:03 +00003090 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3092 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3093 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003094 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003096 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 return ParseStore(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003098 else
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003100 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3101 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3102 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3103 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3104 }
3105}
3106
3107/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3108bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003109 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003110 switch (Lex.getKind()) {
3111 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3112 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3113 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3114 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3115 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3116 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3117 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3118 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3119 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3120 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3121 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3122 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3123 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3124 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3125 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3126 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3127 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3128 }
3129 } else {
3130 switch (Lex.getKind()) {
3131 default: TokError("expected icmp predicate (e.g. 'eq')");
3132 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3133 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3134 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3135 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3136 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3137 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3138 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3139 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3140 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3141 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3142 }
3143 }
3144 Lex.Lex();
3145 return false;
3146}
3147
3148//===----------------------------------------------------------------------===//
3149// Terminator Instructions.
3150//===----------------------------------------------------------------------===//
3151
3152/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003153/// ::= 'ret' void (',' !dbg, !1)*
3154/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3155/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
Devang Patelf633a062009-09-17 23:04:48 +00003156/// [[obsolete: LLVM 3.0]]
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003157int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3158 PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003159 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnera9a9e072009-03-09 04:49:14 +00003160 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003161
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003162 if (Ty->isVoidTy()) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003163 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003164 return false;
3165 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003166
Chris Lattnerdf986172009-01-02 07:01:27 +00003167 Value *RV;
3168 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003169
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003170 bool ExtraComma = false;
Devang Patelf633a062009-09-17 23:04:48 +00003171 if (EatIfPresent(lltok::comma)) {
Devang Patel0475c912009-09-29 00:01:14 +00003172 // Parse optional custom metadata, e.g. !dbg
Chris Lattner1d928312009-12-30 05:02:06 +00003173 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003174 ExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003175 } else {
3176 // The normal case is one return value.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003177 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3178 // use of 'ret {i32,i32} {i32 1, i32 2}'
Devang Patelf633a062009-09-17 23:04:48 +00003179 SmallVector<Value*, 8> RVs;
3180 RVs.push_back(RV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003181
Devang Patelf633a062009-09-17 23:04:48 +00003182 do {
Devang Patel0475c912009-09-29 00:01:14 +00003183 // If optional custom metadata, e.g. !dbg is seen then this is the
3184 // end of MRV.
Chris Lattner1d928312009-12-30 05:02:06 +00003185 if (Lex.getKind() == lltok::MetadataVar)
Daniel Dunbara279bc32009-09-20 02:20:51 +00003186 break;
3187 if (ParseTypeAndValue(RV, PFS)) return true;
3188 RVs.push_back(RV);
Devang Patelf633a062009-09-17 23:04:48 +00003189 } while (EatIfPresent(lltok::comma));
3190
3191 RV = UndefValue::get(PFS.getFunction().getReturnType());
3192 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00003193 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3194 BB->getInstList().push_back(I);
3195 RV = I;
Devang Patelf633a062009-09-17 23:04:48 +00003196 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 }
3198 }
Devang Patelf633a062009-09-17 23:04:48 +00003199
Owen Anderson1d0be152009-08-13 21:58:54 +00003200 Inst = ReturnInst::Create(Context, RV);
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00003201 return ExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003202}
3203
3204
3205/// ParseBr
3206/// ::= 'br' TypeAndValue
3207/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3208bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3209 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003210 Value *Op0;
3211 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003212 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003213
Chris Lattnerdf986172009-01-02 07:01:27 +00003214 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3215 Inst = BranchInst::Create(BB);
3216 return false;
3217 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003218
Owen Anderson1d0be152009-08-13 21:58:54 +00003219 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003220 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003221
Chris Lattnerdf986172009-01-02 07:01:27 +00003222 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003223 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003224 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003225 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003226 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003227
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003228 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 return false;
3230}
3231
3232/// ParseSwitch
3233/// Instruction
3234/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3235/// JumpTable
3236/// ::= (TypeAndValue ',' TypeAndValue)*
3237bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3238 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003239 Value *Cond;
3240 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003241 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3242 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003243 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3245 return true;
3246
Duncan Sands1df98592010-02-16 11:11:14 +00003247 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 // Parse the jump table pairs.
3251 SmallPtrSet<Value*, 32> SeenCases;
3252 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3253 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003254 Value *Constant;
3255 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3258 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003259 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003260 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003261
Chris Lattnerdf986172009-01-02 07:01:27 +00003262 if (!SeenCases.insert(Constant))
3263 return Error(CondLoc, "duplicate case value in switch");
3264 if (!isa<ConstantInt>(Constant))
3265 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003266
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003267 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003268 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003269
Chris Lattnerdf986172009-01-02 07:01:27 +00003270 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003271
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003272 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003273 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3274 SI->addCase(Table[i].first, Table[i].second);
3275 Inst = SI;
3276 return false;
3277}
3278
Chris Lattnerab21db72009-10-28 00:19:10 +00003279/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003280/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003281/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3282bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003283 LocTy AddrLoc;
3284 Value *Address;
3285 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003286 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3287 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003288 return true;
3289
Duncan Sands1df98592010-02-16 11:11:14 +00003290 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003291 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003292
3293 // Parse the destination list.
3294 SmallVector<BasicBlock*, 16> DestList;
3295
3296 if (Lex.getKind() != lltok::rsquare) {
3297 BasicBlock *DestBB;
3298 if (ParseTypeAndBasicBlock(DestBB, PFS))
3299 return true;
3300 DestList.push_back(DestBB);
3301
3302 while (EatIfPresent(lltok::comma)) {
3303 if (ParseTypeAndBasicBlock(DestBB, PFS))
3304 return true;
3305 DestList.push_back(DestBB);
3306 }
3307 }
3308
3309 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3310 return true;
3311
Chris Lattnerab21db72009-10-28 00:19:10 +00003312 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003313 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3314 IBI->addDestination(DestList[i]);
3315 Inst = IBI;
3316 return false;
3317}
3318
3319
Chris Lattnerdf986172009-01-02 07:01:27 +00003320/// ParseInvoke
3321/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3322/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3323bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3324 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003325 unsigned RetAttrs, FnAttrs;
3326 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003327 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003328 LocTy RetTypeLoc;
3329 ValID CalleeID;
3330 SmallVector<ParamInfo, 16> ArgList;
3331
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003332 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 if (ParseOptionalCallingConv(CC) ||
3334 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003335 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 ParseValID(CalleeID) ||
3337 ParseParameterList(ArgList, PFS) ||
3338 ParseOptionalAttrs(FnAttrs, 2) ||
3339 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003340 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003342 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003344
Chris Lattnerdf986172009-01-02 07:01:27 +00003345 // If RetType is a non-function pointer type, then this is the short syntax
3346 // for the call, which means that RetType is just the return type. Infer the
3347 // rest of the function argument types from the arguments that are present.
3348 const PointerType *PFTy = 0;
3349 const FunctionType *Ty = 0;
3350 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3351 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3352 // Pull out the types of all of the arguments...
3353 std::vector<const Type*> ParamTypes;
3354 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3355 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003356
Chris Lattnerdf986172009-01-02 07:01:27 +00003357 if (!FunctionType::isValidReturnType(RetType))
3358 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003359
Owen Andersondebcb012009-07-29 22:17:13 +00003360 Ty = FunctionType::get(RetType, ParamTypes, false);
3361 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003362 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003363
Chris Lattnerdf986172009-01-02 07:01:27 +00003364 // Look up the callee.
3365 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003366 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003367
Chris Lattnerdf986172009-01-02 07:01:27 +00003368 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3369 // function attributes.
3370 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3371 if (FnAttrs & ObsoleteFuncAttrs) {
3372 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3373 FnAttrs &= ~ObsoleteFuncAttrs;
3374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003375
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 // Set up the Attributes for the function.
3377 SmallVector<AttributeWithIndex, 8> Attrs;
3378 if (RetAttrs != Attribute::None)
3379 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003380
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003382
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 // Loop through FunctionType's arguments and ensure they are specified
3384 // correctly. Also, gather any parameter attributes.
3385 FunctionType::param_iterator I = Ty->param_begin();
3386 FunctionType::param_iterator E = Ty->param_end();
3387 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3388 const Type *ExpectedTy = 0;
3389 if (I != E) {
3390 ExpectedTy = *I++;
3391 } else if (!Ty->isVarArg()) {
3392 return Error(ArgList[i].Loc, "too many arguments specified");
3393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3396 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3397 ExpectedTy->getDescription() + "'");
3398 Args.push_back(ArgList[i].V);
3399 if (ArgList[i].Attrs != Attribute::None)
3400 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3401 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003402
Chris Lattnerdf986172009-01-02 07:01:27 +00003403 if (I != E)
3404 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003405
Chris Lattnerdf986172009-01-02 07:01:27 +00003406 if (FnAttrs != Attribute::None)
3407 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003408
Chris Lattnerdf986172009-01-02 07:01:27 +00003409 // Finish off the Attributes and check them
3410 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003411
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003412 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
Chris Lattnerdf986172009-01-02 07:01:27 +00003413 Args.begin(), Args.end());
3414 II->setCallingConv(CC);
3415 II->setAttributes(PAL);
3416 Inst = II;
3417 return false;
3418}
3419
3420
3421
3422//===----------------------------------------------------------------------===//
3423// Binary Operators.
3424//===----------------------------------------------------------------------===//
3425
3426/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003427/// ::= ArithmeticOps TypeAndValue ',' Value
3428///
3429/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3430/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003431bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003432 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003433 LocTy Loc; Value *LHS, *RHS;
3434 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3435 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3436 ParseValue(LHS->getType(), RHS, PFS))
3437 return true;
3438
Chris Lattnere914b592009-01-05 08:24:46 +00003439 bool Valid;
3440 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003441 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003442 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003443 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3444 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003445 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003446 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3447 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003448 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003449
Chris Lattnere914b592009-01-05 08:24:46 +00003450 if (!Valid)
3451 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003452
Chris Lattnerdf986172009-01-02 07:01:27 +00003453 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3454 return false;
3455}
3456
3457/// ParseLogical
3458/// ::= ArithmeticOps TypeAndValue ',' Value {
3459bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3460 unsigned Opc) {
3461 LocTy Loc; Value *LHS, *RHS;
3462 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3463 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3464 ParseValue(LHS->getType(), RHS, PFS))
3465 return true;
3466
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003467 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 return Error(Loc,"instruction requires integer or integer vector operands");
3469
3470 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3471 return false;
3472}
3473
3474
3475/// ParseCompare
3476/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3477/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003478bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3479 unsigned Opc) {
3480 // Parse the integer/fp comparison predicate.
3481 LocTy Loc;
3482 unsigned Pred;
3483 Value *LHS, *RHS;
3484 if (ParseCmpPredicate(Pred, Opc) ||
3485 ParseTypeAndValue(LHS, Loc, PFS) ||
3486 ParseToken(lltok::comma, "expected ',' after compare value") ||
3487 ParseValue(LHS->getType(), RHS, PFS))
3488 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003489
Chris Lattnerdf986172009-01-02 07:01:27 +00003490 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003491 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003493 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003494 } else {
3495 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003496 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003497 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003498 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003499 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 }
3501 return false;
3502}
3503
3504//===----------------------------------------------------------------------===//
3505// Other Instructions.
3506//===----------------------------------------------------------------------===//
3507
3508
3509/// ParseCast
3510/// ::= CastOpc TypeAndValue 'to' Type
3511bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3512 unsigned Opc) {
3513 LocTy Loc; Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003514 PATypeHolder DestTy(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003515 if (ParseTypeAndValue(Op, Loc, PFS) ||
3516 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3517 ParseType(DestTy))
3518 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003519
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003520 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3521 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003522 return Error(Loc, "invalid cast opcode for cast from '" +
3523 Op->getType()->getDescription() + "' to '" +
3524 DestTy->getDescription() + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003525 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3527 return false;
3528}
3529
3530/// ParseSelect
3531/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3532bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3533 LocTy Loc;
3534 Value *Op0, *Op1, *Op2;
3535 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after select condition") ||
3537 ParseTypeAndValue(Op1, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after select 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 (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3543 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003544
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 Inst = SelectInst::Create(Op0, Op1, Op2);
3546 return false;
3547}
3548
Chris Lattner0088a5c2009-01-05 08:18:44 +00003549/// ParseVA_Arg
3550/// ::= 'va_arg' TypeAndValue ',' Type
3551bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003552 Value *Op;
Owen Anderson1d0be152009-08-13 21:58:54 +00003553 PATypeHolder EltTy(Type::getVoidTy(Context));
Chris Lattner0088a5c2009-01-05 08:18:44 +00003554 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003555 if (ParseTypeAndValue(Op, PFS) ||
3556 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003557 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003558 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003559
Chris Lattner0088a5c2009-01-05 08:18:44 +00003560 if (!EltTy->isFirstClassType())
3561 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003562
3563 Inst = new VAArgInst(Op, EltTy);
3564 return false;
3565}
3566
3567/// ParseExtractElement
3568/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3569bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3570 LocTy Loc;
3571 Value *Op0, *Op1;
3572 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3573 ParseToken(lltok::comma, "expected ',' after extract value") ||
3574 ParseTypeAndValue(Op1, PFS))
3575 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003576
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3578 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003579
Eric Christophera3500da2009-07-25 02:28:41 +00003580 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003581 return false;
3582}
3583
3584/// ParseInsertElement
3585/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3586bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3587 LocTy Loc;
3588 Value *Op0, *Op1, *Op2;
3589 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3590 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3591 ParseTypeAndValue(Op1, PFS) ||
3592 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3593 ParseTypeAndValue(Op2, PFS))
3594 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003595
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003597 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003598
Chris Lattnerdf986172009-01-02 07:01:27 +00003599 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3600 return false;
3601}
3602
3603/// ParseShuffleVector
3604/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3605bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3606 LocTy Loc;
3607 Value *Op0, *Op1, *Op2;
3608 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3609 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3610 ParseTypeAndValue(Op1, PFS) ||
3611 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3612 ParseTypeAndValue(Op2, PFS))
3613 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003614
Chris Lattnerdf986172009-01-02 07:01:27 +00003615 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3616 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003617
Chris Lattnerdf986172009-01-02 07:01:27 +00003618 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3619 return false;
3620}
3621
3622/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003623/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003624int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003625 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003626 Value *Op0, *Op1;
3627 LocTy TypeLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003628
Chris Lattnerdf986172009-01-02 07:01:27 +00003629 if (ParseType(Ty) ||
3630 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3631 ParseValue(Ty, Op0, PFS) ||
3632 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003633 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003634 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3635 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003636
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003637 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003638 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3639 while (1) {
3640 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003641
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003642 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 break;
3644
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003645 if (Lex.getKind() == lltok::MetadataVar) {
3646 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003647 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003648 }
Devang Patela43d46f2009-10-16 18:45:49 +00003649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003650 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003651 ParseValue(Ty, Op0, PFS) ||
3652 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003653 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003654 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3655 return true;
3656 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003657
Chris Lattnerdf986172009-01-02 07:01:27 +00003658 if (!Ty->isFirstClassType())
3659 return Error(TypeLoc, "phi node must have first class type");
3660
3661 PHINode *PN = PHINode::Create(Ty);
3662 PN->reserveOperandSpace(PHIVals.size());
3663 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3664 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3665 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003666 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003667}
3668
3669/// ParseCall
3670/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3671/// ParameterList OptionalAttrs
3672bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3673 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003674 unsigned RetAttrs, FnAttrs;
3675 CallingConv::ID CC;
Owen Anderson1d0be152009-08-13 21:58:54 +00003676 PATypeHolder RetType(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003677 LocTy RetTypeLoc;
3678 ValID CalleeID;
3679 SmallVector<ParamInfo, 16> ArgList;
3680 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003681
Chris Lattnerdf986172009-01-02 07:01:27 +00003682 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3683 ParseOptionalCallingConv(CC) ||
3684 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003685 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003686 ParseValID(CalleeID) ||
3687 ParseParameterList(ArgList, PFS) ||
3688 ParseOptionalAttrs(FnAttrs, 2))
3689 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003690
Chris Lattnerdf986172009-01-02 07:01:27 +00003691 // If RetType is a non-function pointer type, then this is the short syntax
3692 // for the call, which means that RetType is just the return type. Infer the
3693 // rest of the function argument types from the arguments that are present.
3694 const PointerType *PFTy = 0;
3695 const FunctionType *Ty = 0;
3696 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3697 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3698 // Pull out the types of all of the arguments...
3699 std::vector<const Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003700 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3701 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003702
Chris Lattnerdf986172009-01-02 07:01:27 +00003703 if (!FunctionType::isValidReturnType(RetType))
3704 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003705
Owen Andersondebcb012009-07-29 22:17:13 +00003706 Ty = FunctionType::get(RetType, ParamTypes, false);
3707 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003709
Chris Lattnerdf986172009-01-02 07:01:27 +00003710 // Look up the callee.
3711 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003712 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003713
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3715 // function attributes.
3716 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3717 if (FnAttrs & ObsoleteFuncAttrs) {
3718 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3719 FnAttrs &= ~ObsoleteFuncAttrs;
3720 }
3721
3722 // Set up the Attributes for the function.
3723 SmallVector<AttributeWithIndex, 8> Attrs;
3724 if (RetAttrs != Attribute::None)
3725 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003726
Chris Lattnerdf986172009-01-02 07:01:27 +00003727 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003728
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 // Loop through FunctionType's arguments and ensure they are specified
3730 // correctly. Also, gather any parameter attributes.
3731 FunctionType::param_iterator I = Ty->param_begin();
3732 FunctionType::param_iterator E = Ty->param_end();
3733 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3734 const Type *ExpectedTy = 0;
3735 if (I != E) {
3736 ExpectedTy = *I++;
3737 } else if (!Ty->isVarArg()) {
3738 return Error(ArgList[i].Loc, "too many arguments specified");
3739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003740
Chris Lattnerdf986172009-01-02 07:01:27 +00003741 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3742 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3743 ExpectedTy->getDescription() + "'");
3744 Args.push_back(ArgList[i].V);
3745 if (ArgList[i].Attrs != Attribute::None)
3746 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003748
Chris Lattnerdf986172009-01-02 07:01:27 +00003749 if (I != E)
3750 return Error(CallLoc, "not enough parameters specified for call");
3751
3752 if (FnAttrs != Attribute::None)
3753 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3754
3755 // Finish off the Attributes and check them
3756 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003757
Chris Lattnerdf986172009-01-02 07:01:27 +00003758 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3759 CI->setTailCall(isTail);
3760 CI->setCallingConv(CC);
3761 CI->setAttributes(PAL);
3762 Inst = CI;
3763 return false;
3764}
3765
3766//===----------------------------------------------------------------------===//
3767// Memory Instructions.
3768//===----------------------------------------------------------------------===//
3769
3770/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003771/// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3772/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003773int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3774 BasicBlock* BB, bool isAlloca) {
Owen Anderson1d0be152009-08-13 21:58:54 +00003775 PATypeHolder Ty(Type::getVoidTy(Context));
Chris Lattnerdf986172009-01-02 07:01:27 +00003776 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003777 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003778 unsigned Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003779 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003780
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003781 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003782 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003783 if (Lex.getKind() == lltok::kw_align) {
3784 if (ParseOptionalAlignment(Alignment)) return true;
3785 } else if (Lex.getKind() == lltok::MetadataVar) {
3786 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003787 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003788 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3789 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3790 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003791 }
3792 }
3793
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003794 if (Size && !Size->getType()->isIntegerTy())
3795 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003796
Victor Hernandez68afa542009-10-21 19:11:40 +00003797 if (isAlloca) {
Owen Anderson50dead02009-07-15 23:53:25 +00003798 Inst = new AllocaInst(Ty, Size, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003799 return AteExtraComma ? InstExtraComma : InstNormal;
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00003800 }
Victor Hernandez68afa542009-10-21 19:11:40 +00003801
3802 // Autoupgrade old malloc instruction to malloc call.
3803 // FIXME: Remove in LLVM 3.0.
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003804 if (Size && !Size->getType()->isIntegerTy(32))
3805 return Error(SizeLoc, "element count must be i32");
Victor Hernandez68afa542009-10-21 19:11:40 +00003806 const Type *IntPtrTy = Type::getInt32Ty(Context);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003807 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3808 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
Victor Hernandez68afa542009-10-21 19:11:40 +00003809 if (!MallocF)
3810 // Prototype malloc as "void *(int32)".
3811 // This function is renamed as "malloc" in ValidateEndOfModule().
Victor Hernandez336ea062009-10-23 00:59:10 +00003812 MallocF = cast<Function>(
3813 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
Victor Hernandez9d0b7042009-11-07 00:16:28 +00003814 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003815return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003816}
3817
3818/// ParseFree
3819/// ::= 'free' TypeAndValue
Victor Hernandez66284e02009-10-24 04:23:03 +00003820bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3821 BasicBlock* BB) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003822 Value *Val; LocTy Loc;
3823 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003824 if (!Val->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003825 return Error(Loc, "operand to free must be a pointer");
Victor Hernandez66284e02009-10-24 04:23:03 +00003826 Inst = CallInst::CreateFree(Val, BB);
Chris Lattnerdf986172009-01-02 07:01:27 +00003827 return false;
3828}
3829
3830/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003831/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003832int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3833 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003834 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003835 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003836 bool AteExtraComma = false;
3837 if (ParseTypeAndValue(Val, Loc, PFS) ||
3838 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3839 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003840
Duncan Sands1df98592010-02-16 11:11:14 +00003841 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003842 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3843 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003844
Chris Lattnerdf986172009-01-02 07:01:27 +00003845 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003846 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003847}
3848
3849/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003850/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003851int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3852 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003853 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003854 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003855 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003856 if (ParseTypeAndValue(Val, Loc, PFS) ||
3857 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003858 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3859 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003860 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003861
Duncan Sands1df98592010-02-16 11:11:14 +00003862 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003863 return Error(PtrLoc, "store operand must be a pointer");
3864 if (!Val->getType()->isFirstClassType())
3865 return Error(Loc, "store operand must be a first class value");
3866 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3867 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003868
Chris Lattnerdf986172009-01-02 07:01:27 +00003869 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003870 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003871}
3872
3873/// ParseGetResult
Dan Gohmana119de82009-06-14 23:30:43 +00003874/// ::= 'getresult' TypeAndValue ',' i32
Chris Lattnerdf986172009-01-02 07:01:27 +00003875/// FIXME: Remove support for getresult in LLVM 3.0
3876bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3877 Value *Val; LocTy ValLoc, EltLoc;
3878 unsigned Element;
3879 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003881 ParseUInt32(Element, EltLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003882 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003883
Duncan Sands1df98592010-02-16 11:11:14 +00003884 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003885 return Error(ValLoc, "getresult inst requires an aggregate operand");
3886 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3887 return Error(EltLoc, "invalid getresult index for value");
3888 Inst = ExtractValueInst::Create(Val, Element);
3889 return false;
3890}
3891
3892/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003893/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003894int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003895 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003896
Dan Gohmandcb40a32009-07-29 15:58:36 +00003897 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003898
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003899 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003900
Duncan Sands1df98592010-02-16 11:11:14 +00003901 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003902 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003903
Chris Lattnerdf986172009-01-02 07:01:27 +00003904 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003905 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003906 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003907 if (Lex.getKind() == lltok::MetadataVar) {
3908 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003909 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003910 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003911 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003912 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003913 return Error(EltLoc, "getelementptr index must be an integer");
3914 Indices.push_back(Val);
3915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003916
Chris Lattnerdf986172009-01-02 07:01:27 +00003917 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3918 Indices.begin(), Indices.end()))
3919 return Error(Loc, "invalid getelementptr indices");
3920 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00003921 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003922 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003923 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003924}
3925
3926/// ParseExtractValue
3927/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003928int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003929 Value *Val; LocTy Loc;
3930 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003931 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003932 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003933 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003934 return true;
3935
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003936 if (!Val->getType()->isAggregateType())
3937 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003938
3939 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3940 Indices.end()))
3941 return Error(Loc, "invalid indices for extractvalue");
3942 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003943 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003944}
3945
3946/// ParseInsertValue
3947/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003948int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003949 Value *Val0, *Val1; LocTy Loc0, Loc1;
3950 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003951 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003952 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3953 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3954 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003955 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003956 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003957
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003958 if (!Val0->getType()->isAggregateType())
3959 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003960
Chris Lattnerdf986172009-01-02 07:01:27 +00003961 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3962 Indices.end()))
3963 return Error(Loc0, "invalid indices for insertvalue");
3964 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003965 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003966}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003967
3968//===----------------------------------------------------------------------===//
3969// Embedded metadata.
3970//===----------------------------------------------------------------------===//
3971
3972/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003973/// ::= Element (',' Element)*
3974/// Element
3975/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003976bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003977 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003978 // Check for an empty list.
3979 if (Lex.getKind() == lltok::rbrace)
3980 return false;
3981
Nick Lewycky21cc4462009-04-04 07:22:01 +00003982 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003983 // Null is a special case since it is typeless.
3984 if (EatIfPresent(lltok::kw_null)) {
3985 Elts.push_back(0);
3986 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003987 }
Chris Lattnera7352392009-12-30 04:42:57 +00003988
3989 Value *V = 0;
3990 PATypeHolder Ty(Type::getVoidTy(Context));
3991 ValID ID;
Victor Hernandezbf170d42010-01-05 22:22:14 +00003992 if (ParseType(Ty) || ParseValID(ID, PFS) ||
Victor Hernandez92f238d2010-01-11 22:31:58 +00003993 ConvertValIDToValue(Ty, ID, V, PFS))
Chris Lattnera7352392009-12-30 04:42:57 +00003994 return true;
3995
Nick Lewyckycb337992009-05-10 20:57:05 +00003996 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003997 } while (EatIfPresent(lltok::comma));
3998
3999 return false;
4000}