blob: e056f69cd702a5f081ae008e3592a2511edbe4c7 [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 Lattnerdb125cf2011-07-18 04:54:35 +000029static std::string getTypeString(Type *T) {
Chris Lattner0cd0d882011-06-18 21:18:23 +000030 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
34}
35
Chris Lattner3ed88ef2009-01-02 08:05:26 +000036/// Run: module ::= toplevelentity*
Chris Lattnerad7d1e22009-01-04 20:44:11 +000037bool LLParser::Run() {
Chris Lattner3ed88ef2009-01-02 08:05:26 +000038 // Prime the lexer.
39 Lex.Lex();
40
Chris Lattnerad7d1e22009-01-04 20:44:11 +000041 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
Chris Lattnerdf986172009-01-02 07:01:27 +000043}
44
45/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46/// module.
47bool LLParser::ValidateEndOfModule() {
Chris Lattner449c3102010-04-01 05:14:45 +000048 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52 I != E; ++I) {
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
55
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
58
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +000061 Twine(SlotNo) + "'");
Chris Lattner449c3102010-04-01 05:14:45 +000062 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
67
68
Chris Lattner09d9ef42009-10-28 03:39:23 +000069 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
73 Function *TheFn = 0;
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
79
80 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
82
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
88
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
91
Chris Lattner1afcace2011-07-09 17:41:24 +000092 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
96
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000102
Chris Lattnerdf986172009-01-02 07:01:27 +0000103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
106 "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000107
Chris Lattnerdf986172009-01-02 07:01:27 +0000108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000111 Twine(ForwardRefValIDs.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000112
Devang Patel1c7eea62009-07-08 19:23:54 +0000113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000116 Twine(ForwardRefMDNodes.begin()->first) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000117
Devang Patel1c7eea62009-07-08 19:23:54 +0000118
Chris Lattnerdf986172009-01-02 07:01:27 +0000119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Chris Lattnerdf986172009-01-02 07:01:27 +0000123 return false;
124}
125
Chris Lattner09d9ef42009-10-28 03:39:23 +0000126bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
131 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000132 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000135 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000139 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000140 } else {
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
143 }
144
Chris Lattnercdfc9402009-11-01 01:27:45 +0000145 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
148
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
153 }
154 return false;
155}
156
157
Chris Lattnerdf986172009-01-02 07:01:27 +0000158//===----------------------------------------------------------------------===//
159// Top-Level Entities
160//===----------------------------------------------------------------------===//
161
162bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000163 while (1) {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000178
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000187 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
193 case lltok::kw_appending: // OptionalLinkage
194 case lltok::kw_dllexport: // OptionalLinkage
195 case lltok::kw_common: // OptionalLinkage
196 case lltok::kw_dllimport: // OptionalLinkage
197 case lltok::kw_extern_weak: // OptionalLinkage
198 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000199 unsigned Linkage, Visibility;
200 if (ParseOptionalLinkage(Linkage) ||
201 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000202 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000203 return true;
204 break;
205 }
206 case lltok::kw_default: // OptionalVisibility
207 case lltok::kw_hidden: // OptionalVisibility
208 case lltok::kw_protected: { // OptionalVisibility
209 unsigned Visibility;
210 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000211 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000212 return true;
213 break;
214 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000215
Chris Lattnerdf986172009-01-02 07:01:27 +0000216 case lltok::kw_thread_local: // OptionalThreadLocal
217 case lltok::kw_addrspace: // OptionalAddrSpace
218 case lltok::kw_constant: // GlobalType
219 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000220 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000221 break;
222 }
223 }
224}
225
226
227/// toplevelentity
228/// ::= 'module' 'asm' STRINGCONSTANT
229bool LLParser::ParseModuleAsm() {
230 assert(Lex.getKind() == lltok::kw_module);
231 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000232
233 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000234 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
235 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000236
Rafael Espindola38c4e532011-03-02 04:14:42 +0000237 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000238 return false;
239}
240
241/// toplevelentity
242/// ::= 'target' 'triple' '=' STRINGCONSTANT
243/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
244bool LLParser::ParseTargetDefinition() {
245 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000246 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000247 switch (Lex.Lex()) {
248 default: return TokError("unknown target property");
249 case lltok::kw_triple:
250 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000251 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
252 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000253 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000254 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return false;
256 case lltok::kw_datalayout:
257 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000258 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
259 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000260 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000261 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000262 return false;
263 }
264}
265
266/// toplevelentity
267/// ::= 'deplibs' '=' '[' ']'
268/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
269bool LLParser::ParseDepLibs() {
270 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000271 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000272 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
273 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
274 return true;
275
276 if (EatIfPresent(lltok::rsquare))
277 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000278
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000279 std::string Str;
280 if (ParseStringConstant(Str)) return true;
281 M->addLibrary(Str);
282
283 while (EatIfPresent(lltok::comma)) {
284 if (ParseStringConstant(Str)) return true;
285 M->addLibrary(Str);
286 }
287
288 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000289}
290
Dan Gohman3845e502009-08-12 23:32:33 +0000291/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000292/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000293bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000294 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000295 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000296 Lex.Lex(); // eat LocalVarID;
297
298 if (ParseToken(lltok::equal, "expected '=' after name") ||
299 ParseToken(lltok::kw_type, "expected 'type' after '='"))
300 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000301
Chris Lattner1afcace2011-07-09 17:41:24 +0000302 if (TypeID >= NumberedTypes.size())
303 NumberedTypes.resize(TypeID+1);
304
305 Type *Result = 0;
306 if (ParseStructDefinition(TypeLoc, "",
307 NumberedTypes[TypeID], Result)) return true;
308
309 if (!isa<StructType>(Result)) {
310 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
311 if (Entry.first)
312 return Error(TypeLoc, "non-struct types may not be recursive");
313 Entry.first = Result;
314 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000316
Chris Lattnerdf986172009-01-02 07:01:27 +0000317 return false;
318}
319
Chris Lattner1afcace2011-07-09 17:41:24 +0000320
Chris Lattnerdf986172009-01-02 07:01:27 +0000321/// toplevelentity
322/// ::= LocalVar '=' 'type' type
323bool LLParser::ParseNamedType() {
324 std::string Name = Lex.getStrVal();
325 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000326 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000328 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000329 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000330 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000331
332 Type *Result = 0;
333 if (ParseStructDefinition(NameLoc, Name,
334 NamedTypes[Name], Result)) return true;
335
336 if (!isa<StructType>(Result)) {
337 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
338 if (Entry.first)
339 return Error(NameLoc, "non-struct types may not be recursive");
340 Entry.first = Result;
341 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000342 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000343
344 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000345}
346
347
348/// toplevelentity
349/// ::= 'declare' FunctionHeader
350bool LLParser::ParseDeclare() {
351 assert(Lex.getKind() == lltok::kw_declare);
352 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000353
Chris Lattnerdf986172009-01-02 07:01:27 +0000354 Function *F;
355 return ParseFunctionHeader(F, false);
356}
357
358/// toplevelentity
359/// ::= 'define' FunctionHeader '{' ...
360bool LLParser::ParseDefine() {
361 assert(Lex.getKind() == lltok::kw_define);
362 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000363
Chris Lattnerdf986172009-01-02 07:01:27 +0000364 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000365 return ParseFunctionHeader(F, true) ||
366 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000367}
368
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000369/// ParseGlobalType
370/// ::= 'constant'
371/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000372bool LLParser::ParseGlobalType(bool &IsConstant) {
373 if (Lex.getKind() == lltok::kw_constant)
374 IsConstant = true;
375 else if (Lex.getKind() == lltok::kw_global)
376 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000377 else {
378 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000379 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000380 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 Lex.Lex();
382 return false;
383}
384
Dan Gohman3845e502009-08-12 23:32:33 +0000385/// ParseUnnamedGlobal:
386/// OptionalVisibility ALIAS ...
387/// OptionalLinkage OptionalVisibility ... -> global variable
388/// GlobalID '=' OptionalVisibility ALIAS ...
389/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
390bool LLParser::ParseUnnamedGlobal() {
391 unsigned VarID = NumberedVals.size();
392 std::string Name;
393 LocTy NameLoc = Lex.getLoc();
394
395 // Handle the GlobalID form.
396 if (Lex.getKind() == lltok::GlobalID) {
397 if (Lex.getUIntVal() != VarID)
398 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000399 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000400 Lex.Lex(); // eat GlobalID;
401
402 if (ParseToken(lltok::equal, "expected '=' after name"))
403 return true;
404 }
405
406 bool HasLinkage;
407 unsigned Linkage, Visibility;
408 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
409 ParseOptionalVisibility(Visibility))
410 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Dan Gohman3845e502009-08-12 23:32:33 +0000412 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
413 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
414 return ParseAlias(Name, NameLoc, Visibility);
415}
416
Chris Lattnerdf986172009-01-02 07:01:27 +0000417/// ParseNamedGlobal:
418/// GlobalVar '=' OptionalVisibility ALIAS ...
419/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
420bool LLParser::ParseNamedGlobal() {
421 assert(Lex.getKind() == lltok::GlobalVar);
422 LocTy NameLoc = Lex.getLoc();
423 std::string Name = Lex.getStrVal();
424 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattnerdf986172009-01-02 07:01:27 +0000426 bool HasLinkage;
427 unsigned Linkage, Visibility;
428 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
429 ParseOptionalLinkage(Linkage, HasLinkage) ||
430 ParseOptionalVisibility(Visibility))
431 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000432
Chris Lattnerdf986172009-01-02 07:01:27 +0000433 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
434 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
435 return ParseAlias(Name, NameLoc, Visibility);
436}
437
Devang Patel256be962009-07-20 19:00:08 +0000438// MDString:
439// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000440bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000441 std::string Str;
442 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000443 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000444 return false;
445}
446
447// MDNode:
448// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000449//
450/// This version of ParseMDNodeID returns the slot number and null in the case
451/// of a forward reference.
452bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
453 // !{ ..., !42, ... }
454 if (ParseUInt32(SlotNo)) return true;
455
456 // Check existing MDNode.
457 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
458 Result = NumberedMetadata[SlotNo];
459 else
460 Result = 0;
461 return false;
462}
463
Chris Lattner4a72efc2009-12-30 04:15:23 +0000464bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000465 // !{ ..., !42, ... }
466 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000467 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000468
Chris Lattner449c3102010-04-01 05:14:45 +0000469 // If not a forward reference, just return it now.
470 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000471
Chris Lattner449c3102010-04-01 05:14:45 +0000472 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000473 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000474 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000475
476 if (NumberedMetadata.size() <= MID)
477 NumberedMetadata.resize(MID+1);
478 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000479 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000480 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000481}
Devang Patel256be962009-07-20 19:00:08 +0000482
Chris Lattner84d03b12009-12-29 22:35:39 +0000483/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000484/// !foo = !{ !1, !2 }
485bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000486 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000487 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000488 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000489
Chris Lattner84d03b12009-12-29 22:35:39 +0000490 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000491 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000492 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000493 return true;
494
Dan Gohman17aa92c2010-07-21 23:38:33 +0000495 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000496 if (Lex.getKind() != lltok::rbrace)
497 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000498 if (ParseToken(lltok::exclaim, "Expected '!' here"))
499 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000500
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000501 MDNode *N = 0;
502 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000503 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000504 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000505
506 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
507 return true;
508
Devang Pateleff2ab62009-07-29 00:34:02 +0000509 return false;
510}
511
Devang Patel923078c2009-07-01 19:21:12 +0000512/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000513/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000514bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000515 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000516 Lex.Lex();
517 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000518
519 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000520 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000521 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000522 if (ParseUInt32(MetadataID) ||
523 ParseToken(lltok::equal, "expected '=' here") ||
524 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000525 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000526 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000527 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000528 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000529 return true;
530
Jay Foadec9186b2011-04-21 19:59:31 +0000531 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000532
533 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000534 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000535 FI = ForwardRefMDNodes.find(MetadataID);
536 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000537 MDNode *Temp = FI->second.first;
538 Temp->replaceAllUsesWith(Init);
539 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000540 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000541
542 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
543 } else {
544 if (MetadataID >= NumberedMetadata.size())
545 NumberedMetadata.resize(MetadataID+1);
546
547 if (NumberedMetadata[MetadataID] != 0)
548 return TokError("Metadata id is already used");
549 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000550 }
551
Devang Patel923078c2009-07-01 19:21:12 +0000552 return false;
553}
554
Chris Lattnerdf986172009-01-02 07:01:27 +0000555/// ParseAlias:
556/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
557/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000558/// ::= TypeAndValue
559/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000560/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000561///
562/// Everything through visibility has already been parsed.
563///
564bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
565 unsigned Visibility) {
566 assert(Lex.getKind() == lltok::kw_alias);
567 Lex.Lex();
568 unsigned Linkage;
569 LocTy LinkageLoc = Lex.getLoc();
570 if (ParseOptionalLinkage(Linkage))
571 return true;
572
573 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000574 Linkage != GlobalValue::WeakAnyLinkage &&
575 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000576 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000577 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000578 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000579 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
580 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000581 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000582
Chris Lattnerdf986172009-01-02 07:01:27 +0000583 Constant *Aliasee;
584 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
588 } else {
589 // The bitcast dest type is not present, it is implied by the dest type.
590 ValID ID;
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
595 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000596
Duncan Sands1df98592010-02-16 11:11:14 +0000597 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000598 return Error(AliaseeLoc, "alias must have pointer type");
599
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
603 Aliasee);
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000605
Chris Lattnerdf986172009-01-02 07:01:27 +0000606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000608 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000609 // See if this was a redefinition. If so, there is no entry in
610 // ForwardRefVals.
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
615
616 // Otherwise, this was a definition of forward ref. Verify that types
617 // agree.
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000621
Chris Lattnerdf986172009-01-02 07:01:27 +0000622 // If they agree, just RAUW the old value with the alias and remove the
623 // forward ref info.
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000628
Chris Lattnerdf986172009-01-02 07:01:27 +0000629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000631 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000632
Chris Lattnerdf986172009-01-02 07:01:27 +0000633 return false;
634}
635
636/// ParseGlobal
637/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000638/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000639/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000640/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000641///
642/// Everything through visibility has been parsed already.
643///
644bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
647 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000648 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000649 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000650 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000651
Chris Lattner1afcace2011-07-09 17:41:24 +0000652 Type *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +0000653 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
654 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000655 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
656 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000657 ParseGlobalType(IsConstant) ||
658 ParseType(Ty, TyLoc))
659 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000660
Chris Lattnerdf986172009-01-02 07:01:27 +0000661 // If the linkage is specified and is external, then no initializer is
662 // present.
663 Constant *Init = 0;
664 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000665 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000666 Linkage != GlobalValue::ExternalLinkage)) {
667 if (ParseGlobalValue(Ty, Init))
668 return true;
669 }
670
Duncan Sands1df98592010-02-16 11:11:14 +0000671 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000672 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000673
Chris Lattnerdf986172009-01-02 07:01:27 +0000674 GlobalVariable *GV = 0;
675
676 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000677 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000678 if (GlobalValue *GVal = M->getNamedValue(Name)) {
679 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
680 return Error(NameLoc, "redefinition of global '@" + Name + "'");
681 GV = cast<GlobalVariable>(GVal);
682 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000683 } else {
684 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
685 I = ForwardRefValIDs.find(NumberedVals.size());
686 if (I != ForwardRefValIDs.end()) {
687 GV = cast<GlobalVariable>(I->second.first);
688 ForwardRefValIDs.erase(I);
689 }
690 }
691
692 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000693 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000694 Name, 0, false, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000695 } else {
696 if (GV->getType()->getElementType() != Ty)
697 return Error(TyLoc,
698 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000699
Chris Lattnerdf986172009-01-02 07:01:27 +0000700 // Move the forward-reference to the correct spot in the module.
701 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
702 }
703
704 if (Name.empty())
705 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000706
Chris Lattnerdf986172009-01-02 07:01:27 +0000707 // Set the parsed properties on the global.
708 if (Init)
709 GV->setInitializer(Init);
710 GV->setConstant(IsConstant);
711 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
712 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
713 GV->setThreadLocal(ThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +0000714 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000715
Chris Lattnerdf986172009-01-02 07:01:27 +0000716 // Parse attributes on the global.
717 while (Lex.getKind() == lltok::comma) {
718 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000719
Chris Lattnerdf986172009-01-02 07:01:27 +0000720 if (Lex.getKind() == lltok::kw_section) {
721 Lex.Lex();
722 GV->setSection(Lex.getStrVal());
723 if (ParseToken(lltok::StringConstant, "expected global section string"))
724 return true;
725 } else if (Lex.getKind() == lltok::kw_align) {
726 unsigned Alignment;
727 if (ParseOptionalAlignment(Alignment)) return true;
728 GV->setAlignment(Alignment);
729 } else {
730 TokError("unknown global variable property!");
731 }
732 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000733
Chris Lattnerdf986172009-01-02 07:01:27 +0000734 return false;
735}
736
737
738//===----------------------------------------------------------------------===//
739// GlobalValue Reference/Resolution Routines.
740//===----------------------------------------------------------------------===//
741
742/// GetGlobalVal - Get a value with the specified name or ID, creating a
743/// forward reference record if needed. This can return null if the value
744/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000746 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000747 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000748 if (PTy == 0) {
749 Error(Loc, "global variable reference must have pointer type");
750 return 0;
751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000752
Chris Lattnerdf986172009-01-02 07:01:27 +0000753 // Look this name up in the normal function symbol table.
754 GlobalValue *Val =
755 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756
Chris Lattnerdf986172009-01-02 07:01:27 +0000757 // If this is a forward reference for the value, see if we already created a
758 // forward ref record.
759 if (Val == 0) {
760 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
761 I = ForwardRefVals.find(Name);
762 if (I != ForwardRefVals.end())
763 Val = I->second.first;
764 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000765
Chris Lattnerdf986172009-01-02 07:01:27 +0000766 // If we have the value in the symbol table or fwd-ref table, return it.
767 if (Val) {
768 if (Val->getType() == Ty) return Val;
769 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000770 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000771 return 0;
772 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000773
Chris Lattnerdf986172009-01-02 07:01:27 +0000774 // Otherwise, create a new forward reference for this value and remember it.
775 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000776 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000777 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000778 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000779 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
780 GlobalValue::ExternalWeakLinkage, 0, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattnerdf986172009-01-02 07:01:27 +0000782 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
783 return FwdVal;
784}
785
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000786GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
787 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000788 if (PTy == 0) {
789 Error(Loc, "global variable reference must have pointer type");
790 return 0;
791 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Chris Lattnerdf986172009-01-02 07:01:27 +0000793 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 // If this is a forward reference for the value, see if we already created a
796 // forward ref record.
797 if (Val == 0) {
798 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
799 I = ForwardRefValIDs.find(ID);
800 if (I != ForwardRefValIDs.end())
801 Val = I->second.first;
802 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Chris Lattnerdf986172009-01-02 07:01:27 +0000804 // If we have the value in the symbol table or fwd-ref table, return it.
805 if (Val) {
806 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000807 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000808 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000809 return 0;
810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Chris Lattnerdf986172009-01-02 07:01:27 +0000812 // Otherwise, create a new forward reference for this value and remember it.
813 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000814 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000815 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000816 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000817 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
818 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Chris Lattnerdf986172009-01-02 07:01:27 +0000820 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
821 return FwdVal;
822}
823
824
825//===----------------------------------------------------------------------===//
826// Helper Routines.
827//===----------------------------------------------------------------------===//
828
829/// ParseToken - If the current token has the specified kind, eat it and return
830/// success. Otherwise, emit the specified error and return failure.
831bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
832 if (Lex.getKind() != T)
833 return TokError(ErrMsg);
834 Lex.Lex();
835 return false;
836}
837
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000838/// ParseStringConstant
839/// ::= StringConstant
840bool LLParser::ParseStringConstant(std::string &Result) {
841 if (Lex.getKind() != lltok::StringConstant)
842 return TokError("expected string constant");
843 Result = Lex.getStrVal();
844 Lex.Lex();
845 return false;
846}
847
848/// ParseUInt32
849/// ::= uint32
850bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000851 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
852 return TokError("expected integer");
853 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
854 if (Val64 != unsigned(Val64))
855 return TokError("expected 32-bit integer (too large)");
856 Val = Val64;
857 Lex.Lex();
858 return false;
859}
860
861
862/// ParseOptionalAddrSpace
863/// := /*empty*/
864/// := 'addrspace' '(' uint32 ')'
865bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
866 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000867 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000868 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000869 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000870 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000871 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000872}
Chris Lattnerdf986172009-01-02 07:01:27 +0000873
874/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
875/// indicates what kind of attribute list this is: 0: function arg, 1: result,
876/// 2: function attr.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000877bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000878 Attrs = Attribute::None;
879 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880
Chris Lattnerdf986172009-01-02 07:01:27 +0000881 while (1) {
882 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 default: // End of attributes.
884 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
885 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000886
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000887 // As a hack, we allow "align 2" on functions as a synonym for
888 // "alignstack 2".
889 if (AttrKind == 2 &&
890 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
891 return Error(AttrLoc, "invalid use of attribute on a function");
892
893 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000894 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000897 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
898 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
899 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
900 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
901 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
902 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
903 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
904 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000905
Devang Patel578efa92009-06-05 21:57:13 +0000906 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
907 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000908 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Rafael Espindola25456ef2011-10-03 14:45:37 +0000909 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
Devang Patel578efa92009-06-05 21:57:13 +0000910 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
911 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
912 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000913 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000914 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
915 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
916 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
917 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
918 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
919 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000920 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
John McCall3a3465b2011-06-15 20:36:13 +0000921 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000922 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923
Charles Davis1e063d12010-02-12 00:31:15 +0000924 case lltok::kw_alignstack: {
925 unsigned Alignment;
926 if (ParseOptionalStackAlignment(Alignment))
927 return true;
928 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
929 continue;
930 }
931
Chris Lattnerdf986172009-01-02 07:01:27 +0000932 case lltok::kw_align: {
933 unsigned Alignment;
934 if (ParseOptionalAlignment(Alignment))
935 return true;
936 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
937 continue;
938 }
Charles Davis1e063d12010-02-12 00:31:15 +0000939
Chris Lattnerdf986172009-01-02 07:01:27 +0000940 }
941 Lex.Lex();
942 }
943}
944
945/// ParseOptionalLinkage
946/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000947/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000948/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000949/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000950/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000951/// ::= 'internal'
952/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000953/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000954/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000955/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000956/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000957/// ::= 'appending'
958/// ::= 'dllexport'
959/// ::= 'common'
960/// ::= 'dllimport'
961/// ::= 'extern_weak'
962/// ::= 'external'
963bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
964 HasLinkage = false;
965 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000966 default: Res=GlobalValue::ExternalLinkage; return false;
967 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
968 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000969 case lltok::kw_linker_private_weak:
970 Res = GlobalValue::LinkerPrivateWeakLinkage;
971 break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000972 case lltok::kw_linker_private_weak_def_auto:
973 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
974 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000975 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
976 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
977 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
978 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
979 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000980 case lltok::kw_available_externally:
981 Res = GlobalValue::AvailableExternallyLinkage;
982 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000983 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
984 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
985 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
986 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
987 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
988 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000989 }
990 Lex.Lex();
991 HasLinkage = true;
992 return false;
993}
994
995/// ParseOptionalVisibility
996/// ::= /*empty*/
997/// ::= 'default'
998/// ::= 'hidden'
999/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001000///
Chris Lattnerdf986172009-01-02 07:01:27 +00001001bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1002 switch (Lex.getKind()) {
1003 default: Res = GlobalValue::DefaultVisibility; return false;
1004 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1005 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1006 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1007 }
1008 Lex.Lex();
1009 return false;
1010}
1011
1012/// ParseOptionalCallingConv
1013/// ::= /*empty*/
1014/// ::= 'ccc'
1015/// ::= 'fastcc'
1016/// ::= 'coldcc'
1017/// ::= 'x86_stdcallcc'
1018/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001019/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001020/// ::= 'arm_apcscc'
1021/// ::= 'arm_aapcscc'
1022/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001023/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001024/// ::= 'ptx_kernel'
1025/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001026/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001027///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001028bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001029 switch (Lex.getKind()) {
1030 default: CC = CallingConv::C; return false;
1031 case lltok::kw_ccc: CC = CallingConv::C; break;
1032 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1033 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1034 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1035 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001036 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001037 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1038 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1039 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001040 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001041 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1042 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001043 case lltok::kw_cc: {
1044 unsigned ArbitraryCC;
1045 Lex.Lex();
1046 if (ParseUInt32(ArbitraryCC)) {
1047 return true;
1048 } else
1049 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1050 return false;
1051 }
1052 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001053 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001054
Chris Lattnerdf986172009-01-02 07:01:27 +00001055 Lex.Lex();
1056 return false;
1057}
1058
Chris Lattnerb8c46862009-12-30 05:31:19 +00001059/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001060/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001061bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1062 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001063 do {
1064 if (Lex.getKind() != lltok::MetadataVar)
1065 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001066
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001067 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001068 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001069 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001070
Chris Lattner442ffa12009-12-29 21:53:55 +00001071 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001072 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001073
1074 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001075 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001076
Dan Gohman68261142010-08-24 14:35:45 +00001077 // This code is similar to that of ParseMetadataValue, however it needs to
1078 // have special-case code for a forward reference; see the comments on
1079 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1080 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001081 if (Lex.getKind() == lltok::lbrace) {
1082 ValID ID;
1083 if (ParseMetadataListValue(ID, PFS))
1084 return true;
1085 assert(ID.Kind == ValID::t_MDNode);
1086 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001087 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001088 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001089 if (ParseMDNodeID(Node, NodeID))
1090 return true;
1091 if (Node) {
1092 // If we got the node, add it to the instruction.
1093 Inst->setMetadata(MDK, Node);
1094 } else {
1095 MDRef R = { Loc, MDK, NodeID };
1096 // Otherwise, remember that this should be resolved later.
1097 ForwardRefInstMetadata[Inst].push_back(R);
1098 }
Chris Lattner449c3102010-04-01 05:14:45 +00001099 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001100
1101 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001102 } while (EatIfPresent(lltok::comma));
1103 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001104}
1105
Chris Lattnerdf986172009-01-02 07:01:27 +00001106/// ParseOptionalAlignment
1107/// ::= /* empty */
1108/// ::= 'align' 4
1109bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1110 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001111 if (!EatIfPresent(lltok::kw_align))
1112 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001113 LocTy AlignLoc = Lex.getLoc();
1114 if (ParseUInt32(Alignment)) return true;
1115 if (!isPowerOf2_32(Alignment))
1116 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001117 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001118 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001119 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001120}
1121
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001122/// ParseOptionalCommaAlign
1123/// ::=
1124/// ::= ',' align 4
1125///
1126/// This returns with AteExtraComma set to true if it ate an excess comma at the
1127/// end.
1128bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1129 bool &AteExtraComma) {
1130 AteExtraComma = false;
1131 while (EatIfPresent(lltok::comma)) {
1132 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001133 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001134 AteExtraComma = true;
1135 return false;
1136 }
1137
Chris Lattner093eed12010-04-23 00:50:50 +00001138 if (Lex.getKind() != lltok::kw_align)
1139 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001140
Chris Lattner093eed12010-04-23 00:50:50 +00001141 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001143
Devang Patelf633a062009-09-17 23:04:48 +00001144 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001145}
1146
Eli Friedman47f35132011-07-25 23:16:38 +00001147/// ParseScopeAndOrdering
1148/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1149/// else: ::=
1150///
1151/// This sets Scope and Ordering to the parsed values.
1152bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1153 AtomicOrdering &Ordering) {
1154 if (!isAtomic)
1155 return false;
1156
1157 Scope = CrossThread;
1158 if (EatIfPresent(lltok::kw_singlethread))
1159 Scope = SingleThread;
1160 switch (Lex.getKind()) {
1161 default: return TokError("Expected ordering on atomic instruction");
1162 case lltok::kw_unordered: Ordering = Unordered; break;
1163 case lltok::kw_monotonic: Ordering = Monotonic; break;
1164 case lltok::kw_acquire: Ordering = Acquire; break;
1165 case lltok::kw_release: Ordering = Release; break;
1166 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1167 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1168 }
1169 Lex.Lex();
1170 return false;
1171}
1172
Charles Davis1e063d12010-02-12 00:31:15 +00001173/// ParseOptionalStackAlignment
1174/// ::= /* empty */
1175/// ::= 'alignstack' '(' 4 ')'
1176bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1177 Alignment = 0;
1178 if (!EatIfPresent(lltok::kw_alignstack))
1179 return false;
1180 LocTy ParenLoc = Lex.getLoc();
1181 if (!EatIfPresent(lltok::lparen))
1182 return Error(ParenLoc, "expected '('");
1183 LocTy AlignLoc = Lex.getLoc();
1184 if (ParseUInt32(Alignment)) return true;
1185 ParenLoc = Lex.getLoc();
1186 if (!EatIfPresent(lltok::rparen))
1187 return Error(ParenLoc, "expected ')'");
1188 if (!isPowerOf2_32(Alignment))
1189 return Error(AlignLoc, "stack alignment is not a power of two");
1190 return false;
1191}
Devang Patelf633a062009-09-17 23:04:48 +00001192
Chris Lattner628c13a2009-12-30 05:14:00 +00001193/// ParseIndexList - This parses the index list for an insert/extractvalue
1194/// instruction. This sets AteExtraComma in the case where we eat an extra
1195/// comma at the end of the line and find that it is followed by metadata.
1196/// Clients that don't allow metadata can call the version of this function that
1197/// only takes one argument.
1198///
Chris Lattnerdf986172009-01-02 07:01:27 +00001199/// ParseIndexList
1200/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001201///
1202bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1203 bool &AteExtraComma) {
1204 AteExtraComma = false;
1205
Chris Lattnerdf986172009-01-02 07:01:27 +00001206 if (Lex.getKind() != lltok::comma)
1207 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001208
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001209 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001210 if (Lex.getKind() == lltok::MetadataVar) {
1211 AteExtraComma = true;
1212 return false;
1213 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001214 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001215 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001216 Indices.push_back(Idx);
1217 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001218
Chris Lattnerdf986172009-01-02 07:01:27 +00001219 return false;
1220}
1221
1222//===----------------------------------------------------------------------===//
1223// Type Parsing.
1224//===----------------------------------------------------------------------===//
1225
Chris Lattner1afcace2011-07-09 17:41:24 +00001226/// ParseType - Parse a type.
1227bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1228 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001229 switch (Lex.getKind()) {
1230 default:
1231 return TokError("expected type");
1232 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001233 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001234 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001235 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001236 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001238 // Type ::= StructType
1239 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001240 return true;
1241 break;
1242 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001243 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001244 Lex.Lex(); // eat the lsquare.
1245 if (ParseArrayVectorType(Result, false))
1246 return true;
1247 break;
1248 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001249 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001250 Lex.Lex();
1251 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001252 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001253 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001254 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 } else if (ParseArrayVectorType(Result, true))
1256 return true;
1257 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001258 case lltok::LocalVar: {
1259 // Type ::= %foo
1260 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1261
1262 // If the type hasn't been defined yet, create a forward definition and
1263 // remember where that forward def'n was seen (in case it never is defined).
1264 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001265 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001266 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001267 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001268 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 Lex.Lex();
1270 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001271 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001272
Chris Lattner1afcace2011-07-09 17:41:24 +00001273 case lltok::LocalVarID: {
1274 // Type ::= %4
1275 if (Lex.getUIntVal() >= NumberedTypes.size())
1276 NumberedTypes.resize(Lex.getUIntVal()+1);
1277 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1278
1279 // If the type hasn't been defined yet, create a forward definition and
1280 // remember where that forward def'n was seen (in case it never is defined).
1281 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001282 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001283 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001285 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001286 Lex.Lex();
1287 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001288 }
1289 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001290
1291 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001292 while (1) {
1293 switch (Lex.getKind()) {
1294 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001295 default:
1296 if (!AllowVoid && Result->isVoidTy())
1297 return Error(TypeLoc, "void type only allowed for function results");
1298 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001299
Chris Lattner1afcace2011-07-09 17:41:24 +00001300 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001301 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001302 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001303 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001304 if (Result->isVoidTy())
1305 return TokError("pointers to void are invalid - use i8* instead");
1306 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001307 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001308 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 Lex.Lex();
1310 break;
1311
Chris Lattner1afcace2011-07-09 17:41:24 +00001312 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001313 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001314 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001315 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001316 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001317 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001318 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001319 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001320 unsigned AddrSpace;
1321 if (ParseOptionalAddrSpace(AddrSpace) ||
1322 ParseToken(lltok::star, "expected '*' in address space"))
1323 return true;
1324
Chris Lattner1afcace2011-07-09 17:41:24 +00001325 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 break;
1327 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001328
Chris Lattnerdf986172009-01-02 07:01:27 +00001329 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1330 case lltok::lparen:
1331 if (ParseFunctionType(Result))
1332 return true;
1333 break;
1334 }
1335 }
1336}
1337
1338/// ParseParameterList
1339/// ::= '(' ')'
1340/// ::= '(' Arg (',' Arg)* ')'
1341/// Arg
1342/// ::= Type OptionalAttributes Value OptionalAttributes
1343bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1344 PerFunctionState &PFS) {
1345 if (ParseToken(lltok::lparen, "expected '(' in call"))
1346 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001347
Chris Lattnerdf986172009-01-02 07:01:27 +00001348 while (Lex.getKind() != lltok::rparen) {
1349 // If this isn't the first argument, we need a comma.
1350 if (!ArgList.empty() &&
1351 ParseToken(lltok::comma, "expected ',' in argument list"))
1352 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Chris Lattnerdf986172009-01-02 07:01:27 +00001354 // Parse the argument.
1355 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001356 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001357 Attributes ArgAttrs1;
1358 Attributes ArgAttrs2;
Chris Lattnerdf986172009-01-02 07:01:27 +00001359 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001360 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001361 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001362
Chris Lattner287881d2009-12-30 02:11:14 +00001363 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001364 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001365 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1367 }
1368
1369 Lex.Lex(); // Lex the ')'.
1370 return false;
1371}
1372
1373
1374
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001375/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001376/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001377/// ::= '(' ArgTypeListI ')'
1378/// ArgTypeListI
1379/// ::= /*empty*/
1380/// ::= '...'
1381/// ::= ArgTypeList ',' '...'
1382/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001383///
Chris Lattner1afcace2011-07-09 17:41:24 +00001384bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1385 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001386 isVarArg = false;
1387 assert(Lex.getKind() == lltok::lparen);
1388 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001389
Chris Lattnerdf986172009-01-02 07:01:27 +00001390 if (Lex.getKind() == lltok::rparen) {
1391 // empty
1392 } else if (Lex.getKind() == lltok::dotdotdot) {
1393 isVarArg = true;
1394 Lex.Lex();
1395 } else {
1396 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001397 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001398 Attributes Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001399 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400
Chris Lattner1afcace2011-07-09 17:41:24 +00001401 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001402 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001404 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001405 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001406
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001407 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001408 Name = Lex.getStrVal();
1409 Lex.Lex();
1410 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001411
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001412 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001413 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001414
Chris Lattnerdf986172009-01-02 07:01:27 +00001415 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001416
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001417 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001418 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001419 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001420 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 break;
1422 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001423
Chris Lattnerdf986172009-01-02 07:01:27 +00001424 // Otherwise must be an argument type.
1425 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001426 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001427
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001428 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001429 return Error(TypeLoc, "argument can not have void type");
1430
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001431 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001432 Name = Lex.getStrVal();
1433 Lex.Lex();
1434 } else {
1435 Name = "";
1436 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001437
Chris Lattner1afcace2011-07-09 17:41:24 +00001438 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001439 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001440
Chris Lattnerdf986172009-01-02 07:01:27 +00001441 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1442 }
1443 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001444
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001445 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001446}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001447
Chris Lattnerdf986172009-01-02 07:01:27 +00001448/// ParseFunctionType
1449/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001450bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001451 assert(Lex.getKind() == lltok::lparen);
1452
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001453 if (!FunctionType::isValidReturnType(Result))
1454 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001455
Chris Lattner1afcace2011-07-09 17:41:24 +00001456 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001457 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001458 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001459 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001460
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 // Reject names on the arguments lists.
1462 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1463 if (!ArgList[i].Name.empty())
1464 return Error(ArgList[i].Loc, "argument name invalid in function type");
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001465 if (ArgList[i].Attrs)
Chris Lattnera16546a2011-06-17 17:37:13 +00001466 return Error(ArgList[i].Loc,
1467 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001468 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001469
Jay Foad5fdd6c82011-07-12 14:06:48 +00001470 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001471 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001472 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001473
Chris Lattner1afcace2011-07-09 17:41:24 +00001474 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001475 return false;
1476}
1477
Chris Lattner1afcace2011-07-09 17:41:24 +00001478/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1479/// other structs.
1480bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1481 SmallVector<Type*, 8> Elts;
1482 if (ParseStructBody(Elts)) return true;
1483
1484 Result = StructType::get(Context, Elts, Packed);
1485 return false;
1486}
1487
1488/// ParseStructDefinition - Parse a struct in a 'type' definition.
1489bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1490 std::pair<Type*, LocTy> &Entry,
1491 Type *&ResultTy) {
1492 // If the type was already defined, diagnose the redefinition.
1493 if (Entry.first && !Entry.second.isValid())
1494 return Error(TypeLoc, "redefinition of type");
1495
1496 // If we have opaque, just return without filling in the definition for the
1497 // struct. This counts as a definition as far as the .ll file goes.
1498 if (EatIfPresent(lltok::kw_opaque)) {
1499 // This type is being defined, so clear the location to indicate this.
1500 Entry.second = SMLoc();
1501
1502 // If this type number has never been uttered, create it.
1503 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001504 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001505 ResultTy = Entry.first;
1506 return false;
1507 }
1508
1509 // If the type starts with '<', then it is either a packed struct or a vector.
1510 bool isPacked = EatIfPresent(lltok::less);
1511
1512 // If we don't have a struct, then we have a random type alias, which we
1513 // accept for compatibility with old files. These types are not allowed to be
1514 // forward referenced and not allowed to be recursive.
1515 if (Lex.getKind() != lltok::lbrace) {
1516 if (Entry.first)
1517 return Error(TypeLoc, "forward references to non-struct type");
1518
1519 ResultTy = 0;
1520 if (isPacked)
1521 return ParseArrayVectorType(ResultTy, true);
1522 return ParseType(ResultTy);
1523 }
1524
1525 // This type is being defined, so clear the location to indicate this.
1526 Entry.second = SMLoc();
1527
1528 // If this type number has never been uttered, create it.
1529 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001530 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001531
1532 StructType *STy = cast<StructType>(Entry.first);
1533
1534 SmallVector<Type*, 8> Body;
1535 if (ParseStructBody(Body) ||
1536 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1537 return true;
1538
1539 STy->setBody(Body, isPacked);
1540 ResultTy = STy;
1541 return false;
1542}
1543
1544
Chris Lattnerdf986172009-01-02 07:01:27 +00001545/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001546/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001547/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001548/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001549/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001550/// ::= '<' '{' Type (',' Type)* '}' '>'
1551bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001552 assert(Lex.getKind() == lltok::lbrace);
1553 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001554
Chris Lattner1afcace2011-07-09 17:41:24 +00001555 // Handle the empty struct.
1556 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001557 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001558
Chris Lattnera9a9e072009-03-09 04:49:14 +00001559 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001560 Type *Ty = 0;
1561 if (ParseType(Ty)) return true;
1562 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattner1afcace2011-07-09 17:41:24 +00001564 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001565 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001567 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001568 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001569 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattner1afcace2011-07-09 17:41:24 +00001571 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001572 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001573
Chris Lattner1afcace2011-07-09 17:41:24 +00001574 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001575 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattner1afcace2011-07-09 17:41:24 +00001577 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001578}
1579
1580/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1581/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001582/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001583/// ::= '[' APSINTVAL 'x' Types ']'
1584/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001585bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001586 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1587 Lex.getAPSIntVal().getBitWidth() > 64)
1588 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattnerdf986172009-01-02 07:01:27 +00001590 LocTy SizeLoc = Lex.getLoc();
1591 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001592 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001593
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001594 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1595 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001596
1597 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001598 Type *EltTy = 0;
1599 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001600
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001601 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1602 "expected end of sequential type"))
1603 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604
Chris Lattnerdf986172009-01-02 07:01:27 +00001605 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001606 if (Size == 0)
1607 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001608 if ((unsigned)Size != Size)
1609 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001610 if (!VectorType::isValidElementType(EltTy))
Nadav Rotem16087692011-12-05 06:29:09 +00001611 return Error(TypeLoc,
1612 "vector element type must be fp, integer or a pointer to these types");
Owen Andersondebcb012009-07-29 22:17:13 +00001613 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001614 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001615 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001617 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001618 }
1619 return false;
1620}
1621
1622//===----------------------------------------------------------------------===//
1623// Function Semantic Analysis.
1624//===----------------------------------------------------------------------===//
1625
Chris Lattner09d9ef42009-10-28 03:39:23 +00001626LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1627 int functionNumber)
1628 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001629
1630 // Insert unnamed arguments into the NumberedVals list.
1631 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1632 AI != E; ++AI)
1633 if (!AI->hasName())
1634 NumberedVals.push_back(AI);
1635}
1636
1637LLParser::PerFunctionState::~PerFunctionState() {
1638 // If there were any forward referenced non-basicblock values, delete them.
1639 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1640 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1641 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001642 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001643 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 delete I->second.first;
1645 I->second.first = 0;
1646 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1649 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1650 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001651 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001652 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 delete I->second.first;
1654 I->second.first = 0;
1655 }
1656}
1657
Chris Lattner09d9ef42009-10-28 03:39:23 +00001658bool LLParser::PerFunctionState::FinishFunction() {
1659 // Check to see if someone took the address of labels in this block.
1660 if (!P.ForwardRefBlockAddresses.empty()) {
1661 ValID FunctionID;
1662 if (!F.getName().empty()) {
1663 FunctionID.Kind = ValID::t_GlobalName;
1664 FunctionID.StrVal = F.getName();
1665 } else {
1666 FunctionID.Kind = ValID::t_GlobalID;
1667 FunctionID.UIntVal = FunctionNumber;
1668 }
1669
1670 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1671 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1672 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1673 // Resolve all these references.
1674 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1675 return true;
1676
1677 P.ForwardRefBlockAddresses.erase(FRBAI);
1678 }
1679 }
1680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 if (!ForwardRefVals.empty())
1682 return P.Error(ForwardRefVals.begin()->second.second,
1683 "use of undefined value '%" + ForwardRefVals.begin()->first +
1684 "'");
1685 if (!ForwardRefValIDs.empty())
1686 return P.Error(ForwardRefValIDs.begin()->second.second,
1687 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001688 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001689 return false;
1690}
1691
1692
1693/// GetVal - Get a value with the specified name or ID, creating a
1694/// forward reference record if needed. This can return null if the value
1695/// exists but does not have the right type.
1696Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001697 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 // Look this name up in the normal function symbol table.
1699 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 // If this is a forward reference for the value, see if we already created a
1702 // forward ref record.
1703 if (Val == 0) {
1704 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1705 I = ForwardRefVals.find(Name);
1706 if (I != ForwardRefVals.end())
1707 Val = I->second.first;
1708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 // If we have the value in the symbol table or fwd-ref table, return it.
1711 if (Val) {
1712 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001713 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 P.Error(Loc, "'%" + Name + "' is not a basic block");
1715 else
1716 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001717 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 return 0;
1719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001722 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 P.Error(Loc, "invalid use of a non-first-class type");
1724 return 0;
1725 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001726
Chris Lattnerdf986172009-01-02 07:01:27 +00001727 // Otherwise, create a new forward reference for this value and remember it.
1728 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001729 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001730 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001731 else
1732 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001733
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1735 return FwdVal;
1736}
1737
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001738Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 LocTy Loc) {
1740 // Look this name up in the normal function symbol table.
1741 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 // If this is a forward reference for the value, see if we already created a
1744 // forward ref record.
1745 if (Val == 0) {
1746 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1747 I = ForwardRefValIDs.find(ID);
1748 if (I != ForwardRefValIDs.end())
1749 Val = I->second.first;
1750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 // If we have the value in the symbol table or fwd-ref table, return it.
1753 if (Val) {
1754 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001755 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001756 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001758 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001759 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 return 0;
1761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattner1afcace2011-07-09 17:41:24 +00001763 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001764 P.Error(Loc, "invalid use of a non-first-class type");
1765 return 0;
1766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001767
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 // Otherwise, create a new forward reference for this value and remember it.
1769 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001770 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001771 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 else
1773 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001774
Chris Lattnerdf986172009-01-02 07:01:27 +00001775 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1776 return FwdVal;
1777}
1778
1779/// SetInstName - After an instruction is parsed and inserted into its
1780/// basic block, this installs its name.
1781bool LLParser::PerFunctionState::SetInstName(int NameID,
1782 const std::string &NameStr,
1783 LocTy NameLoc, Instruction *Inst) {
1784 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001785 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 if (NameID != -1 || !NameStr.empty())
1787 return P.Error(NameLoc, "instructions returning void cannot have a name");
1788 return false;
1789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001790
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 // If this was a numbered instruction, verify that the instruction is the
1792 // expected value and resolve any forward references.
1793 if (NameStr.empty()) {
1794 // If neither a name nor an ID was specified, just use the next ID.
1795 if (NameID == -1)
1796 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 if (unsigned(NameID) != NumberedVals.size())
1799 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001800 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001801
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1803 ForwardRefValIDs.find(NameID);
1804 if (FI != ForwardRefValIDs.end()) {
1805 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001807 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001809 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 ForwardRefValIDs.erase(FI);
1811 }
1812
1813 NumberedVals.push_back(Inst);
1814 return false;
1815 }
1816
1817 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1818 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1819 FI = ForwardRefVals.find(NameStr);
1820 if (FI != ForwardRefVals.end()) {
1821 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001822 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001823 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001825 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 ForwardRefVals.erase(FI);
1827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 // Set the name on the instruction.
1830 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Benjamin Krameraf812352010-10-16 11:28:23 +00001832 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001833 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001834 NameStr + "'");
1835 return false;
1836}
1837
1838/// GetBB - Get a basic block with the specified name or ID, creating a
1839/// forward reference record if needed.
1840BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1841 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001842 return cast_or_null<BasicBlock>(GetVal(Name,
1843 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001844}
1845
1846BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001847 return cast_or_null<BasicBlock>(GetVal(ID,
1848 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001849}
1850
1851/// DefineBB - Define the specified basic block, which is either named or
1852/// unnamed. If there is an error, this returns null otherwise it returns
1853/// the block being defined.
1854BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1855 LocTy Loc) {
1856 BasicBlock *BB;
1857 if (Name.empty())
1858 BB = GetBB(NumberedVals.size(), Loc);
1859 else
1860 BB = GetBB(Name, Loc);
1861 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 // Move the block to the end of the function. Forward ref'd blocks are
1864 // inserted wherever they happen to be referenced.
1865 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 // Remove the block from forward ref sets.
1868 if (Name.empty()) {
1869 ForwardRefValIDs.erase(NumberedVals.size());
1870 NumberedVals.push_back(BB);
1871 } else {
1872 // BB forward references are already in the function symbol table.
1873 ForwardRefVals.erase(Name);
1874 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 return BB;
1877}
1878
1879//===----------------------------------------------------------------------===//
1880// Constants.
1881//===----------------------------------------------------------------------===//
1882
1883/// ParseValID - Parse an abstract value that doesn't necessarily have a
1884/// type implied. For example, if we parse "4" we don't know what integer type
1885/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001886/// sanity. PFS is used to convert function-local operands of metadata (since
1887/// metadata operands are not just parsed here but also converted to values).
1888/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001889bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 ID.Loc = Lex.getLoc();
1891 switch (Lex.getKind()) {
1892 default: return TokError("expected value token");
1893 case lltok::GlobalID: // @42
1894 ID.UIntVal = Lex.getUIntVal();
1895 ID.Kind = ValID::t_GlobalID;
1896 break;
1897 case lltok::GlobalVar: // @foo
1898 ID.StrVal = Lex.getStrVal();
1899 ID.Kind = ValID::t_GlobalName;
1900 break;
1901 case lltok::LocalVarID: // %42
1902 ID.UIntVal = Lex.getUIntVal();
1903 ID.Kind = ValID::t_LocalID;
1904 break;
1905 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 ID.StrVal = Lex.getStrVal();
1907 ID.Kind = ValID::t_LocalName;
1908 break;
Dan Gohman83448032010-07-14 18:26:50 +00001909 case lltok::exclaim: // !42, !{...}, or !"foo"
1910 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001911 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 ID.Kind = ValID::t_APSInt;
1914 break;
1915 case lltok::APFloat:
1916 ID.APFloatVal = Lex.getAPFloatVal();
1917 ID.Kind = ValID::t_APFloat;
1918 break;
1919 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001920 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 ID.Kind = ValID::t_Constant;
1922 break;
1923 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001924 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 ID.Kind = ValID::t_Constant;
1926 break;
1927 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1928 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1929 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 case lltok::lbrace: {
1932 // ValID ::= '{' ConstVector '}'
1933 Lex.Lex();
1934 SmallVector<Constant*, 16> Elts;
1935 if (ParseGlobalValueVector(Elts) ||
1936 ParseToken(lltok::rbrace, "expected end of struct constant"))
1937 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938
Chris Lattner1afcace2011-07-09 17:41:24 +00001939 ID.ConstantStructElts = new Constant*[Elts.size()];
1940 ID.UIntVal = Elts.size();
1941 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1942 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 return false;
1944 }
1945 case lltok::less: {
1946 // ValID ::= '<' ConstVector '>' --> Vector.
1947 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1948 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001949 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001950
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 SmallVector<Constant*, 16> Elts;
1952 LocTy FirstEltLoc = Lex.getLoc();
1953 if (ParseGlobalValueVector(Elts) ||
1954 (isPackedStruct &&
1955 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1956 ParseToken(lltok::greater, "expected end of constant"))
1957 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001960 ID.ConstantStructElts = new Constant*[Elts.size()];
1961 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1962 ID.UIntVal = Elts.size();
1963 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 return false;
1965 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001966
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 if (Elts.empty())
1968 return Error(ID.Loc, "constant vector must not be empty");
1969
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001970 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00001971 !Elts[0]->getType()->isFloatingPointTy() &&
1972 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001973 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00001974 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001975
Chris Lattnerdf986172009-01-02 07:01:27 +00001976 // Verify that all the vector elements have the same type.
1977 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1978 if (Elts[i]->getType() != Elts[0]->getType())
1979 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001980 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001981 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001982
Chris Lattner2ca5c862011-02-15 00:14:00 +00001983 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00001984 ID.Kind = ValID::t_Constant;
1985 return false;
1986 }
1987 case lltok::lsquare: { // Array Constant
1988 Lex.Lex();
1989 SmallVector<Constant*, 16> Elts;
1990 LocTy FirstEltLoc = Lex.getLoc();
1991 if (ParseGlobalValueVector(Elts) ||
1992 ParseToken(lltok::rsquare, "expected end of array constant"))
1993 return true;
1994
1995 // Handle empty element.
1996 if (Elts.empty()) {
1997 // Use undef instead of an array because it's inconvenient to determine
1998 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001999 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002000 return false;
2001 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002002
Chris Lattnerdf986172009-01-02 07:01:27 +00002003 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002004 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002005 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002006
Owen Andersondebcb012009-07-29 22:17:13 +00002007 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008
Chris Lattnerdf986172009-01-02 07:01:27 +00002009 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002010 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002011 if (Elts[i]->getType() != Elts[0]->getType())
2012 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002013 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002014 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002015 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Jay Foad26701082011-06-22 09:24:39 +00002017 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002018 ID.Kind = ValID::t_Constant;
2019 return false;
2020 }
2021 case lltok::kw_c: // c "foo"
2022 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002023 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2025 ID.Kind = ValID::t_Constant;
2026 return false;
2027
2028 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002029 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2030 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002031 Lex.Lex();
2032 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002033 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002034 ParseStringConstant(ID.StrVal) ||
2035 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002036 ParseToken(lltok::StringConstant, "expected constraint string"))
2037 return true;
2038 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002039 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 ID.Kind = ValID::t_InlineAsm;
2041 return false;
2042 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Chris Lattner09d9ef42009-10-28 03:39:23 +00002044 case lltok::kw_blockaddress: {
2045 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2046 Lex.Lex();
2047
2048 ValID Fn, Label;
2049 LocTy FnLoc, LabelLoc;
2050
2051 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2052 ParseValID(Fn) ||
2053 ParseToken(lltok::comma, "expected comma in block address expression")||
2054 ParseValID(Label) ||
2055 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2056 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002057
Chris Lattner09d9ef42009-10-28 03:39:23 +00002058 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2059 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002060 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002061 return Error(Label.Loc, "expected basic block name in blockaddress");
2062
2063 // Make a global variable as a placeholder for this reference.
2064 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2065 false, GlobalValue::InternalLinkage,
2066 0, "");
2067 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2068 ID.ConstantVal = FwdRef;
2069 ID.Kind = ValID::t_Constant;
2070 return false;
2071 }
2072
Chris Lattnerdf986172009-01-02 07:01:27 +00002073 case lltok::kw_trunc:
2074 case lltok::kw_zext:
2075 case lltok::kw_sext:
2076 case lltok::kw_fptrunc:
2077 case lltok::kw_fpext:
2078 case lltok::kw_bitcast:
2079 case lltok::kw_uitofp:
2080 case lltok::kw_sitofp:
2081 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002083 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002085 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002086 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002087 Constant *SrcVal;
2088 Lex.Lex();
2089 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2090 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002091 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002092 ParseType(DestTy) ||
2093 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2094 return true;
2095 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2096 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002097 getTypeString(SrcVal->getType()) + "' to '" +
2098 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002100 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002101 ID.Kind = ValID::t_Constant;
2102 return false;
2103 }
2104 case lltok::kw_extractvalue: {
2105 Lex.Lex();
2106 Constant *Val;
2107 SmallVector<unsigned, 4> Indices;
2108 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2109 ParseGlobalTypeAndValue(Val) ||
2110 ParseIndexList(Indices) ||
2111 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2112 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002113
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002114 if (!Val->getType()->isAggregateType())
2115 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002116 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002117 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002118 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002119 ID.Kind = ValID::t_Constant;
2120 return false;
2121 }
2122 case lltok::kw_insertvalue: {
2123 Lex.Lex();
2124 Constant *Val0, *Val1;
2125 SmallVector<unsigned, 4> Indices;
2126 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2127 ParseGlobalTypeAndValue(Val0) ||
2128 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2129 ParseGlobalTypeAndValue(Val1) ||
2130 ParseIndexList(Indices) ||
2131 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2132 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002133 if (!Val0->getType()->isAggregateType())
2134 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002135 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002136 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002137 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002138 ID.Kind = ValID::t_Constant;
2139 return false;
2140 }
2141 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002142 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002143 unsigned PredVal, Opc = Lex.getUIntVal();
2144 Constant *Val0, *Val1;
2145 Lex.Lex();
2146 if (ParseCmpPredicate(PredVal, Opc) ||
2147 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2148 ParseGlobalTypeAndValue(Val0) ||
2149 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2150 ParseGlobalTypeAndValue(Val1) ||
2151 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2152 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002153
Chris Lattnerdf986172009-01-02 07:01:27 +00002154 if (Val0->getType() != Val1->getType())
2155 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002156
Chris Lattnerdf986172009-01-02 07:01:27 +00002157 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002158
Chris Lattnerdf986172009-01-02 07:01:27 +00002159 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002160 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002161 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002162 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002163 } else {
2164 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002165 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002166 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002167 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002168 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002169 }
2170 ID.Kind = ValID::t_Constant;
2171 return false;
2172 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002173
Chris Lattnerdf986172009-01-02 07:01:27 +00002174 // Binary Operators.
2175 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002176 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002178 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002180 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002181 case lltok::kw_udiv:
2182 case lltok::kw_sdiv:
2183 case lltok::kw_fdiv:
2184 case lltok::kw_urem:
2185 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002186 case lltok::kw_frem:
2187 case lltok::kw_shl:
2188 case lltok::kw_lshr:
2189 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002190 bool NUW = false;
2191 bool NSW = false;
2192 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002193 unsigned Opc = Lex.getUIntVal();
2194 Constant *Val0, *Val1;
2195 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002196 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002197 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2198 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002199 if (EatIfPresent(lltok::kw_nuw))
2200 NUW = true;
2201 if (EatIfPresent(lltok::kw_nsw)) {
2202 NSW = true;
2203 if (EatIfPresent(lltok::kw_nuw))
2204 NUW = true;
2205 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002206 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2207 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002208 if (EatIfPresent(lltok::kw_exact))
2209 Exact = true;
2210 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002211 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2212 ParseGlobalTypeAndValue(Val0) ||
2213 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2214 ParseGlobalTypeAndValue(Val1) ||
2215 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2216 return true;
2217 if (Val0->getType() != Val1->getType())
2218 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002219 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002220 if (NUW)
2221 return Error(ModifierLoc, "nuw only applies to integer operations");
2222 if (NSW)
2223 return Error(ModifierLoc, "nsw only applies to integer operations");
2224 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002225 // Check that the type is valid for the operator.
2226 switch (Opc) {
2227 case Instruction::Add:
2228 case Instruction::Sub:
2229 case Instruction::Mul:
2230 case Instruction::UDiv:
2231 case Instruction::SDiv:
2232 case Instruction::URem:
2233 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002234 case Instruction::Shl:
2235 case Instruction::AShr:
2236 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002237 if (!Val0->getType()->isIntOrIntVectorTy())
2238 return Error(ID.Loc, "constexpr requires integer operands");
2239 break;
2240 case Instruction::FAdd:
2241 case Instruction::FSub:
2242 case Instruction::FMul:
2243 case Instruction::FDiv:
2244 case Instruction::FRem:
2245 if (!Val0->getType()->isFPOrFPVectorTy())
2246 return Error(ID.Loc, "constexpr requires fp operands");
2247 break;
2248 default: llvm_unreachable("Unknown binary operator!");
2249 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002250 unsigned Flags = 0;
2251 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2252 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002253 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002254 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002255 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002256 ID.Kind = ValID::t_Constant;
2257 return false;
2258 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002259
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002261 case lltok::kw_and:
2262 case lltok::kw_or:
2263 case lltok::kw_xor: {
2264 unsigned Opc = Lex.getUIntVal();
2265 Constant *Val0, *Val1;
2266 Lex.Lex();
2267 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2268 ParseGlobalTypeAndValue(Val0) ||
2269 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2270 ParseGlobalTypeAndValue(Val1) ||
2271 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2272 return true;
2273 if (Val0->getType() != Val1->getType())
2274 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002275 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002276 return Error(ID.Loc,
2277 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002278 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002279 ID.Kind = ValID::t_Constant;
2280 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002281 }
2282
Chris Lattnerdf986172009-01-02 07:01:27 +00002283 case lltok::kw_getelementptr:
2284 case lltok::kw_shufflevector:
2285 case lltok::kw_insertelement:
2286 case lltok::kw_extractelement:
2287 case lltok::kw_select: {
2288 unsigned Opc = Lex.getUIntVal();
2289 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002290 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002291 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002292 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002293 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002294 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2295 ParseGlobalValueVector(Elts) ||
2296 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2297 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002298
Chris Lattnerdf986172009-01-02 07:01:27 +00002299 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002300 if (Elts.size() == 0 ||
2301 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002303
Jay Foaddab3d292011-07-21 14:31:17 +00002304 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002305 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002306 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002307 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2308 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002309 } else if (Opc == Instruction::Select) {
2310 if (Elts.size() != 3)
2311 return Error(ID.Loc, "expected three operands to select");
2312 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2313 Elts[2]))
2314 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002315 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002316 } else if (Opc == Instruction::ShuffleVector) {
2317 if (Elts.size() != 3)
2318 return Error(ID.Loc, "expected three operands to shufflevector");
2319 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2320 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002321 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002323 } else if (Opc == Instruction::ExtractElement) {
2324 if (Elts.size() != 2)
2325 return Error(ID.Loc, "expected two operands to extractelement");
2326 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2327 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002328 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002329 } else {
2330 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2331 if (Elts.size() != 3)
2332 return Error(ID.Loc, "expected three operands to insertelement");
2333 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2334 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002335 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002336 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338
Chris Lattnerdf986172009-01-02 07:01:27 +00002339 ID.Kind = ValID::t_Constant;
2340 return false;
2341 }
2342 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343
Chris Lattnerdf986172009-01-02 07:01:27 +00002344 Lex.Lex();
2345 return false;
2346}
2347
2348/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002349bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002350 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002351 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002352 Value *V = NULL;
2353 bool Parsed = ParseValID(ID) ||
2354 ConvertValIDToValue(Ty, ID, V, NULL);
2355 if (V && !(C = dyn_cast<Constant>(V)))
2356 return Error(ID.Loc, "global values must be constants");
2357 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002358}
2359
Victor Hernandez92f238d2010-01-11 22:31:58 +00002360bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002361 Type *Ty = 0;
2362 return ParseType(Ty) ||
2363 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002364}
2365
2366/// ParseGlobalValueVector
2367/// ::= /*empty*/
2368/// ::= TypeAndValue (',' TypeAndValue)*
2369bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2370 // Empty list.
2371 if (Lex.getKind() == lltok::rbrace ||
2372 Lex.getKind() == lltok::rsquare ||
2373 Lex.getKind() == lltok::greater ||
2374 Lex.getKind() == lltok::rparen)
2375 return false;
2376
2377 Constant *C;
2378 if (ParseGlobalTypeAndValue(C)) return true;
2379 Elts.push_back(C);
2380
2381 while (EatIfPresent(lltok::comma)) {
2382 if (ParseGlobalTypeAndValue(C)) return true;
2383 Elts.push_back(C);
2384 }
2385
2386 return false;
2387}
2388
Dan Gohman309b3af2010-08-24 02:24:03 +00002389bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2390 assert(Lex.getKind() == lltok::lbrace);
2391 Lex.Lex();
2392
2393 SmallVector<Value*, 16> Elts;
2394 if (ParseMDNodeVector(Elts, PFS) ||
2395 ParseToken(lltok::rbrace, "expected end of metadata node"))
2396 return true;
2397
Jay Foadec9186b2011-04-21 19:59:31 +00002398 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002399 ID.Kind = ValID::t_MDNode;
2400 return false;
2401}
2402
Dan Gohman83448032010-07-14 18:26:50 +00002403/// ParseMetadataValue
2404/// ::= !42
2405/// ::= !{...}
2406/// ::= !"string"
2407bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2408 assert(Lex.getKind() == lltok::exclaim);
2409 Lex.Lex();
2410
2411 // MDNode:
2412 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002413 if (Lex.getKind() == lltok::lbrace)
2414 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002415
2416 // Standalone metadata reference
2417 // !42
2418 if (Lex.getKind() == lltok::APSInt) {
2419 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2420 ID.Kind = ValID::t_MDNode;
2421 return false;
2422 }
2423
2424 // MDString:
2425 // ::= '!' STRINGCONSTANT
2426 if (ParseMDString(ID.MDStringVal)) return true;
2427 ID.Kind = ValID::t_MDString;
2428 return false;
2429}
2430
Victor Hernandez92f238d2010-01-11 22:31:58 +00002431
2432//===----------------------------------------------------------------------===//
2433// Function Parsing.
2434//===----------------------------------------------------------------------===//
2435
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002436bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002437 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002438 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002440
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002442 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002443 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2444 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2445 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002446 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002447 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2448 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2449 return (V == 0);
2450 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002451 PointerType *PTy = dyn_cast<PointerType>(Ty);
2452 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002453 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2454 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2455 return Error(ID.Loc, "invalid type for inline asm constraint string");
2456 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2457 return false;
2458 }
2459 case ValID::t_MDNode:
2460 if (!Ty->isMetadataTy())
2461 return Error(ID.Loc, "metadata value must have metadata type");
2462 V = ID.MDNodeVal;
2463 return false;
2464 case ValID::t_MDString:
2465 if (!Ty->isMetadataTy())
2466 return Error(ID.Loc, "metadata value must have metadata type");
2467 V = ID.MDStringVal;
2468 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002469 case ValID::t_GlobalName:
2470 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2471 return V == 0;
2472 case ValID::t_GlobalID:
2473 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2474 return V == 0;
2475 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002476 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002477 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002478 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002479 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002480 return false;
2481 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002482 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002483 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2484 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002485
Dan Gohmance163392011-12-17 00:04:22 +00002486 // The lexer has no type info, so builds all half, float, and double FP
2487 // constants as double. Fix this here. Long double does not need this.
2488 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002490 if (Ty->isHalfTy())
2491 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2492 &Ignored);
2493 else if (Ty->isFloatTy())
2494 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2495 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002496 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002497 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002498
Chris Lattner959873d2009-01-05 18:24:23 +00002499 if (V->getType() != Ty)
2500 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002501 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002502
Chris Lattnerdf986172009-01-02 07:01:27 +00002503 return false;
2504 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002505 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002506 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002507 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002508 return false;
2509 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002510 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002511 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002512 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002513 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002514 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002515 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002516 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002517 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002518 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002519 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002520 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002521 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002522 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002523 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002524 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002525 return false;
2526 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002527 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002528 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002529
Chris Lattnerdf986172009-01-02 07:01:27 +00002530 V = ID.ConstantVal;
2531 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002532 case ValID::t_ConstantStruct:
2533 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002534 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002535 if (ST->getNumElements() != ID.UIntVal)
2536 return Error(ID.Loc,
2537 "initializer with struct type has wrong # elements");
2538 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2539 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2540
2541 // Verify that the elements are compatible with the structtype.
2542 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2543 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2544 return Error(ID.Loc, "element " + Twine(i) +
2545 " of struct initializer doesn't match struct element type");
2546
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002547 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2548 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002549 } else
2550 return Error(ID.Loc, "constant expression type mismatch");
2551 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002552 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002553 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002554}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002555
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002556bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002557 V = 0;
2558 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002559 return ParseValID(ID, PFS) ||
2560 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002561}
2562
Chris Lattner1afcace2011-07-09 17:41:24 +00002563bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2564 Type *Ty = 0;
2565 return ParseType(Ty) ||
2566 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002567}
2568
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002569bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2570 PerFunctionState &PFS) {
2571 Value *V;
2572 Loc = Lex.getLoc();
2573 if (ParseTypeAndValue(V, PFS)) return true;
2574 if (!isa<BasicBlock>(V))
2575 return Error(Loc, "expected a basic block");
2576 BB = cast<BasicBlock>(V);
2577 return false;
2578}
2579
2580
Chris Lattnerdf986172009-01-02 07:01:27 +00002581/// FunctionHeader
2582/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002583/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002584/// OptionalAlign OptGC
2585bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2586 // Parse the linkage.
2587 LocTy LinkageLoc = Lex.getLoc();
2588 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002590 unsigned Visibility;
2591 Attributes RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002592 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002593 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 LocTy RetTypeLoc = Lex.getLoc();
2595 if (ParseOptionalLinkage(Linkage) ||
2596 ParseOptionalVisibility(Visibility) ||
2597 ParseOptionalCallingConv(CC) ||
2598 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002599 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002600 return true;
2601
2602 // Verify that the linkage is ok.
2603 switch ((GlobalValue::LinkageTypes)Linkage) {
2604 case GlobalValue::ExternalLinkage:
2605 break; // always ok.
2606 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002607 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002608 if (isDefine)
2609 return Error(LinkageLoc, "invalid linkage for function definition");
2610 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002611 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002612 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002613 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002614 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002616 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002617 case GlobalValue::LinkOnceAnyLinkage:
2618 case GlobalValue::LinkOnceODRLinkage:
2619 case GlobalValue::WeakAnyLinkage:
2620 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002621 case GlobalValue::DLLExportLinkage:
2622 if (!isDefine)
2623 return Error(LinkageLoc, "invalid linkage for function declaration");
2624 break;
2625 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002626 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 return Error(LinkageLoc, "invalid function linkage type");
2628 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattner1afcace2011-07-09 17:41:24 +00002630 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002631 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattnerdf986172009-01-02 07:01:27 +00002633 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002634
2635 std::string FunctionName;
2636 if (Lex.getKind() == lltok::GlobalVar) {
2637 FunctionName = Lex.getStrVal();
2638 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2639 unsigned NameID = Lex.getUIntVal();
2640
2641 if (NameID != NumberedVals.size())
2642 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002643 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002644 } else {
2645 return TokError("expected function name");
2646 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002647
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002648 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002649
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002650 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002652
Chris Lattner1afcace2011-07-09 17:41:24 +00002653 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002654 bool isVarArg;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002655 Attributes FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002656 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002657 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002658 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002659 bool UnnamedAddr;
2660 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002661
Chris Lattner1afcace2011-07-09 17:41:24 +00002662 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002663 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2664 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002665 ParseOptionalAttrs(FuncAttrs, 2) ||
2666 (EatIfPresent(lltok::kw_section) &&
2667 ParseStringConstant(Section)) ||
2668 ParseOptionalAlignment(Alignment) ||
2669 (EatIfPresent(lltok::kw_gc) &&
2670 ParseStringConstant(GC)))
2671 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002672
2673 // If the alignment was parsed as an attribute, move to the alignment field.
2674 if (FuncAttrs & Attribute::Alignment) {
2675 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2676 FuncAttrs &= ~Attribute::Alignment;
2677 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002678
Chris Lattnerdf986172009-01-02 07:01:27 +00002679 // Okay, if we got here, the function is syntactically valid. Convert types
2680 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002681 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002682 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683
Chris Lattnerdf986172009-01-02 07:01:27 +00002684 if (RetAttrs != Attribute::None)
2685 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002686
Chris Lattnerdf986172009-01-02 07:01:27 +00002687 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002688 ParamTypeList.push_back(ArgList[i].Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002689 if (ArgList[i].Attrs != Attribute::None)
2690 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2691 }
2692
2693 if (FuncAttrs != Attribute::None)
2694 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2695
2696 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Benjamin Kramerf0127052010-01-05 13:12:22 +00002698 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2700
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002701 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002702 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002703 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002704
2705 Fn = 0;
2706 if (!FunctionName.empty()) {
2707 // If this was a definition of a forward reference, remove the definition
2708 // from the forward reference table and fill in the forward ref.
2709 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2710 ForwardRefVals.find(FunctionName);
2711 if (FRVI != ForwardRefVals.end()) {
2712 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002713 if (Fn->getType() != PFT)
2714 return Error(FRVI->second.second, "invalid forward reference to "
2715 "function '" + FunctionName + "' with wrong type!");
2716
Chris Lattnerdf986172009-01-02 07:01:27 +00002717 ForwardRefVals.erase(FRVI);
2718 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002719 // Reject redefinitions.
2720 return Error(NameLoc, "invalid redefinition of function '" +
2721 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002722 } else if (M->getNamedValue(FunctionName)) {
2723 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Dan Gohman41905542009-08-29 23:37:49 +00002726 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002727 // If this is a definition of a forward referenced function, make sure the
2728 // types agree.
2729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2730 = ForwardRefValIDs.find(NumberedVals.size());
2731 if (I != ForwardRefValIDs.end()) {
2732 Fn = cast<Function>(I->second.first);
2733 if (Fn->getType() != PFT)
2734 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002735 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002736 ForwardRefValIDs.erase(I);
2737 }
2738 }
2739
2740 if (Fn == 0)
2741 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2742 else // Move the forward-reference to the correct spot in the module.
2743 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2744
2745 if (FunctionName.empty())
2746 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002747
Chris Lattnerdf986172009-01-02 07:01:27 +00002748 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2749 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2750 Fn->setCallingConv(CC);
2751 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002752 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002753 Fn->setAlignment(Alignment);
2754 Fn->setSection(Section);
2755 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002756
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 // Add all of the arguments we parsed to the function.
2758 Function::arg_iterator ArgIt = Fn->arg_begin();
2759 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2760 // If the argument has a name, insert it into the argument symbol table.
2761 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002762
Chris Lattnerdf986172009-01-02 07:01:27 +00002763 // Set the name, if it conflicted, it will be auto-renamed.
2764 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Benjamin Krameraf812352010-10-16 11:28:23 +00002766 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002767 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2768 ArgList[i].Name + "'");
2769 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002770
Chris Lattnerdf986172009-01-02 07:01:27 +00002771 return false;
2772}
2773
2774
2775/// ParseFunctionBody
2776/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002777///
2778bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002779 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002780 return TokError("expected '{' in function body");
2781 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Chris Lattner09d9ef42009-10-28 03:39:23 +00002783 int FunctionNumber = -1;
2784 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2785
2786 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002787
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002788 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002789 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002790 return TokError("function body requires at least one basic block");
2791
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002792 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002793 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Chris Lattnerdf986172009-01-02 07:01:27 +00002795 // Eat the }.
2796 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002799 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002800}
2801
2802/// ParseBasicBlock
2803/// ::= LabelStr? Instruction*
2804bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2805 // If this basic block starts out with a name, remember it.
2806 std::string Name;
2807 LocTy NameLoc = Lex.getLoc();
2808 if (Lex.getKind() == lltok::LabelStr) {
2809 Name = Lex.getStrVal();
2810 Lex.Lex();
2811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002812
Chris Lattnerdf986172009-01-02 07:01:27 +00002813 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2814 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Chris Lattnerdf986172009-01-02 07:01:27 +00002816 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002817
Chris Lattnerdf986172009-01-02 07:01:27 +00002818 // Parse the instructions in this block until we get a terminator.
2819 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002820 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 do {
2822 // This instruction may have three possibilities for a name: a) none
2823 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2824 LocTy NameLoc = Lex.getLoc();
2825 int NameID = -1;
2826 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 if (Lex.getKind() == lltok::LocalVarID) {
2829 NameID = Lex.getUIntVal();
2830 Lex.Lex();
2831 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2832 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002833 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 NameStr = Lex.getStrVal();
2835 Lex.Lex();
2836 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2837 return true;
2838 }
Devang Patelf633a062009-09-17 23:04:48 +00002839
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002840 switch (ParseInstruction(Inst, BB, PFS)) {
2841 default: assert(0 && "Unknown ParseInstruction result!");
2842 case InstError: return true;
2843 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002844 BB->getInstList().push_back(Inst);
2845
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002846 // With a normal result, we check to see if the instruction is followed by
2847 // a comma and metadata.
2848 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002849 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002850 return true;
2851 break;
2852 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002853 BB->getInstList().push_back(Inst);
2854
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002855 // If the instruction parser ate an extra comma at the end of it, it
2856 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002857 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002858 return true;
2859 break;
2860 }
Devang Patelf633a062009-09-17 23:04:48 +00002861
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 // Set the name on the instruction.
2863 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2864 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002865
Chris Lattnerdf986172009-01-02 07:01:27 +00002866 return false;
2867}
2868
2869//===----------------------------------------------------------------------===//
2870// Instruction Parsing.
2871//===----------------------------------------------------------------------===//
2872
2873/// ParseInstruction - Parse one of the many different instructions.
2874///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002875int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2876 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002877 lltok::Kind Token = Lex.getKind();
2878 if (Token == lltok::Eof)
2879 return TokError("found end of file when expecting more instructions");
2880 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002881 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002882 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002883
Chris Lattnerdf986172009-01-02 07:01:27 +00002884 switch (Token) {
2885 default: return Error(Loc, "expected instruction opcode");
2886 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002887 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2888 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2890 case lltok::kw_br: return ParseBr(Inst, PFS);
2891 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002892 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002893 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002894 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002895 // Binary Operators.
2896 case lltok::kw_add:
2897 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002898 case lltok::kw_mul:
2899 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002900 bool NUW = EatIfPresent(lltok::kw_nuw);
2901 bool NSW = EatIfPresent(lltok::kw_nsw);
2902 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2903
2904 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2905
2906 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2907 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2908 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002909 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002910 case lltok::kw_fadd:
2911 case lltok::kw_fsub:
2912 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2913
Chris Lattner35bda892011-02-06 21:44:57 +00002914 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002915 case lltok::kw_udiv:
2916 case lltok::kw_lshr:
2917 case lltok::kw_ashr: {
2918 bool Exact = EatIfPresent(lltok::kw_exact);
2919
2920 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2921 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2922 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002923 }
2924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002926 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002927 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002928 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 case lltok::kw_and:
2930 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002931 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002932 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002933 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002934 // Casts.
2935 case lltok::kw_trunc:
2936 case lltok::kw_zext:
2937 case lltok::kw_sext:
2938 case lltok::kw_fptrunc:
2939 case lltok::kw_fpext:
2940 case lltok::kw_bitcast:
2941 case lltok::kw_uitofp:
2942 case lltok::kw_sitofp:
2943 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002944 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002945 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002946 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002947 // Other.
2948 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002949 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002950 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2951 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2952 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2953 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002954 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002955 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2956 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2957 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002958 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00002959 case lltok::kw_load: return ParseLoad(Inst, PFS);
2960 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00002961 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2962 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00002963 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002964 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2965 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2966 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2967 }
2968}
2969
2970/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2971bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002972 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002973 switch (Lex.getKind()) {
2974 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2975 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2976 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2977 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2978 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2979 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2980 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2981 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2982 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2983 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2984 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2985 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2986 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2987 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2988 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2989 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2990 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2991 }
2992 } else {
2993 switch (Lex.getKind()) {
2994 default: TokError("expected icmp predicate (e.g. 'eq')");
2995 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2996 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2997 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2998 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2999 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3000 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3001 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3002 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3003 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3004 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3005 }
3006 }
3007 Lex.Lex();
3008 return false;
3009}
3010
3011//===----------------------------------------------------------------------===//
3012// Terminator Instructions.
3013//===----------------------------------------------------------------------===//
3014
3015/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003016/// ::= 'ret' void (',' !dbg, !1)*
3017/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003018bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003019 PerFunctionState &PFS) {
3020 SMLoc TypeLoc = Lex.getLoc();
3021 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003022 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003023
Chris Lattner1afcace2011-07-09 17:41:24 +00003024 Type *ResType = PFS.getFunction().getReturnType();
3025
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003026 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003027 if (!ResType->isVoidTy())
3028 return Error(TypeLoc, "value doesn't match function result type '" +
3029 getTypeString(ResType) + "'");
3030
Owen Anderson1d0be152009-08-13 21:58:54 +00003031 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003032 return false;
3033 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003034
Chris Lattnerdf986172009-01-02 07:01:27 +00003035 Value *RV;
3036 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003037
Chris Lattner1afcace2011-07-09 17:41:24 +00003038 if (ResType != RV->getType())
3039 return Error(TypeLoc, "value doesn't match function result type '" +
3040 getTypeString(ResType) + "'");
3041
Owen Anderson1d0be152009-08-13 21:58:54 +00003042 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003043 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003044}
3045
3046
3047/// ParseBr
3048/// ::= 'br' TypeAndValue
3049/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3050bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3051 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003052 Value *Op0;
3053 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003054 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003055
Chris Lattnerdf986172009-01-02 07:01:27 +00003056 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3057 Inst = BranchInst::Create(BB);
3058 return false;
3059 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003060
Owen Anderson1d0be152009-08-13 21:58:54 +00003061 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003062 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003063
Chris Lattnerdf986172009-01-02 07:01:27 +00003064 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003065 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003066 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003067 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003068 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003069
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003070 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 return false;
3072}
3073
3074/// ParseSwitch
3075/// Instruction
3076/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3077/// JumpTable
3078/// ::= (TypeAndValue ',' TypeAndValue)*
3079bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3080 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003081 Value *Cond;
3082 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003083 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3084 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003085 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003086 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3087 return true;
3088
Duncan Sands1df98592010-02-16 11:11:14 +00003089 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003090 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003091
Chris Lattnerdf986172009-01-02 07:01:27 +00003092 // Parse the jump table pairs.
3093 SmallPtrSet<Value*, 32> SeenCases;
3094 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3095 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003096 Value *Constant;
3097 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003098
Chris Lattnerdf986172009-01-02 07:01:27 +00003099 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3100 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003101 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003102 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 if (!SeenCases.insert(Constant))
3105 return Error(CondLoc, "duplicate case value in switch");
3106 if (!isa<ConstantInt>(Constant))
3107 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003108
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003109 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003110 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003111
Chris Lattnerdf986172009-01-02 07:01:27 +00003112 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003113
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003114 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3116 SI->addCase(Table[i].first, Table[i].second);
3117 Inst = SI;
3118 return false;
3119}
3120
Chris Lattnerab21db72009-10-28 00:19:10 +00003121/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003122/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003123/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3124bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003125 LocTy AddrLoc;
3126 Value *Address;
3127 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003128 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3129 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003130 return true;
3131
Duncan Sands1df98592010-02-16 11:11:14 +00003132 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003133 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003134
3135 // Parse the destination list.
3136 SmallVector<BasicBlock*, 16> DestList;
3137
3138 if (Lex.getKind() != lltok::rsquare) {
3139 BasicBlock *DestBB;
3140 if (ParseTypeAndBasicBlock(DestBB, PFS))
3141 return true;
3142 DestList.push_back(DestBB);
3143
3144 while (EatIfPresent(lltok::comma)) {
3145 if (ParseTypeAndBasicBlock(DestBB, PFS))
3146 return true;
3147 DestList.push_back(DestBB);
3148 }
3149 }
3150
3151 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3152 return true;
3153
Chris Lattnerab21db72009-10-28 00:19:10 +00003154 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003155 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3156 IBI->addDestination(DestList[i]);
3157 Inst = IBI;
3158 return false;
3159}
3160
3161
Chris Lattnerdf986172009-01-02 07:01:27 +00003162/// ParseInvoke
3163/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3164/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3165bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3166 LocTy CallLoc = Lex.getLoc();
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003167 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003168 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003169 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003170 LocTy RetTypeLoc;
3171 ValID CalleeID;
3172 SmallVector<ParamInfo, 16> ArgList;
3173
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003174 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 if (ParseOptionalCallingConv(CC) ||
3176 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003177 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003178 ParseValID(CalleeID) ||
3179 ParseParameterList(ArgList, PFS) ||
3180 ParseOptionalAttrs(FnAttrs, 2) ||
3181 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003182 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003184 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003185 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003186
Chris Lattnerdf986172009-01-02 07:01:27 +00003187 // If RetType is a non-function pointer type, then this is the short syntax
3188 // for the call, which means that RetType is just the return type. Infer the
3189 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003190 PointerType *PFTy = 0;
3191 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003192 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3193 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3194 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003195 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003196 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3197 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003198
Chris Lattnerdf986172009-01-02 07:01:27 +00003199 if (!FunctionType::isValidReturnType(RetType))
3200 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003201
Owen Andersondebcb012009-07-29 22:17:13 +00003202 Ty = FunctionType::get(RetType, ParamTypes, false);
3203 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003205
Chris Lattnerdf986172009-01-02 07:01:27 +00003206 // Look up the callee.
3207 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003208 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 // Set up the Attributes for the function.
3211 SmallVector<AttributeWithIndex, 8> Attrs;
3212 if (RetAttrs != Attribute::None)
3213 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003214
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003216
Chris Lattnerdf986172009-01-02 07:01:27 +00003217 // Loop through FunctionType's arguments and ensure they are specified
3218 // correctly. Also, gather any parameter attributes.
3219 FunctionType::param_iterator I = Ty->param_begin();
3220 FunctionType::param_iterator E = Ty->param_end();
3221 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003222 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 if (I != E) {
3224 ExpectedTy = *I++;
3225 } else if (!Ty->isVarArg()) {
3226 return Error(ArgList[i].Loc, "too many arguments specified");
3227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003228
Chris Lattnerdf986172009-01-02 07:01:27 +00003229 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3230 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003231 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 Args.push_back(ArgList[i].V);
3233 if (ArgList[i].Attrs != Attribute::None)
3234 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003236
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 if (I != E)
3238 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003239
Chris Lattnerdf986172009-01-02 07:01:27 +00003240 if (FnAttrs != Attribute::None)
3241 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003242
Chris Lattnerdf986172009-01-02 07:01:27 +00003243 // Finish off the Attributes and check them
3244 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003245
Jay Foada3efbb12011-07-15 08:37:34 +00003246 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003247 II->setCallingConv(CC);
3248 II->setAttributes(PAL);
3249 Inst = II;
3250 return false;
3251}
3252
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003253/// ParseResume
3254/// ::= 'resume' TypeAndValue
3255bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3256 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003257 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3258 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003259
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003260 ResumeInst *RI = ResumeInst::Create(Exn);
3261 Inst = RI;
3262 return false;
3263}
Chris Lattnerdf986172009-01-02 07:01:27 +00003264
3265//===----------------------------------------------------------------------===//
3266// Binary Operators.
3267//===----------------------------------------------------------------------===//
3268
3269/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003270/// ::= ArithmeticOps TypeAndValue ',' Value
3271///
3272/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3273/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003274bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003275 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003276 LocTy Loc; Value *LHS, *RHS;
3277 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3278 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3279 ParseValue(LHS->getType(), RHS, PFS))
3280 return true;
3281
Chris Lattnere914b592009-01-05 08:24:46 +00003282 bool Valid;
3283 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003284 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003285 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003286 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3287 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003288 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003289 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3290 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003291 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003292
Chris Lattnere914b592009-01-05 08:24:46 +00003293 if (!Valid)
3294 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003295
Chris Lattnerdf986172009-01-02 07:01:27 +00003296 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3297 return false;
3298}
3299
3300/// ParseLogical
3301/// ::= ArithmeticOps TypeAndValue ',' Value {
3302bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3303 unsigned Opc) {
3304 LocTy Loc; Value *LHS, *RHS;
3305 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3306 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3307 ParseValue(LHS->getType(), RHS, PFS))
3308 return true;
3309
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003310 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003311 return Error(Loc,"instruction requires integer or integer vector operands");
3312
3313 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3314 return false;
3315}
3316
3317
3318/// ParseCompare
3319/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3320/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003321bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3322 unsigned Opc) {
3323 // Parse the integer/fp comparison predicate.
3324 LocTy Loc;
3325 unsigned Pred;
3326 Value *LHS, *RHS;
3327 if (ParseCmpPredicate(Pred, Opc) ||
3328 ParseTypeAndValue(LHS, Loc, PFS) ||
3329 ParseToken(lltok::comma, "expected ',' after compare value") ||
3330 ParseValue(LHS->getType(), RHS, PFS))
3331 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnerdf986172009-01-02 07:01:27 +00003333 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003334 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003335 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003336 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003337 } else {
3338 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003339 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003340 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003342 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003343 }
3344 return false;
3345}
3346
3347//===----------------------------------------------------------------------===//
3348// Other Instructions.
3349//===----------------------------------------------------------------------===//
3350
3351
3352/// ParseCast
3353/// ::= CastOpc TypeAndValue 'to' Type
3354bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3355 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003356 LocTy Loc;
3357 Value *Op;
3358 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003359 if (ParseTypeAndValue(Op, Loc, PFS) ||
3360 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3361 ParseType(DestTy))
3362 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003363
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003364 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3365 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003366 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003367 getTypeString(Op->getType()) + "' to '" +
3368 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003369 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003370 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3371 return false;
3372}
3373
3374/// ParseSelect
3375/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3376bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3377 LocTy Loc;
3378 Value *Op0, *Op1, *Op2;
3379 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3380 ParseToken(lltok::comma, "expected ',' after select condition") ||
3381 ParseTypeAndValue(Op1, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after select value") ||
3383 ParseTypeAndValue(Op2, PFS))
3384 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003385
Chris Lattnerdf986172009-01-02 07:01:27 +00003386 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3387 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003388
Chris Lattnerdf986172009-01-02 07:01:27 +00003389 Inst = SelectInst::Create(Op0, Op1, Op2);
3390 return false;
3391}
3392
Chris Lattner0088a5c2009-01-05 08:18:44 +00003393/// ParseVA_Arg
3394/// ::= 'va_arg' TypeAndValue ',' Type
3395bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003396 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003397 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003398 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003399 if (ParseTypeAndValue(Op, PFS) ||
3400 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003401 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003403
Chris Lattner0088a5c2009-01-05 08:18:44 +00003404 if (!EltTy->isFirstClassType())
3405 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003406
3407 Inst = new VAArgInst(Op, EltTy);
3408 return false;
3409}
3410
3411/// ParseExtractElement
3412/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3413bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3414 LocTy Loc;
3415 Value *Op0, *Op1;
3416 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3417 ParseToken(lltok::comma, "expected ',' after extract value") ||
3418 ParseTypeAndValue(Op1, PFS))
3419 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003420
Chris Lattnerdf986172009-01-02 07:01:27 +00003421 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3422 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003423
Eric Christophera3500da2009-07-25 02:28:41 +00003424 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003425 return false;
3426}
3427
3428/// ParseInsertElement
3429/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3430bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3431 LocTy Loc;
3432 Value *Op0, *Op1, *Op2;
3433 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3434 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3435 ParseTypeAndValue(Op1, PFS) ||
3436 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3437 ParseTypeAndValue(Op2, PFS))
3438 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003439
Chris Lattnerdf986172009-01-02 07:01:27 +00003440 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003441 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003442
Chris Lattnerdf986172009-01-02 07:01:27 +00003443 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3444 return false;
3445}
3446
3447/// ParseShuffleVector
3448/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3449bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3450 LocTy Loc;
3451 Value *Op0, *Op1, *Op2;
3452 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3453 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3454 ParseTypeAndValue(Op1, PFS) ||
3455 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3456 ParseTypeAndValue(Op2, PFS))
3457 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003458
Chris Lattnerdf986172009-01-02 07:01:27 +00003459 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3460 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003461
Chris Lattnerdf986172009-01-02 07:01:27 +00003462 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3463 return false;
3464}
3465
3466/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003467/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003468int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003469 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003470 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003471
Chris Lattner1afcace2011-07-09 17:41:24 +00003472 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003473 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3474 ParseValue(Ty, Op0, PFS) ||
3475 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003476 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003477 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003479
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003480 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003481 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3482 while (1) {
3483 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003484
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003485 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003486 break;
3487
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003488 if (Lex.getKind() == lltok::MetadataVar) {
3489 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003490 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003491 }
Devang Patela43d46f2009-10-16 18:45:49 +00003492
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003493 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003494 ParseValue(Ty, Op0, PFS) ||
3495 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003496 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003497 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3498 return true;
3499 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003500
Chris Lattnerdf986172009-01-02 07:01:27 +00003501 if (!Ty->isFirstClassType())
3502 return Error(TypeLoc, "phi node must have first class type");
3503
Jay Foad3ecfc862011-03-30 11:28:46 +00003504 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003505 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3506 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3507 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003508 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003509}
3510
Bill Wendlinge6e88262011-08-12 20:24:12 +00003511/// ParseLandingPad
3512/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3513/// Clause
3514/// ::= 'catch' TypeAndValue
3515/// ::= 'filter'
3516/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3517bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3518 Type *Ty = 0; LocTy TyLoc;
3519 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003520
3521 if (ParseType(Ty, TyLoc) ||
3522 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3523 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3524 return true;
3525
3526 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3527 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3528
3529 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3530 LandingPadInst::ClauseType CT;
3531 if (EatIfPresent(lltok::kw_catch))
3532 CT = LandingPadInst::Catch;
3533 else if (EatIfPresent(lltok::kw_filter))
3534 CT = LandingPadInst::Filter;
3535 else
3536 return TokError("expected 'catch' or 'filter' clause type");
3537
3538 Value *V; LocTy VLoc;
3539 if (ParseTypeAndValue(V, VLoc, PFS)) {
3540 delete LP;
3541 return true;
3542 }
3543
Bill Wendling746c8822011-08-12 20:52:25 +00003544 // A 'catch' type expects a non-array constant. A filter clause expects an
3545 // array constant.
3546 if (CT == LandingPadInst::Catch) {
3547 if (isa<ArrayType>(V->getType()))
3548 Error(VLoc, "'catch' clause has an invalid type");
3549 } else {
3550 if (!isa<ArrayType>(V->getType()))
3551 Error(VLoc, "'filter' clause has an invalid type");
3552 }
3553
Bill Wendlinge6e88262011-08-12 20:24:12 +00003554 LP->addClause(V);
3555 }
3556
3557 Inst = LP;
3558 return false;
3559}
3560
Chris Lattnerdf986172009-01-02 07:01:27 +00003561/// ParseCall
3562/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3563/// ParameterList OptionalAttrs
3564bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3565 bool isTail) {
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003566 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003567 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003568 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003569 LocTy RetTypeLoc;
3570 ValID CalleeID;
3571 SmallVector<ParamInfo, 16> ArgList;
3572 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003573
Chris Lattnerdf986172009-01-02 07:01:27 +00003574 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3575 ParseOptionalCallingConv(CC) ||
3576 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003577 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003578 ParseValID(CalleeID) ||
3579 ParseParameterList(ArgList, PFS) ||
3580 ParseOptionalAttrs(FnAttrs, 2))
3581 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003582
Chris Lattnerdf986172009-01-02 07:01:27 +00003583 // If RetType is a non-function pointer type, then this is the short syntax
3584 // for the call, which means that RetType is just the return type. Infer the
3585 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003586 PointerType *PFTy = 0;
3587 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003588 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3589 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3590 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003591 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003592 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3593 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003594
Chris Lattnerdf986172009-01-02 07:01:27 +00003595 if (!FunctionType::isValidReturnType(RetType))
3596 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003597
Owen Andersondebcb012009-07-29 22:17:13 +00003598 Ty = FunctionType::get(RetType, ParamTypes, false);
3599 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003600 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003601
Chris Lattnerdf986172009-01-02 07:01:27 +00003602 // Look up the callee.
3603 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003604 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003605
Chris Lattnerdf986172009-01-02 07:01:27 +00003606 // Set up the Attributes for the function.
3607 SmallVector<AttributeWithIndex, 8> Attrs;
3608 if (RetAttrs != Attribute::None)
3609 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003610
Chris Lattnerdf986172009-01-02 07:01:27 +00003611 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003612
Chris Lattnerdf986172009-01-02 07:01:27 +00003613 // Loop through FunctionType's arguments and ensure they are specified
3614 // correctly. Also, gather any parameter attributes.
3615 FunctionType::param_iterator I = Ty->param_begin();
3616 FunctionType::param_iterator E = Ty->param_end();
3617 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003618 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 if (I != E) {
3620 ExpectedTy = *I++;
3621 } else if (!Ty->isVarArg()) {
3622 return Error(ArgList[i].Loc, "too many arguments specified");
3623 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003624
Chris Lattnerdf986172009-01-02 07:01:27 +00003625 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3626 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003627 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003628 Args.push_back(ArgList[i].V);
3629 if (ArgList[i].Attrs != Attribute::None)
3630 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003632
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 if (I != E)
3634 return Error(CallLoc, "not enough parameters specified for call");
3635
3636 if (FnAttrs != Attribute::None)
3637 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3638
3639 // Finish off the Attributes and check them
3640 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003641
Jay Foada3efbb12011-07-15 08:37:34 +00003642 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003643 CI->setTailCall(isTail);
3644 CI->setCallingConv(CC);
3645 CI->setAttributes(PAL);
3646 Inst = CI;
3647 return false;
3648}
3649
3650//===----------------------------------------------------------------------===//
3651// Memory Instructions.
3652//===----------------------------------------------------------------------===//
3653
3654/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003655/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003656int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003657 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003658 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003660 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003661 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003662
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003663 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003664 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003665 if (Lex.getKind() == lltok::kw_align) {
3666 if (ParseOptionalAlignment(Alignment)) return true;
3667 } else if (Lex.getKind() == lltok::MetadataVar) {
3668 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003669 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003670 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3671 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3672 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003673 }
3674 }
3675
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003676 if (Size && !Size->getType()->isIntegerTy())
3677 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003678
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003679 Inst = new AllocaInst(Ty, Size, Alignment);
3680 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003681}
3682
3683/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003684/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3685/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3686/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003687int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003688 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003689 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003690 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003691 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003692 AtomicOrdering Ordering = NotAtomic;
3693 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003694
3695 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003696 isAtomic = true;
3697 Lex.Lex();
3698 }
3699
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003700 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003701 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003702 isVolatile = true;
3703 Lex.Lex();
3704 }
3705
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003706 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003707 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003708 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3709 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003710
Duncan Sands1df98592010-02-16 11:11:14 +00003711 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003712 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3713 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003714 if (isAtomic && !Alignment)
3715 return Error(Loc, "atomic load must have explicit non-zero alignment");
3716 if (Ordering == Release || Ordering == AcquireRelease)
3717 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003718
Eli Friedman21006d42011-08-09 23:02:53 +00003719 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003720 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003721}
3722
3723/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003724
3725/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3726/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003727/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003728int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003729 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003730 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003731 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003732 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003733 AtomicOrdering Ordering = NotAtomic;
3734 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003735
3736 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003737 isAtomic = true;
3738 Lex.Lex();
3739 }
3740
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003741 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003742 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003743 isVolatile = true;
3744 Lex.Lex();
3745 }
3746
Chris Lattnerdf986172009-01-02 07:01:27 +00003747 if (ParseTypeAndValue(Val, Loc, PFS) ||
3748 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003749 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003750 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003751 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003752 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003753
Duncan Sands1df98592010-02-16 11:11:14 +00003754 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003755 return Error(PtrLoc, "store operand must be a pointer");
3756 if (!Val->getType()->isFirstClassType())
3757 return Error(Loc, "store operand must be a first class value");
3758 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3759 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003760 if (isAtomic && !Alignment)
3761 return Error(Loc, "atomic store must have explicit non-zero alignment");
3762 if (Ordering == Acquire || Ordering == AcquireRelease)
3763 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003764
Eli Friedman21006d42011-08-09 23:02:53 +00003765 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003766 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003767}
3768
Eli Friedmanff030482011-07-28 21:48:00 +00003769/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003770/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3771/// 'singlethread'? AtomicOrdering
3772int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003773 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3774 bool AteExtraComma = false;
3775 AtomicOrdering Ordering = NotAtomic;
3776 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003777 bool isVolatile = false;
3778
3779 if (EatIfPresent(lltok::kw_volatile))
3780 isVolatile = true;
3781
Eli Friedmanff030482011-07-28 21:48:00 +00003782 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3783 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3784 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3785 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3786 ParseTypeAndValue(New, NewLoc, PFS) ||
3787 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3788 return true;
3789
3790 if (Ordering == Unordered)
3791 return TokError("cmpxchg cannot be unordered");
3792 if (!Ptr->getType()->isPointerTy())
3793 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3794 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3795 return Error(CmpLoc, "compare value and pointer type do not match");
3796 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3797 return Error(NewLoc, "new value and pointer type do not match");
3798 if (!New->getType()->isIntegerTy())
3799 return Error(NewLoc, "cmpxchg operand must be an integer");
3800 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3801 if (Size < 8 || (Size & (Size - 1)))
3802 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3803 " integer");
3804
3805 AtomicCmpXchgInst *CXI =
3806 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3807 CXI->setVolatile(isVolatile);
3808 Inst = CXI;
3809 return AteExtraComma ? InstExtraComma : InstNormal;
3810}
3811
3812/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003813/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3814/// 'singlethread'? AtomicOrdering
3815int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003816 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3817 bool AteExtraComma = false;
3818 AtomicOrdering Ordering = NotAtomic;
3819 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003820 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003821 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003822
3823 if (EatIfPresent(lltok::kw_volatile))
3824 isVolatile = true;
3825
Eli Friedmanff030482011-07-28 21:48:00 +00003826 switch (Lex.getKind()) {
3827 default: return TokError("expected binary operation in atomicrmw");
3828 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3829 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3830 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3831 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3832 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3833 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3834 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3835 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3836 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3837 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3838 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3839 }
3840 Lex.Lex(); // Eat the operation.
3841
3842 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3843 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3844 ParseTypeAndValue(Val, ValLoc, PFS) ||
3845 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3846 return true;
3847
3848 if (Ordering == Unordered)
3849 return TokError("atomicrmw cannot be unordered");
3850 if (!Ptr->getType()->isPointerTy())
3851 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3852 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3853 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3854 if (!Val->getType()->isIntegerTy())
3855 return Error(ValLoc, "atomicrmw operand must be an integer");
3856 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3857 if (Size < 8 || (Size & (Size - 1)))
3858 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3859 " integer");
3860
3861 AtomicRMWInst *RMWI =
3862 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3863 RMWI->setVolatile(isVolatile);
3864 Inst = RMWI;
3865 return AteExtraComma ? InstExtraComma : InstNormal;
3866}
3867
Eli Friedman47f35132011-07-25 23:16:38 +00003868/// ParseFence
3869/// ::= 'fence' 'singlethread'? AtomicOrdering
3870int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3871 AtomicOrdering Ordering = NotAtomic;
3872 SynchronizationScope Scope = CrossThread;
3873 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3874 return true;
3875
3876 if (Ordering == Unordered)
3877 return TokError("fence cannot be unordered");
3878 if (Ordering == Monotonic)
3879 return TokError("fence cannot be monotonic");
3880
3881 Inst = new FenceInst(Context, Ordering, Scope);
3882 return InstNormal;
3883}
3884
Chris Lattnerdf986172009-01-02 07:01:27 +00003885/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003886/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003887int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00003888 Value *Ptr = 0;
3889 Value *Val = 0;
3890 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003891
Dan Gohmandcb40a32009-07-29 15:58:36 +00003892 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003893
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003894 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003895
Nadav Rotem16087692011-12-05 06:29:09 +00003896 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003897 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003898
Chris Lattnerdf986172009-01-02 07:01:27 +00003899 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003900 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003901 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003902 if (Lex.getKind() == lltok::MetadataVar) {
3903 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003904 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003905 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003906 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00003907 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003908 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00003909 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
3910 return Error(EltLoc, "getelementptr index type missmatch");
3911 if (Val->getType()->isVectorTy()) {
3912 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
3913 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
3914 if (ValNumEl != PtrNumEl)
3915 return Error(EltLoc,
3916 "getelementptr vector index has a wrong number of elements");
3917 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003918 Indices.push_back(Val);
3919 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003920
Nadav Rotem16087692011-12-05 06:29:09 +00003921 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
3922 return Error(EltLoc, "vector getelementptrs must have a single index");
3923
Jay Foada9203102011-07-25 09:48:08 +00003924 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003925 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00003926 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003927 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003928 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003929 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003930}
3931
3932/// ParseExtractValue
3933/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003934int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003935 Value *Val; LocTy Loc;
3936 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003937 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003938 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003939 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003940 return true;
3941
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003942 if (!Val->getType()->isAggregateType())
3943 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003944
Jay Foadfc6d3a42011-07-13 10:26:04 +00003945 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003946 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003947 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003948 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003949}
3950
3951/// ParseInsertValue
3952/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003953int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003954 Value *Val0, *Val1; LocTy Loc0, Loc1;
3955 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003956 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003957 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3958 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3959 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003960 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003961 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003962
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003963 if (!Val0->getType()->isAggregateType())
3964 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003965
Jay Foadfc6d3a42011-07-13 10:26:04 +00003966 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003967 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003968 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003969 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003970}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003971
3972//===----------------------------------------------------------------------===//
3973// Embedded metadata.
3974//===----------------------------------------------------------------------===//
3975
3976/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003977/// ::= Element (',' Element)*
3978/// Element
3979/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003980bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003981 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003982 // Check for an empty list.
3983 if (Lex.getKind() == lltok::rbrace)
3984 return false;
3985
Nick Lewycky21cc4462009-04-04 07:22:01 +00003986 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003987 // Null is a special case since it is typeless.
3988 if (EatIfPresent(lltok::kw_null)) {
3989 Elts.push_back(0);
3990 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003991 }
Chris Lattnera7352392009-12-30 04:42:57 +00003992
3993 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003994 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00003995 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003996 } while (EatIfPresent(lltok::comma));
3997
3998 return false;
3999}