blob: 095b7c5f6747092e8e8540d3f528bf183dbfa953 [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;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000648 bool IsConstant, UnnamedAddr;
649 GlobalVariable::ThreadLocalMode TLM;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000650 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000651 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000652
Chris Lattner1afcace2011-07-09 17:41:24 +0000653 Type *Ty = 0;
Hans Wennborgce718ff2012-06-23 11:37:03 +0000654 if (ParseOptionalThreadLocal(TLM) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
657 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
660 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000661
Chris Lattnerdf986172009-01-02 07:01:27 +0000662 // If the linkage is specified and is external, then no initializer is
663 // present.
664 Constant *Init = 0;
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000666 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
669 return true;
670 }
671
Duncan Sands1df98592010-02-16 11:11:14 +0000672 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000673 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000674
Chris Lattnerdf986172009-01-02 07:01:27 +0000675 GlobalVariable *GV = 0;
676
677 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000678 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000679 if (GlobalValue *GVal = M->getNamedValue(Name)) {
680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 GV = cast<GlobalVariable>(GVal);
683 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000684 } else {
685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefValIDs.find(NumberedVals.size());
687 if (I != ForwardRefValIDs.end()) {
688 GV = cast<GlobalVariable>(I->second.first);
689 ForwardRefValIDs.erase(I);
690 }
691 }
692
693 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000695 Name, 0, GlobalVariable::NotThreadLocal,
696 AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +0000697 } else {
698 if (GV->getType()->getElementType() != Ty)
699 return Error(TyLoc,
700 "forward reference and definition of global have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000701
Chris Lattnerdf986172009-01-02 07:01:27 +0000702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
704 }
705
706 if (Name.empty())
707 NumberedVals.push_back(GV);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000708
Chris Lattnerdf986172009-01-02 07:01:27 +0000709 // Set the parsed properties on the global.
710 if (Init)
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Hans Wennborgce718ff2012-06-23 11:37:03 +0000715 GV->setThreadLocalMode(TLM);
Rafael Espindolabea46262011-01-08 16:42:36 +0000716 GV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattnerdf986172009-01-02 07:01:27 +0000718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
720 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000721
Chris Lattnerdf986172009-01-02 07:01:27 +0000722 if (Lex.getKind() == lltok::kw_section) {
723 Lex.Lex();
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
726 return true;
727 } else if (Lex.getKind() == lltok::kw_align) {
728 unsigned Alignment;
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
731 } else {
732 TokError("unknown global variable property!");
733 }
734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattnerdf986172009-01-02 07:01:27 +0000736 return false;
737}
738
739
740//===----------------------------------------------------------------------===//
741// GlobalValue Reference/Resolution Routines.
742//===----------------------------------------------------------------------===//
743
744/// GetGlobalVal - Get a value with the specified name or ID, creating a
745/// forward reference record if needed. This can return null if the value
746/// exists but does not have the right type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000747GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +0000748 LocTy Loc) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000749 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000750 if (PTy == 0) {
751 Error(Loc, "global variable reference must have pointer type");
752 return 0;
753 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000754
Chris Lattnerdf986172009-01-02 07:01:27 +0000755 // Look this name up in the normal function symbol table.
756 GlobalValue *Val =
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Chris Lattnerdf986172009-01-02 07:01:27 +0000759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
761 if (Val == 0) {
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000767
Chris Lattnerdf986172009-01-02 07:01:27 +0000768 // If we have the value in the symbol table or fwd-ref table, return it.
769 if (Val) {
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000772 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000773 return 0;
774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Chris Lattnerdf986172009-01-02 07:01:27 +0000776 // Otherwise, create a new forward reference for this value and remember it.
777 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000780 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000783
Chris Lattnerdf986172009-01-02 07:01:27 +0000784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
785 return FwdVal;
786}
787
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000788GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +0000790 if (PTy == 0) {
791 Error(Loc, "global variable reference must have pointer type");
792 return 0;
793 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerdf986172009-01-02 07:01:27 +0000795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Chris Lattnerdf986172009-01-02 07:01:27 +0000797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
799 if (Val == 0) {
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Chris Lattnerdf986172009-01-02 07:01:27 +0000806 // If we have the value in the symbol table or fwd-ref table, return it.
807 if (Val) {
808 if (Val->getType() == Ty) return Val;
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000810 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +0000811 return 0;
812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattnerdf986172009-01-02 07:01:27 +0000814 // Otherwise, create a new forward reference for this value and remember it.
815 GlobalValue *FwdVal;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
Chris Lattner1afcace2011-07-09 17:41:24 +0000818 else
Owen Andersone9b11b42009-07-08 19:03:57 +0000819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000821
Chris Lattnerdf986172009-01-02 07:01:27 +0000822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
823 return FwdVal;
824}
825
826
827//===----------------------------------------------------------------------===//
828// Helper Routines.
829//===----------------------------------------------------------------------===//
830
831/// ParseToken - If the current token has the specified kind, eat it and return
832/// success. Otherwise, emit the specified error and return failure.
833bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
836 Lex.Lex();
837 return false;
838}
839
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000840/// ParseStringConstant
841/// ::= StringConstant
842bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
846 Lex.Lex();
847 return false;
848}
849
850/// ParseUInt32
851/// ::= uint32
852bool LLParser::ParseUInt32(unsigned &Val) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
858 Val = Val64;
859 Lex.Lex();
860 return false;
861}
862
Hans Wennborgce718ff2012-06-23 11:37:03 +0000863/// ParseTLSModel
864/// := 'localdynamic'
865/// := 'initialexec'
866/// := 'localexec'
867bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
868 switch (Lex.getKind()) {
869 default:
870 return TokError("expected localdynamic, initialexec or localexec");
871 case lltok::kw_localdynamic:
872 TLM = GlobalVariable::LocalDynamicTLSModel;
873 break;
874 case lltok::kw_initialexec:
875 TLM = GlobalVariable::InitialExecTLSModel;
876 break;
877 case lltok::kw_localexec:
878 TLM = GlobalVariable::LocalExecTLSModel;
879 break;
880 }
881
882 Lex.Lex();
883 return false;
884}
885
886/// ParseOptionalThreadLocal
887/// := /*empty*/
888/// := 'thread_local'
889/// := 'thread_local' '(' tlsmodel ')'
890bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
891 TLM = GlobalVariable::NotThreadLocal;
892 if (!EatIfPresent(lltok::kw_thread_local))
893 return false;
894
895 TLM = GlobalVariable::GeneralDynamicTLSModel;
896 if (Lex.getKind() == lltok::lparen) {
897 Lex.Lex();
898 return ParseTLSModel(TLM) ||
899 ParseToken(lltok::rparen, "expected ')' after thread local model");
900 }
901 return false;
902}
Chris Lattnerdf986172009-01-02 07:01:27 +0000903
904/// ParseOptionalAddrSpace
905/// := /*empty*/
906/// := 'addrspace' '(' uint32 ')'
907bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
908 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000909 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000910 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000911 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000912 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000913 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000914}
Chris Lattnerdf986172009-01-02 07:01:27 +0000915
916/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
917/// indicates what kind of attribute list this is: 0: function arg, 1: result,
918/// 2: function attr.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000919bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000922
Chris Lattnerdf986172009-01-02 07:01:27 +0000923 while (1) {
924 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000925 default: // End of attributes.
926 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
927 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000928
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000929 // As a hack, we allow "align 2" on functions as a synonym for
930 // "alignstack 2".
931 if (AttrKind == 2 &&
932 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
933 return Error(AttrLoc, "invalid use of attribute on a function");
934
935 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000936 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000937
Chris Lattnerdf986172009-01-02 07:01:27 +0000938 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000939 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
940 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
941 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
942 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
943 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
944 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
945 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
946 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000947
Devang Patel578efa92009-06-05 21:57:13 +0000948 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
949 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000950 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Rafael Espindola25456ef2011-10-03 14:45:37 +0000951 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
Devang Patel578efa92009-06-05 21:57:13 +0000952 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
953 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
954 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000955 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000956 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
957 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
958 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
959 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
960 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
961 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000962 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
John McCall3a3465b2011-06-15 20:36:13 +0000963 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000964 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000965
Charles Davis1e063d12010-02-12 00:31:15 +0000966 case lltok::kw_alignstack: {
967 unsigned Alignment;
968 if (ParseOptionalStackAlignment(Alignment))
969 return true;
970 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
971 continue;
972 }
973
Chris Lattnerdf986172009-01-02 07:01:27 +0000974 case lltok::kw_align: {
975 unsigned Alignment;
976 if (ParseOptionalAlignment(Alignment))
977 return true;
978 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
979 continue;
980 }
Charles Davis1e063d12010-02-12 00:31:15 +0000981
Chris Lattnerdf986172009-01-02 07:01:27 +0000982 }
983 Lex.Lex();
984 }
985}
986
987/// ParseOptionalLinkage
988/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000989/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000990/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000991/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000992/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000993/// ::= 'internal'
994/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000995/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000996/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000997/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000998/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000999/// ::= 'appending'
1000/// ::= 'dllexport'
1001/// ::= 'common'
1002/// ::= 'dllimport'
1003/// ::= 'extern_weak'
1004/// ::= 'external'
1005bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1006 HasLinkage = false;
1007 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001008 default: Res=GlobalValue::ExternalLinkage; return false;
1009 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1010 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +00001011 case lltok::kw_linker_private_weak:
1012 Res = GlobalValue::LinkerPrivateWeakLinkage;
1013 break;
Bill Wendling55ae5152010-08-20 22:05:50 +00001014 case lltok::kw_linker_private_weak_def_auto:
1015 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1016 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001017 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1018 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1019 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1020 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1021 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +00001022 case lltok::kw_available_externally:
1023 Res = GlobalValue::AvailableExternallyLinkage;
1024 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +00001025 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1026 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1027 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1028 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1029 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1030 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001031 }
1032 Lex.Lex();
1033 HasLinkage = true;
1034 return false;
1035}
1036
1037/// ParseOptionalVisibility
1038/// ::= /*empty*/
1039/// ::= 'default'
1040/// ::= 'hidden'
1041/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001042///
Chris Lattnerdf986172009-01-02 07:01:27 +00001043bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1044 switch (Lex.getKind()) {
1045 default: Res = GlobalValue::DefaultVisibility; return false;
1046 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1047 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1048 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1049 }
1050 Lex.Lex();
1051 return false;
1052}
1053
1054/// ParseOptionalCallingConv
1055/// ::= /*empty*/
1056/// ::= 'ccc'
1057/// ::= 'fastcc'
1058/// ::= 'coldcc'
1059/// ::= 'x86_stdcallcc'
1060/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001061/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001062/// ::= 'arm_apcscc'
1063/// ::= 'arm_aapcscc'
1064/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001065/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001066/// ::= 'ptx_kernel'
1067/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001068/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001069///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001070bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001071 switch (Lex.getKind()) {
1072 default: CC = CallingConv::C; return false;
1073 case lltok::kw_ccc: CC = CallingConv::C; break;
1074 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1075 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1076 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1077 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001078 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001079 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1080 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1081 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001082 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001083 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1084 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001085 case lltok::kw_cc: {
1086 unsigned ArbitraryCC;
1087 Lex.Lex();
David Blaikie4d6ccb52012-01-20 21:51:11 +00001088 if (ParseUInt32(ArbitraryCC))
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001089 return true;
David Blaikie4d6ccb52012-01-20 21:51:11 +00001090 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1091 return false;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001092 }
Chris Lattnerdf986172009-01-02 07:01:27 +00001093 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001094
Chris Lattnerdf986172009-01-02 07:01:27 +00001095 Lex.Lex();
1096 return false;
1097}
1098
Chris Lattnerb8c46862009-12-30 05:31:19 +00001099/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001100/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001101bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1102 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001103 do {
1104 if (Lex.getKind() != lltok::MetadataVar)
1105 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001106
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001107 std::string Name = Lex.getStrVal();
Benjamin Kramer85dadec2011-12-06 11:50:26 +00001108 unsigned MDK = M->getMDKindID(Name);
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001109 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001110
Chris Lattner442ffa12009-12-29 21:53:55 +00001111 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001112 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001113
1114 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001115 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001116
Dan Gohman68261142010-08-24 14:35:45 +00001117 // This code is similar to that of ParseMetadataValue, however it needs to
1118 // have special-case code for a forward reference; see the comments on
1119 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1120 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001121 if (Lex.getKind() == lltok::lbrace) {
1122 ValID ID;
1123 if (ParseMetadataListValue(ID, PFS))
1124 return true;
1125 assert(ID.Kind == ValID::t_MDNode);
1126 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001127 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001128 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001129 if (ParseMDNodeID(Node, NodeID))
1130 return true;
1131 if (Node) {
1132 // If we got the node, add it to the instruction.
1133 Inst->setMetadata(MDK, Node);
1134 } else {
1135 MDRef R = { Loc, MDK, NodeID };
1136 // Otherwise, remember that this should be resolved later.
1137 ForwardRefInstMetadata[Inst].push_back(R);
1138 }
Chris Lattner449c3102010-04-01 05:14:45 +00001139 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001140
1141 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001142 } while (EatIfPresent(lltok::comma));
1143 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001144}
1145
Chris Lattnerdf986172009-01-02 07:01:27 +00001146/// ParseOptionalAlignment
1147/// ::= /* empty */
1148/// ::= 'align' 4
1149bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1150 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001151 if (!EatIfPresent(lltok::kw_align))
1152 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001153 LocTy AlignLoc = Lex.getLoc();
1154 if (ParseUInt32(Alignment)) return true;
1155 if (!isPowerOf2_32(Alignment))
1156 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001157 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001158 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001159 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001160}
1161
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001162/// ParseOptionalCommaAlign
1163/// ::=
1164/// ::= ',' align 4
1165///
1166/// This returns with AteExtraComma set to true if it ate an excess comma at the
1167/// end.
1168bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1169 bool &AteExtraComma) {
1170 AteExtraComma = false;
1171 while (EatIfPresent(lltok::comma)) {
1172 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001173 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001174 AteExtraComma = true;
1175 return false;
1176 }
1177
Chris Lattner093eed12010-04-23 00:50:50 +00001178 if (Lex.getKind() != lltok::kw_align)
1179 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001180
Chris Lattner093eed12010-04-23 00:50:50 +00001181 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001182 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001183
Devang Patelf633a062009-09-17 23:04:48 +00001184 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001185}
1186
Eli Friedman47f35132011-07-25 23:16:38 +00001187/// ParseScopeAndOrdering
1188/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1189/// else: ::=
1190///
1191/// This sets Scope and Ordering to the parsed values.
1192bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1193 AtomicOrdering &Ordering) {
1194 if (!isAtomic)
1195 return false;
1196
1197 Scope = CrossThread;
1198 if (EatIfPresent(lltok::kw_singlethread))
1199 Scope = SingleThread;
1200 switch (Lex.getKind()) {
1201 default: return TokError("Expected ordering on atomic instruction");
1202 case lltok::kw_unordered: Ordering = Unordered; break;
1203 case lltok::kw_monotonic: Ordering = Monotonic; break;
1204 case lltok::kw_acquire: Ordering = Acquire; break;
1205 case lltok::kw_release: Ordering = Release; break;
1206 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1207 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1208 }
1209 Lex.Lex();
1210 return false;
1211}
1212
Charles Davis1e063d12010-02-12 00:31:15 +00001213/// ParseOptionalStackAlignment
1214/// ::= /* empty */
1215/// ::= 'alignstack' '(' 4 ')'
1216bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1217 Alignment = 0;
1218 if (!EatIfPresent(lltok::kw_alignstack))
1219 return false;
1220 LocTy ParenLoc = Lex.getLoc();
1221 if (!EatIfPresent(lltok::lparen))
1222 return Error(ParenLoc, "expected '('");
1223 LocTy AlignLoc = Lex.getLoc();
1224 if (ParseUInt32(Alignment)) return true;
1225 ParenLoc = Lex.getLoc();
1226 if (!EatIfPresent(lltok::rparen))
1227 return Error(ParenLoc, "expected ')'");
1228 if (!isPowerOf2_32(Alignment))
1229 return Error(AlignLoc, "stack alignment is not a power of two");
1230 return false;
1231}
Devang Patelf633a062009-09-17 23:04:48 +00001232
Chris Lattner628c13a2009-12-30 05:14:00 +00001233/// ParseIndexList - This parses the index list for an insert/extractvalue
1234/// instruction. This sets AteExtraComma in the case where we eat an extra
1235/// comma at the end of the line and find that it is followed by metadata.
1236/// Clients that don't allow metadata can call the version of this function that
1237/// only takes one argument.
1238///
Chris Lattnerdf986172009-01-02 07:01:27 +00001239/// ParseIndexList
1240/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001241///
1242bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1243 bool &AteExtraComma) {
1244 AteExtraComma = false;
1245
Chris Lattnerdf986172009-01-02 07:01:27 +00001246 if (Lex.getKind() != lltok::comma)
1247 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001248
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001249 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001250 if (Lex.getKind() == lltok::MetadataVar) {
1251 AteExtraComma = true;
1252 return false;
1253 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001254 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001255 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 Indices.push_back(Idx);
1257 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001258
Chris Lattnerdf986172009-01-02 07:01:27 +00001259 return false;
1260}
1261
1262//===----------------------------------------------------------------------===//
1263// Type Parsing.
1264//===----------------------------------------------------------------------===//
1265
Chris Lattner1afcace2011-07-09 17:41:24 +00001266/// ParseType - Parse a type.
1267bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1268 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001269 switch (Lex.getKind()) {
1270 default:
1271 return TokError("expected type");
1272 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001273 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001274 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001276 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001277 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001278 // Type ::= StructType
1279 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001280 return true;
1281 break;
1282 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001283 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001284 Lex.Lex(); // eat the lsquare.
1285 if (ParseArrayVectorType(Result, false))
1286 return true;
1287 break;
1288 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001289 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001290 Lex.Lex();
1291 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001292 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001293 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001294 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001295 } else if (ParseArrayVectorType(Result, true))
1296 return true;
1297 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001298 case lltok::LocalVar: {
1299 // Type ::= %foo
1300 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1301
1302 // If the type hasn't been defined yet, create a forward definition and
1303 // remember where that forward def'n was seen (in case it never is defined).
1304 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001305 Entry.first = StructType::create(Context, Lex.getStrVal());
Chris Lattner1afcace2011-07-09 17:41:24 +00001306 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001307 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001308 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001309 Lex.Lex();
1310 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001312
Chris Lattner1afcace2011-07-09 17:41:24 +00001313 case lltok::LocalVarID: {
1314 // Type ::= %4
1315 if (Lex.getUIntVal() >= NumberedTypes.size())
1316 NumberedTypes.resize(Lex.getUIntVal()+1);
1317 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1318
1319 // If the type hasn't been defined yet, create a forward definition and
1320 // remember where that forward def'n was seen (in case it never is defined).
1321 if (Entry.first == 0) {
Chris Lattner3ebb6492011-08-12 18:06:37 +00001322 Entry.first = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +00001323 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001324 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001325 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001326 Lex.Lex();
1327 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001328 }
1329 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001330
1331 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001332 while (1) {
1333 switch (Lex.getKind()) {
1334 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001335 default:
1336 if (!AllowVoid && Result->isVoidTy())
1337 return Error(TypeLoc, "void type only allowed for function results");
1338 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001339
Chris Lattner1afcace2011-07-09 17:41:24 +00001340 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001341 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001342 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001343 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001344 if (Result->isVoidTy())
1345 return TokError("pointers to void are invalid - use i8* instead");
1346 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001347 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001348 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001349 Lex.Lex();
1350 break;
1351
Chris Lattner1afcace2011-07-09 17:41:24 +00001352 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001353 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001354 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001356 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001357 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001358 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001359 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001360 unsigned AddrSpace;
1361 if (ParseOptionalAddrSpace(AddrSpace) ||
1362 ParseToken(lltok::star, "expected '*' in address space"))
1363 return true;
1364
Chris Lattner1afcace2011-07-09 17:41:24 +00001365 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001366 break;
1367 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001368
Chris Lattnerdf986172009-01-02 07:01:27 +00001369 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1370 case lltok::lparen:
1371 if (ParseFunctionType(Result))
1372 return true;
1373 break;
1374 }
1375 }
1376}
1377
1378/// ParseParameterList
1379/// ::= '(' ')'
1380/// ::= '(' Arg (',' Arg)* ')'
1381/// Arg
1382/// ::= Type OptionalAttributes Value OptionalAttributes
1383bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1384 PerFunctionState &PFS) {
1385 if (ParseToken(lltok::lparen, "expected '(' in call"))
1386 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387
Chris Lattnerdf986172009-01-02 07:01:27 +00001388 while (Lex.getKind() != lltok::rparen) {
1389 // If this isn't the first argument, we need a comma.
1390 if (!ArgList.empty() &&
1391 ParseToken(lltok::comma, "expected ',' in argument list"))
1392 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001393
Chris Lattnerdf986172009-01-02 07:01:27 +00001394 // Parse the argument.
1395 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001396 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001397 Attributes ArgAttrs1;
1398 Attributes ArgAttrs2;
Chris Lattnerdf986172009-01-02 07:01:27 +00001399 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001400 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001401 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001402
Chris Lattner287881d2009-12-30 02:11:14 +00001403 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001404 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001405 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001406 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1407 }
1408
1409 Lex.Lex(); // Lex the ')'.
1410 return false;
1411}
1412
1413
1414
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001415/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001416/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001417/// ::= '(' ArgTypeListI ')'
1418/// ArgTypeListI
1419/// ::= /*empty*/
1420/// ::= '...'
1421/// ::= ArgTypeList ',' '...'
1422/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001423///
Chris Lattner1afcace2011-07-09 17:41:24 +00001424bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1425 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001426 isVarArg = false;
1427 assert(Lex.getKind() == lltok::lparen);
1428 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001429
Chris Lattnerdf986172009-01-02 07:01:27 +00001430 if (Lex.getKind() == lltok::rparen) {
1431 // empty
1432 } else if (Lex.getKind() == lltok::dotdotdot) {
1433 isVarArg = true;
1434 Lex.Lex();
1435 } else {
1436 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001437 Type *ArgTy = 0;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001438 Attributes Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001439 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001440
Chris Lattner1afcace2011-07-09 17:41:24 +00001441 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001442 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001443
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001444 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001445 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001446
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001447 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001448 Name = Lex.getStrVal();
1449 Lex.Lex();
1450 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001451
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001452 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001453 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001454
Chris Lattnerdf986172009-01-02 07:01:27 +00001455 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001457 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001459 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001461 break;
1462 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001463
Chris Lattnerdf986172009-01-02 07:01:27 +00001464 // Otherwise must be an argument type.
1465 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001466 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001467
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001468 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001469 return Error(TypeLoc, "argument can not have void type");
1470
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001471 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 Name = Lex.getStrVal();
1473 Lex.Lex();
1474 } else {
1475 Name = "";
1476 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001477
Chris Lattner1afcace2011-07-09 17:41:24 +00001478 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001479 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001480
Chris Lattnerdf986172009-01-02 07:01:27 +00001481 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1482 }
1483 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001484
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001485 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001486}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnerdf986172009-01-02 07:01:27 +00001488/// ParseFunctionType
1489/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001490bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001491 assert(Lex.getKind() == lltok::lparen);
1492
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001493 if (!FunctionType::isValidReturnType(Result))
1494 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001495
Chris Lattner1afcace2011-07-09 17:41:24 +00001496 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001497 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001498 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001499 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001500
Chris Lattnerdf986172009-01-02 07:01:27 +00001501 // Reject names on the arguments lists.
1502 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1503 if (!ArgList[i].Name.empty())
1504 return Error(ArgList[i].Loc, "argument name invalid in function type");
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001505 if (ArgList[i].Attrs)
Chris Lattnera16546a2011-06-17 17:37:13 +00001506 return Error(ArgList[i].Loc,
1507 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001508 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001509
Jay Foad5fdd6c82011-07-12 14:06:48 +00001510 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001511 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001512 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001513
Chris Lattner1afcace2011-07-09 17:41:24 +00001514 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001515 return false;
1516}
1517
Chris Lattner1afcace2011-07-09 17:41:24 +00001518/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1519/// other structs.
1520bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1521 SmallVector<Type*, 8> Elts;
1522 if (ParseStructBody(Elts)) return true;
1523
1524 Result = StructType::get(Context, Elts, Packed);
1525 return false;
1526}
1527
1528/// ParseStructDefinition - Parse a struct in a 'type' definition.
1529bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1530 std::pair<Type*, LocTy> &Entry,
1531 Type *&ResultTy) {
1532 // If the type was already defined, diagnose the redefinition.
1533 if (Entry.first && !Entry.second.isValid())
1534 return Error(TypeLoc, "redefinition of type");
1535
1536 // If we have opaque, just return without filling in the definition for the
1537 // struct. This counts as a definition as far as the .ll file goes.
1538 if (EatIfPresent(lltok::kw_opaque)) {
1539 // This type is being defined, so clear the location to indicate this.
1540 Entry.second = SMLoc();
1541
1542 // If this type number has never been uttered, create it.
1543 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001544 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001545 ResultTy = Entry.first;
1546 return false;
1547 }
1548
1549 // If the type starts with '<', then it is either a packed struct or a vector.
1550 bool isPacked = EatIfPresent(lltok::less);
1551
1552 // If we don't have a struct, then we have a random type alias, which we
1553 // accept for compatibility with old files. These types are not allowed to be
1554 // forward referenced and not allowed to be recursive.
1555 if (Lex.getKind() != lltok::lbrace) {
1556 if (Entry.first)
1557 return Error(TypeLoc, "forward references to non-struct type");
1558
1559 ResultTy = 0;
1560 if (isPacked)
1561 return ParseArrayVectorType(ResultTy, true);
1562 return ParseType(ResultTy);
1563 }
1564
1565 // This type is being defined, so clear the location to indicate this.
1566 Entry.second = SMLoc();
1567
1568 // If this type number has never been uttered, create it.
1569 if (Entry.first == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +00001570 Entry.first = StructType::create(Context, Name);
Chris Lattner1afcace2011-07-09 17:41:24 +00001571
1572 StructType *STy = cast<StructType>(Entry.first);
1573
1574 SmallVector<Type*, 8> Body;
1575 if (ParseStructBody(Body) ||
1576 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1577 return true;
1578
1579 STy->setBody(Body, isPacked);
1580 ResultTy = STy;
1581 return false;
1582}
1583
1584
Chris Lattnerdf986172009-01-02 07:01:27 +00001585/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001586/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001587/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001588/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001589/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001590/// ::= '<' '{' Type (',' Type)* '}' '>'
1591bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001592 assert(Lex.getKind() == lltok::lbrace);
1593 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattner1afcace2011-07-09 17:41:24 +00001595 // Handle the empty struct.
1596 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001597 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001598
Chris Lattnera9a9e072009-03-09 04:49:14 +00001599 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001600 Type *Ty = 0;
1601 if (ParseType(Ty)) return true;
1602 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattner1afcace2011-07-09 17:41:24 +00001604 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001605 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001606
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001607 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001608 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001609 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001610
Chris Lattner1afcace2011-07-09 17:41:24 +00001611 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001612 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner1afcace2011-07-09 17:41:24 +00001614 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001615 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001616
Chris Lattner1afcace2011-07-09 17:41:24 +00001617 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001618}
1619
1620/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1621/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001622/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001623/// ::= '[' APSINTVAL 'x' Types ']'
1624/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001625bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001626 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1627 Lex.getAPSIntVal().getBitWidth() > 64)
1628 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattnerdf986172009-01-02 07:01:27 +00001630 LocTy SizeLoc = Lex.getLoc();
1631 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001632 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001634 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1635 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001636
1637 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001638 Type *EltTy = 0;
1639 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001640
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001641 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1642 "expected end of sequential type"))
1643 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001644
Chris Lattnerdf986172009-01-02 07:01:27 +00001645 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001646 if (Size == 0)
1647 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 if ((unsigned)Size != Size)
1649 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001650 if (!VectorType::isValidElementType(EltTy))
Nadav Rotem16087692011-12-05 06:29:09 +00001651 return Error(TypeLoc,
1652 "vector element type must be fp, integer or a pointer to these types");
Owen Andersondebcb012009-07-29 22:17:13 +00001653 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001654 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001655 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001656 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001657 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001658 }
1659 return false;
1660}
1661
1662//===----------------------------------------------------------------------===//
1663// Function Semantic Analysis.
1664//===----------------------------------------------------------------------===//
1665
Chris Lattner09d9ef42009-10-28 03:39:23 +00001666LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1667 int functionNumber)
1668 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001669
1670 // Insert unnamed arguments into the NumberedVals list.
1671 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1672 AI != E; ++AI)
1673 if (!AI->hasName())
1674 NumberedVals.push_back(AI);
1675}
1676
1677LLParser::PerFunctionState::~PerFunctionState() {
1678 // If there were any forward referenced non-basicblock values, delete them.
1679 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1680 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1681 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001682 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001683 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001684 delete I->second.first;
1685 I->second.first = 0;
1686 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001687
Chris Lattnerdf986172009-01-02 07:01:27 +00001688 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1689 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1690 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001691 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001692 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001693 delete I->second.first;
1694 I->second.first = 0;
1695 }
1696}
1697
Chris Lattner09d9ef42009-10-28 03:39:23 +00001698bool LLParser::PerFunctionState::FinishFunction() {
1699 // Check to see if someone took the address of labels in this block.
1700 if (!P.ForwardRefBlockAddresses.empty()) {
1701 ValID FunctionID;
1702 if (!F.getName().empty()) {
1703 FunctionID.Kind = ValID::t_GlobalName;
1704 FunctionID.StrVal = F.getName();
1705 } else {
1706 FunctionID.Kind = ValID::t_GlobalID;
1707 FunctionID.UIntVal = FunctionNumber;
1708 }
1709
1710 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1711 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1712 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1713 // Resolve all these references.
1714 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1715 return true;
1716
1717 P.ForwardRefBlockAddresses.erase(FRBAI);
1718 }
1719 }
1720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 if (!ForwardRefVals.empty())
1722 return P.Error(ForwardRefVals.begin()->second.second,
1723 "use of undefined value '%" + ForwardRefVals.begin()->first +
1724 "'");
1725 if (!ForwardRefValIDs.empty())
1726 return P.Error(ForwardRefValIDs.begin()->second.second,
1727 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001728 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001729 return false;
1730}
1731
1732
1733/// GetVal - Get a value with the specified name or ID, creating a
1734/// forward reference record if needed. This can return null if the value
1735/// exists but does not have the right type.
1736Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001737 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001738 // Look this name up in the normal function symbol table.
1739 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Chris Lattnerdf986172009-01-02 07:01:27 +00001741 // If this is a forward reference for the value, see if we already created a
1742 // forward ref record.
1743 if (Val == 0) {
1744 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1745 I = ForwardRefVals.find(Name);
1746 if (I != ForwardRefVals.end())
1747 Val = I->second.first;
1748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001749
Chris Lattnerdf986172009-01-02 07:01:27 +00001750 // If we have the value in the symbol table or fwd-ref table, return it.
1751 if (Val) {
1752 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001753 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001754 P.Error(Loc, "'%" + Name + "' is not a basic block");
1755 else
1756 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001757 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001758 return 0;
1759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001760
Chris Lattnerdf986172009-01-02 07:01:27 +00001761 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001762 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001763 P.Error(Loc, "invalid use of a non-first-class type");
1764 return 0;
1765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001766
Chris Lattnerdf986172009-01-02 07:01:27 +00001767 // Otherwise, create a new forward reference for this value and remember it.
1768 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001769 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001770 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001771 else
1772 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattnerdf986172009-01-02 07:01:27 +00001774 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1775 return FwdVal;
1776}
1777
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001778Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001779 LocTy Loc) {
1780 // Look this name up in the normal function symbol table.
1781 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001782
Chris Lattnerdf986172009-01-02 07:01:27 +00001783 // If this is a forward reference for the value, see if we already created a
1784 // forward ref record.
1785 if (Val == 0) {
1786 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1787 I = ForwardRefValIDs.find(ID);
1788 if (I != ForwardRefValIDs.end())
1789 Val = I->second.first;
1790 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001791
Chris Lattnerdf986172009-01-02 07:01:27 +00001792 // If we have the value in the symbol table or fwd-ref table, return it.
1793 if (Val) {
1794 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001795 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001796 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001797 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001798 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001799 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001800 return 0;
1801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001802
Chris Lattner1afcace2011-07-09 17:41:24 +00001803 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001804 P.Error(Loc, "invalid use of a non-first-class type");
1805 return 0;
1806 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001807
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 // Otherwise, create a new forward reference for this value and remember it.
1809 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001810 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001811 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001812 else
1813 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001814
Chris Lattnerdf986172009-01-02 07:01:27 +00001815 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1816 return FwdVal;
1817}
1818
1819/// SetInstName - After an instruction is parsed and inserted into its
1820/// basic block, this installs its name.
1821bool LLParser::PerFunctionState::SetInstName(int NameID,
1822 const std::string &NameStr,
1823 LocTy NameLoc, Instruction *Inst) {
1824 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001825 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 if (NameID != -1 || !NameStr.empty())
1827 return P.Error(NameLoc, "instructions returning void cannot have a name");
1828 return false;
1829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830
Chris Lattnerdf986172009-01-02 07:01:27 +00001831 // If this was a numbered instruction, verify that the instruction is the
1832 // expected value and resolve any forward references.
1833 if (NameStr.empty()) {
1834 // If neither a name nor an ID was specified, just use the next ID.
1835 if (NameID == -1)
1836 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837
Chris Lattnerdf986172009-01-02 07:01:27 +00001838 if (unsigned(NameID) != NumberedVals.size())
1839 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001840 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerdf986172009-01-02 07:01:27 +00001842 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1843 ForwardRefValIDs.find(NameID);
1844 if (FI != ForwardRefValIDs.end()) {
1845 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001847 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001848 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001849 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001850 ForwardRefValIDs.erase(FI);
1851 }
1852
1853 NumberedVals.push_back(Inst);
1854 return false;
1855 }
1856
1857 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1858 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1859 FI = ForwardRefVals.find(NameStr);
1860 if (FI != ForwardRefVals.end()) {
1861 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001863 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001864 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001865 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001866 ForwardRefVals.erase(FI);
1867 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868
Chris Lattnerdf986172009-01-02 07:01:27 +00001869 // Set the name on the instruction.
1870 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871
Benjamin Krameraf812352010-10-16 11:28:23 +00001872 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001873 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001874 NameStr + "'");
1875 return false;
1876}
1877
1878/// GetBB - Get a basic block with the specified name or ID, creating a
1879/// forward reference record if needed.
1880BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1881 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001882 return cast_or_null<BasicBlock>(GetVal(Name,
1883 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001884}
1885
1886BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001887 return cast_or_null<BasicBlock>(GetVal(ID,
1888 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001889}
1890
1891/// DefineBB - Define the specified basic block, which is either named or
1892/// unnamed. If there is an error, this returns null otherwise it returns
1893/// the block being defined.
1894BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1895 LocTy Loc) {
1896 BasicBlock *BB;
1897 if (Name.empty())
1898 BB = GetBB(NumberedVals.size(), Loc);
1899 else
1900 BB = GetBB(Name, Loc);
1901 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001902
Chris Lattnerdf986172009-01-02 07:01:27 +00001903 // Move the block to the end of the function. Forward ref'd blocks are
1904 // inserted wherever they happen to be referenced.
1905 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Chris Lattnerdf986172009-01-02 07:01:27 +00001907 // Remove the block from forward ref sets.
1908 if (Name.empty()) {
1909 ForwardRefValIDs.erase(NumberedVals.size());
1910 NumberedVals.push_back(BB);
1911 } else {
1912 // BB forward references are already in the function symbol table.
1913 ForwardRefVals.erase(Name);
1914 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001915
Chris Lattnerdf986172009-01-02 07:01:27 +00001916 return BB;
1917}
1918
1919//===----------------------------------------------------------------------===//
1920// Constants.
1921//===----------------------------------------------------------------------===//
1922
1923/// ParseValID - Parse an abstract value that doesn't necessarily have a
1924/// type implied. For example, if we parse "4" we don't know what integer type
1925/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001926/// sanity. PFS is used to convert function-local operands of metadata (since
1927/// metadata operands are not just parsed here but also converted to values).
1928/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001929bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001930 ID.Loc = Lex.getLoc();
1931 switch (Lex.getKind()) {
1932 default: return TokError("expected value token");
1933 case lltok::GlobalID: // @42
1934 ID.UIntVal = Lex.getUIntVal();
1935 ID.Kind = ValID::t_GlobalID;
1936 break;
1937 case lltok::GlobalVar: // @foo
1938 ID.StrVal = Lex.getStrVal();
1939 ID.Kind = ValID::t_GlobalName;
1940 break;
1941 case lltok::LocalVarID: // %42
1942 ID.UIntVal = Lex.getUIntVal();
1943 ID.Kind = ValID::t_LocalID;
1944 break;
1945 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001946 ID.StrVal = Lex.getStrVal();
1947 ID.Kind = ValID::t_LocalName;
1948 break;
Dan Gohman83448032010-07-14 18:26:50 +00001949 case lltok::exclaim: // !42, !{...}, or !"foo"
1950 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001953 ID.Kind = ValID::t_APSInt;
1954 break;
1955 case lltok::APFloat:
1956 ID.APFloatVal = Lex.getAPFloatVal();
1957 ID.Kind = ValID::t_APFloat;
1958 break;
1959 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001960 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001961 ID.Kind = ValID::t_Constant;
1962 break;
1963 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001964 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001965 ID.Kind = ValID::t_Constant;
1966 break;
1967 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1968 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1969 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Chris Lattnerdf986172009-01-02 07:01:27 +00001971 case lltok::lbrace: {
1972 // ValID ::= '{' ConstVector '}'
1973 Lex.Lex();
1974 SmallVector<Constant*, 16> Elts;
1975 if (ParseGlobalValueVector(Elts) ||
1976 ParseToken(lltok::rbrace, "expected end of struct constant"))
1977 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001978
Chris Lattner1afcace2011-07-09 17:41:24 +00001979 ID.ConstantStructElts = new Constant*[Elts.size()];
1980 ID.UIntVal = Elts.size();
1981 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1982 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 return false;
1984 }
1985 case lltok::less: {
1986 // ValID ::= '<' ConstVector '>' --> Vector.
1987 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1988 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001989 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Chris Lattnerdf986172009-01-02 07:01:27 +00001991 SmallVector<Constant*, 16> Elts;
1992 LocTy FirstEltLoc = Lex.getLoc();
1993 if (ParseGlobalValueVector(Elts) ||
1994 (isPackedStruct &&
1995 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1996 ParseToken(lltok::greater, "expected end of constant"))
1997 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001998
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002000 ID.ConstantStructElts = new Constant*[Elts.size()];
2001 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2002 ID.UIntVal = Elts.size();
2003 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00002004 return false;
2005 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002006
Chris Lattnerdf986172009-01-02 07:01:27 +00002007 if (Elts.empty())
2008 return Error(ID.Loc, "constant vector must not be empty");
2009
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002010 if (!Elts[0]->getType()->isIntegerTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002011 !Elts[0]->getType()->isFloatingPointTy() &&
2012 !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002013 return Error(FirstEltLoc,
Nadav Rotem16087692011-12-05 06:29:09 +00002014 "vector elements must have integer, pointer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Chris Lattnerdf986172009-01-02 07:01:27 +00002016 // Verify that all the vector elements have the same type.
2017 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2018 if (Elts[i]->getType() != Elts[0]->getType())
2019 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002020 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002021 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Chris Lattner2ca5c862011-02-15 00:14:00 +00002023 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002024 ID.Kind = ValID::t_Constant;
2025 return false;
2026 }
2027 case lltok::lsquare: { // Array Constant
2028 Lex.Lex();
2029 SmallVector<Constant*, 16> Elts;
2030 LocTy FirstEltLoc = Lex.getLoc();
2031 if (ParseGlobalValueVector(Elts) ||
2032 ParseToken(lltok::rsquare, "expected end of array constant"))
2033 return true;
2034
2035 // Handle empty element.
2036 if (Elts.empty()) {
2037 // Use undef instead of an array because it's inconvenient to determine
2038 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00002039 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00002040 return false;
2041 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002042
Chris Lattnerdf986172009-01-02 07:01:27 +00002043 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002044 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002045 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Owen Andersondebcb012009-07-29 22:17:13 +00002047 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002048
Chris Lattnerdf986172009-01-02 07:01:27 +00002049 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002050 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002051 if (Elts[i]->getType() != Elts[0]->getType())
2052 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002053 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002054 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002055 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002056
Jay Foad26701082011-06-22 09:24:39 +00002057 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002058 ID.Kind = ValID::t_Constant;
2059 return false;
2060 }
2061 case lltok::kw_c: // c "foo"
2062 Lex.Lex();
Chris Lattner18c7f802012-02-05 02:29:43 +00002063 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2064 false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002065 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2066 ID.Kind = ValID::t_Constant;
2067 return false;
2068
2069 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002070 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2071 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 Lex.Lex();
2073 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002074 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002075 ParseStringConstant(ID.StrVal) ||
2076 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002077 ParseToken(lltok::StringConstant, "expected constraint string"))
2078 return true;
2079 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002080 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002081 ID.Kind = ValID::t_InlineAsm;
2082 return false;
2083 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Chris Lattner09d9ef42009-10-28 03:39:23 +00002085 case lltok::kw_blockaddress: {
2086 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2087 Lex.Lex();
2088
2089 ValID Fn, Label;
2090 LocTy FnLoc, LabelLoc;
2091
2092 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2093 ParseValID(Fn) ||
2094 ParseToken(lltok::comma, "expected comma in block address expression")||
2095 ParseValID(Label) ||
2096 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2097 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002098
Chris Lattner09d9ef42009-10-28 03:39:23 +00002099 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2100 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002101 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002102 return Error(Label.Loc, "expected basic block name in blockaddress");
2103
2104 // Make a global variable as a placeholder for this reference.
2105 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2106 false, GlobalValue::InternalLinkage,
2107 0, "");
2108 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2109 ID.ConstantVal = FwdRef;
2110 ID.Kind = ValID::t_Constant;
2111 return false;
2112 }
2113
Chris Lattnerdf986172009-01-02 07:01:27 +00002114 case lltok::kw_trunc:
2115 case lltok::kw_zext:
2116 case lltok::kw_sext:
2117 case lltok::kw_fptrunc:
2118 case lltok::kw_fpext:
2119 case lltok::kw_bitcast:
2120 case lltok::kw_uitofp:
2121 case lltok::kw_sitofp:
2122 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002123 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002124 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002126 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002127 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002128 Constant *SrcVal;
2129 Lex.Lex();
2130 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2131 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002132 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002133 ParseType(DestTy) ||
2134 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2135 return true;
2136 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2137 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002138 getTypeString(SrcVal->getType()) + "' to '" +
2139 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002141 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 ID.Kind = ValID::t_Constant;
2143 return false;
2144 }
2145 case lltok::kw_extractvalue: {
2146 Lex.Lex();
2147 Constant *Val;
2148 SmallVector<unsigned, 4> Indices;
2149 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2150 ParseGlobalTypeAndValue(Val) ||
2151 ParseIndexList(Indices) ||
2152 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2153 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002154
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002155 if (!Val->getType()->isAggregateType())
2156 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002157 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002158 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002159 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 ID.Kind = ValID::t_Constant;
2161 return false;
2162 }
2163 case lltok::kw_insertvalue: {
2164 Lex.Lex();
2165 Constant *Val0, *Val1;
2166 SmallVector<unsigned, 4> Indices;
2167 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2168 ParseGlobalTypeAndValue(Val0) ||
2169 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2170 ParseGlobalTypeAndValue(Val1) ||
2171 ParseIndexList(Indices) ||
2172 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2173 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002174 if (!Val0->getType()->isAggregateType())
2175 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002176 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002177 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002178 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002179 ID.Kind = ValID::t_Constant;
2180 return false;
2181 }
2182 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002183 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002184 unsigned PredVal, Opc = Lex.getUIntVal();
2185 Constant *Val0, *Val1;
2186 Lex.Lex();
2187 if (ParseCmpPredicate(PredVal, Opc) ||
2188 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2189 ParseGlobalTypeAndValue(Val0) ||
2190 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2191 ParseGlobalTypeAndValue(Val1) ||
2192 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2193 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002194
Chris Lattnerdf986172009-01-02 07:01:27 +00002195 if (Val0->getType() != Val1->getType())
2196 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002197
Chris Lattnerdf986172009-01-02 07:01:27 +00002198 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002199
Chris Lattnerdf986172009-01-02 07:01:27 +00002200 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002201 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002202 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002203 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002204 } else {
2205 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002206 if (!Val0->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00002207 !Val0->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002208 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002209 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 }
2211 ID.Kind = ValID::t_Constant;
2212 return false;
2213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002214
Chris Lattnerdf986172009-01-02 07:01:27 +00002215 // Binary Operators.
2216 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002217 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002218 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002219 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002220 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002221 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002222 case lltok::kw_udiv:
2223 case lltok::kw_sdiv:
2224 case lltok::kw_fdiv:
2225 case lltok::kw_urem:
2226 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002227 case lltok::kw_frem:
2228 case lltok::kw_shl:
2229 case lltok::kw_lshr:
2230 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002231 bool NUW = false;
2232 bool NSW = false;
2233 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002234 unsigned Opc = Lex.getUIntVal();
2235 Constant *Val0, *Val1;
2236 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002237 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002238 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2239 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002240 if (EatIfPresent(lltok::kw_nuw))
2241 NUW = true;
2242 if (EatIfPresent(lltok::kw_nsw)) {
2243 NSW = true;
2244 if (EatIfPresent(lltok::kw_nuw))
2245 NUW = true;
2246 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002247 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2248 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002249 if (EatIfPresent(lltok::kw_exact))
2250 Exact = true;
2251 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002252 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2253 ParseGlobalTypeAndValue(Val0) ||
2254 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2255 ParseGlobalTypeAndValue(Val1) ||
2256 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2257 return true;
2258 if (Val0->getType() != Val1->getType())
2259 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002260 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002261 if (NUW)
2262 return Error(ModifierLoc, "nuw only applies to integer operations");
2263 if (NSW)
2264 return Error(ModifierLoc, "nsw only applies to integer operations");
2265 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002266 // Check that the type is valid for the operator.
2267 switch (Opc) {
2268 case Instruction::Add:
2269 case Instruction::Sub:
2270 case Instruction::Mul:
2271 case Instruction::UDiv:
2272 case Instruction::SDiv:
2273 case Instruction::URem:
2274 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002275 case Instruction::Shl:
2276 case Instruction::AShr:
2277 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002278 if (!Val0->getType()->isIntOrIntVectorTy())
2279 return Error(ID.Loc, "constexpr requires integer operands");
2280 break;
2281 case Instruction::FAdd:
2282 case Instruction::FSub:
2283 case Instruction::FMul:
2284 case Instruction::FDiv:
2285 case Instruction::FRem:
2286 if (!Val0->getType()->isFPOrFPVectorTy())
2287 return Error(ID.Loc, "constexpr requires fp operands");
2288 break;
2289 default: llvm_unreachable("Unknown binary operator!");
2290 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002291 unsigned Flags = 0;
2292 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2293 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002294 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002295 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002296 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002297 ID.Kind = ValID::t_Constant;
2298 return false;
2299 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Chris Lattnerdf986172009-01-02 07:01:27 +00002301 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002302 case lltok::kw_and:
2303 case lltok::kw_or:
2304 case lltok::kw_xor: {
2305 unsigned Opc = Lex.getUIntVal();
2306 Constant *Val0, *Val1;
2307 Lex.Lex();
2308 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2309 ParseGlobalTypeAndValue(Val0) ||
2310 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2311 ParseGlobalTypeAndValue(Val1) ||
2312 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2313 return true;
2314 if (Val0->getType() != Val1->getType())
2315 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002316 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002317 return Error(ID.Loc,
2318 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002319 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002320 ID.Kind = ValID::t_Constant;
2321 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002322 }
2323
Chris Lattnerdf986172009-01-02 07:01:27 +00002324 case lltok::kw_getelementptr:
2325 case lltok::kw_shufflevector:
2326 case lltok::kw_insertelement:
2327 case lltok::kw_extractelement:
2328 case lltok::kw_select: {
2329 unsigned Opc = Lex.getUIntVal();
2330 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002331 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002332 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002333 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002334 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2336 ParseGlobalValueVector(Elts) ||
2337 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2338 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002339
Chris Lattnerdf986172009-01-02 07:01:27 +00002340 if (Opc == Instruction::GetElementPtr) {
Nadav Rotem16087692011-12-05 06:29:09 +00002341 if (Elts.size() == 0 ||
2342 !Elts[0]->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002343 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002344
Jay Foaddab3d292011-07-21 14:31:17 +00002345 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002346 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002347 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002348 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2349 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002350 } else if (Opc == Instruction::Select) {
2351 if (Elts.size() != 3)
2352 return Error(ID.Loc, "expected three operands to select");
2353 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2354 Elts[2]))
2355 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002356 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002357 } else if (Opc == Instruction::ShuffleVector) {
2358 if (Elts.size() != 3)
2359 return Error(ID.Loc, "expected three operands to shufflevector");
2360 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2361 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002362 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002363 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002364 } else if (Opc == Instruction::ExtractElement) {
2365 if (Elts.size() != 2)
2366 return Error(ID.Loc, "expected two operands to extractelement");
2367 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2368 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002369 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002370 } else {
2371 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2372 if (Elts.size() != 3)
2373 return Error(ID.Loc, "expected three operands to insertelement");
2374 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2375 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002376 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002379
Chris Lattnerdf986172009-01-02 07:01:27 +00002380 ID.Kind = ValID::t_Constant;
2381 return false;
2382 }
2383 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002384
Chris Lattnerdf986172009-01-02 07:01:27 +00002385 Lex.Lex();
2386 return false;
2387}
2388
2389/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002390bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002391 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002392 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002393 Value *V = NULL;
2394 bool Parsed = ParseValID(ID) ||
2395 ConvertValIDToValue(Ty, ID, V, NULL);
2396 if (V && !(C = dyn_cast<Constant>(V)))
2397 return Error(ID.Loc, "global values must be constants");
2398 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002399}
2400
Victor Hernandez92f238d2010-01-11 22:31:58 +00002401bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002402 Type *Ty = 0;
2403 return ParseType(Ty) ||
2404 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002405}
2406
2407/// ParseGlobalValueVector
2408/// ::= /*empty*/
2409/// ::= TypeAndValue (',' TypeAndValue)*
2410bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2411 // Empty list.
2412 if (Lex.getKind() == lltok::rbrace ||
2413 Lex.getKind() == lltok::rsquare ||
2414 Lex.getKind() == lltok::greater ||
2415 Lex.getKind() == lltok::rparen)
2416 return false;
2417
2418 Constant *C;
2419 if (ParseGlobalTypeAndValue(C)) return true;
2420 Elts.push_back(C);
2421
2422 while (EatIfPresent(lltok::comma)) {
2423 if (ParseGlobalTypeAndValue(C)) return true;
2424 Elts.push_back(C);
2425 }
2426
2427 return false;
2428}
2429
Dan Gohman309b3af2010-08-24 02:24:03 +00002430bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2431 assert(Lex.getKind() == lltok::lbrace);
2432 Lex.Lex();
2433
2434 SmallVector<Value*, 16> Elts;
2435 if (ParseMDNodeVector(Elts, PFS) ||
2436 ParseToken(lltok::rbrace, "expected end of metadata node"))
2437 return true;
2438
Jay Foadec9186b2011-04-21 19:59:31 +00002439 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002440 ID.Kind = ValID::t_MDNode;
2441 return false;
2442}
2443
Dan Gohman83448032010-07-14 18:26:50 +00002444/// ParseMetadataValue
2445/// ::= !42
2446/// ::= !{...}
2447/// ::= !"string"
2448bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2449 assert(Lex.getKind() == lltok::exclaim);
2450 Lex.Lex();
2451
2452 // MDNode:
2453 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002454 if (Lex.getKind() == lltok::lbrace)
2455 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002456
2457 // Standalone metadata reference
2458 // !42
2459 if (Lex.getKind() == lltok::APSInt) {
2460 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2461 ID.Kind = ValID::t_MDNode;
2462 return false;
2463 }
2464
2465 // MDString:
2466 // ::= '!' STRINGCONSTANT
2467 if (ParseMDString(ID.MDStringVal)) return true;
2468 ID.Kind = ValID::t_MDString;
2469 return false;
2470}
2471
Victor Hernandez92f238d2010-01-11 22:31:58 +00002472
2473//===----------------------------------------------------------------------===//
2474// Function Parsing.
2475//===----------------------------------------------------------------------===//
2476
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002477bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002478 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002479 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002480 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002481
Chris Lattnerdf986172009-01-02 07:01:27 +00002482 switch (ID.Kind) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002483 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002484 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2485 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2486 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002487 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002488 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2489 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2490 return (V == 0);
2491 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002492 PointerType *PTy = dyn_cast<PointerType>(Ty);
2493 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002494 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2495 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2496 return Error(ID.Loc, "invalid type for inline asm constraint string");
2497 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2498 return false;
2499 }
2500 case ValID::t_MDNode:
2501 if (!Ty->isMetadataTy())
2502 return Error(ID.Loc, "metadata value must have metadata type");
2503 V = ID.MDNodeVal;
2504 return false;
2505 case ValID::t_MDString:
2506 if (!Ty->isMetadataTy())
2507 return Error(ID.Loc, "metadata value must have metadata type");
2508 V = ID.MDStringVal;
2509 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 case ValID::t_GlobalName:
2511 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2512 return V == 0;
2513 case ValID::t_GlobalID:
2514 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2515 return V == 0;
2516 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002517 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002518 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002519 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002520 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 return false;
2522 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002523 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002524 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2525 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002526
Dan Gohmance163392011-12-17 00:04:22 +00002527 // The lexer has no type info, so builds all half, float, and double FP
2528 // constants as double. Fix this here. Long double does not need this.
2529 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002530 bool Ignored;
Dan Gohmance163392011-12-17 00:04:22 +00002531 if (Ty->isHalfTy())
2532 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2533 &Ignored);
2534 else if (Ty->isFloatTy())
2535 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2536 &Ignored);
Chris Lattnerdf986172009-01-02 07:01:27 +00002537 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002538 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002539
Chris Lattner959873d2009-01-05 18:24:23 +00002540 if (V->getType() != Ty)
2541 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002542 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002543
Chris Lattnerdf986172009-01-02 07:01:27 +00002544 return false;
2545 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002546 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002547 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002548 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002549 return false;
2550 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002551 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002552 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002553 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002554 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002555 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002556 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002557 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002558 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002559 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002560 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002561 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002562 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002563 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002564 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002565 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002566 return false;
2567 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002568 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002569 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002570
Chris Lattnerdf986172009-01-02 07:01:27 +00002571 V = ID.ConstantVal;
2572 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002573 case ValID::t_ConstantStruct:
2574 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002575 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002576 if (ST->getNumElements() != ID.UIntVal)
2577 return Error(ID.Loc,
2578 "initializer with struct type has wrong # elements");
2579 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2580 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2581
2582 // Verify that the elements are compatible with the structtype.
2583 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2584 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2585 return Error(ID.Loc, "element " + Twine(i) +
2586 " of struct initializer doesn't match struct element type");
2587
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002588 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2589 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002590 } else
2591 return Error(ID.Loc, "constant expression type mismatch");
2592 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002593 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00002594 llvm_unreachable("Invalid ValID");
Chris Lattnerdf986172009-01-02 07:01:27 +00002595}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002597bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002598 V = 0;
2599 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002600 return ParseValID(ID, PFS) ||
2601 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002602}
2603
Chris Lattner1afcace2011-07-09 17:41:24 +00002604bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2605 Type *Ty = 0;
2606 return ParseType(Ty) ||
2607 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002608}
2609
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002610bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2611 PerFunctionState &PFS) {
2612 Value *V;
2613 Loc = Lex.getLoc();
2614 if (ParseTypeAndValue(V, PFS)) return true;
2615 if (!isa<BasicBlock>(V))
2616 return Error(Loc, "expected a basic block");
2617 BB = cast<BasicBlock>(V);
2618 return false;
2619}
2620
2621
Chris Lattnerdf986172009-01-02 07:01:27 +00002622/// FunctionHeader
2623/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002624/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002625/// OptionalAlign OptGC
2626bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2627 // Parse the linkage.
2628 LocTy LinkageLoc = Lex.getLoc();
2629 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002630
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002631 unsigned Visibility;
2632 Attributes RetAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002633 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002634 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002635 LocTy RetTypeLoc = Lex.getLoc();
2636 if (ParseOptionalLinkage(Linkage) ||
2637 ParseOptionalVisibility(Visibility) ||
2638 ParseOptionalCallingConv(CC) ||
2639 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002640 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002641 return true;
2642
2643 // Verify that the linkage is ok.
2644 switch ((GlobalValue::LinkageTypes)Linkage) {
2645 case GlobalValue::ExternalLinkage:
2646 break; // always ok.
2647 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002648 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 if (isDefine)
2650 return Error(LinkageLoc, "invalid linkage for function definition");
2651 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002652 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002653 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002654 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002655 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002656 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002657 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002658 case GlobalValue::LinkOnceAnyLinkage:
2659 case GlobalValue::LinkOnceODRLinkage:
2660 case GlobalValue::WeakAnyLinkage:
2661 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002662 case GlobalValue::DLLExportLinkage:
2663 if (!isDefine)
2664 return Error(LinkageLoc, "invalid linkage for function declaration");
2665 break;
2666 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002667 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002668 return Error(LinkageLoc, "invalid function linkage type");
2669 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Chris Lattner1afcace2011-07-09 17:41:24 +00002671 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002672 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattnerdf986172009-01-02 07:01:27 +00002674 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002675
2676 std::string FunctionName;
2677 if (Lex.getKind() == lltok::GlobalVar) {
2678 FunctionName = Lex.getStrVal();
2679 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2680 unsigned NameID = Lex.getUIntVal();
2681
2682 if (NameID != NumberedVals.size())
2683 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002684 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002685 } else {
2686 return TokError("expected function name");
2687 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002689 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002691 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002692 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002693
Chris Lattner1afcace2011-07-09 17:41:24 +00002694 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002695 bool isVarArg;
Kostya Serebryany164b86b2012-01-20 17:56:17 +00002696 Attributes FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002697 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002698 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002699 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002700 bool UnnamedAddr;
2701 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002702
Chris Lattner1afcace2011-07-09 17:41:24 +00002703 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002704 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2705 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002706 ParseOptionalAttrs(FuncAttrs, 2) ||
2707 (EatIfPresent(lltok::kw_section) &&
2708 ParseStringConstant(Section)) ||
2709 ParseOptionalAlignment(Alignment) ||
2710 (EatIfPresent(lltok::kw_gc) &&
2711 ParseStringConstant(GC)))
2712 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002713
2714 // If the alignment was parsed as an attribute, move to the alignment field.
2715 if (FuncAttrs & Attribute::Alignment) {
2716 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2717 FuncAttrs &= ~Attribute::Alignment;
2718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnerdf986172009-01-02 07:01:27 +00002720 // Okay, if we got here, the function is syntactically valid. Convert types
2721 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002722 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002723 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnerdf986172009-01-02 07:01:27 +00002725 if (RetAttrs != Attribute::None)
2726 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Chris Lattnerdf986172009-01-02 07:01:27 +00002728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002729 ParamTypeList.push_back(ArgList[i].Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 if (ArgList[i].Attrs != Attribute::None)
2731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2732 }
2733
2734 if (FuncAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2736
Chris Lattnerd509d0b2012-05-28 01:47:44 +00002737 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Benjamin Kramerf0127052010-01-05 13:12:22 +00002739 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2741
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002742 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002743 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002744 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002745
2746 Fn = 0;
2747 if (!FunctionName.empty()) {
2748 // If this was a definition of a forward reference, remove the definition
2749 // from the forward reference table and fill in the forward ref.
2750 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2751 ForwardRefVals.find(FunctionName);
2752 if (FRVI != ForwardRefVals.end()) {
2753 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002754 if (Fn->getType() != PFT)
2755 return Error(FRVI->second.second, "invalid forward reference to "
2756 "function '" + FunctionName + "' with wrong type!");
2757
Chris Lattnerdf986172009-01-02 07:01:27 +00002758 ForwardRefVals.erase(FRVI);
2759 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002760 // Reject redefinitions.
2761 return Error(NameLoc, "invalid redefinition of function '" +
2762 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002763 } else if (M->getNamedValue(FunctionName)) {
2764 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002766
Dan Gohman41905542009-08-29 23:37:49 +00002767 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002768 // If this is a definition of a forward referenced function, make sure the
2769 // types agree.
2770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2771 = ForwardRefValIDs.find(NumberedVals.size());
2772 if (I != ForwardRefValIDs.end()) {
2773 Fn = cast<Function>(I->second.first);
2774 if (Fn->getType() != PFT)
2775 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002776 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002777 ForwardRefValIDs.erase(I);
2778 }
2779 }
2780
2781 if (Fn == 0)
2782 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2783 else // Move the forward-reference to the correct spot in the module.
2784 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2785
2786 if (FunctionName.empty())
2787 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2790 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2791 Fn->setCallingConv(CC);
2792 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002793 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002794 Fn->setAlignment(Alignment);
2795 Fn->setSection(Section);
2796 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerdf986172009-01-02 07:01:27 +00002798 // Add all of the arguments we parsed to the function.
2799 Function::arg_iterator ArgIt = Fn->arg_begin();
2800 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2801 // If the argument has a name, insert it into the argument symbol table.
2802 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002803
Chris Lattnerdf986172009-01-02 07:01:27 +00002804 // Set the name, if it conflicted, it will be auto-renamed.
2805 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Benjamin Krameraf812352010-10-16 11:28:23 +00002807 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002808 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2809 ArgList[i].Name + "'");
2810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 return false;
2813}
2814
2815
2816/// ParseFunctionBody
2817/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002818///
2819bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002820 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002821 return TokError("expected '{' in function body");
2822 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002823
Chris Lattner09d9ef42009-10-28 03:39:23 +00002824 int FunctionNumber = -1;
2825 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2826
2827 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002829 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002830 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002831 return TokError("function body requires at least one basic block");
2832
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002833 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002834 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002835
Chris Lattnerdf986172009-01-02 07:01:27 +00002836 // Eat the }.
2837 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002838
Chris Lattnerdf986172009-01-02 07:01:27 +00002839 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002840 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002841}
2842
2843/// ParseBasicBlock
2844/// ::= LabelStr? Instruction*
2845bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2846 // If this basic block starts out with a name, remember it.
2847 std::string Name;
2848 LocTy NameLoc = Lex.getLoc();
2849 if (Lex.getKind() == lltok::LabelStr) {
2850 Name = Lex.getStrVal();
2851 Lex.Lex();
2852 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002853
Chris Lattnerdf986172009-01-02 07:01:27 +00002854 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2855 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002856
Chris Lattnerdf986172009-01-02 07:01:27 +00002857 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002858
Chris Lattnerdf986172009-01-02 07:01:27 +00002859 // Parse the instructions in this block until we get a terminator.
2860 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002861 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002862 do {
2863 // This instruction may have three possibilities for a name: a) none
2864 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2865 LocTy NameLoc = Lex.getLoc();
2866 int NameID = -1;
2867 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Chris Lattnerdf986172009-01-02 07:01:27 +00002869 if (Lex.getKind() == lltok::LocalVarID) {
2870 NameID = Lex.getUIntVal();
2871 Lex.Lex();
2872 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2873 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002874 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002875 NameStr = Lex.getStrVal();
2876 Lex.Lex();
2877 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2878 return true;
2879 }
Devang Patelf633a062009-09-17 23:04:48 +00002880
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002881 switch (ParseInstruction(Inst, BB, PFS)) {
Craig Topper85814382012-02-07 05:05:23 +00002882 default: llvm_unreachable("Unknown ParseInstruction result!");
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002883 case InstError: return true;
2884 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002885 BB->getInstList().push_back(Inst);
2886
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002887 // With a normal result, we check to see if the instruction is followed by
2888 // a comma and metadata.
2889 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002890 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002891 return true;
2892 break;
2893 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002894 BB->getInstList().push_back(Inst);
2895
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002896 // If the instruction parser ate an extra comma at the end of it, it
2897 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002898 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002899 return true;
2900 break;
2901 }
Devang Patelf633a062009-09-17 23:04:48 +00002902
Chris Lattnerdf986172009-01-02 07:01:27 +00002903 // Set the name on the instruction.
2904 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2905 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002906
Chris Lattnerdf986172009-01-02 07:01:27 +00002907 return false;
2908}
2909
2910//===----------------------------------------------------------------------===//
2911// Instruction Parsing.
2912//===----------------------------------------------------------------------===//
2913
2914/// ParseInstruction - Parse one of the many different instructions.
2915///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002916int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2917 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002918 lltok::Kind Token = Lex.getKind();
2919 if (Token == lltok::Eof)
2920 return TokError("found end of file when expecting more instructions");
2921 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002922 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerdf986172009-01-02 07:01:27 +00002925 switch (Token) {
2926 default: return Error(Loc, "expected instruction opcode");
2927 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002928 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002929 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2930 case lltok::kw_br: return ParseBr(Inst, PFS);
2931 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002932 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002933 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002934 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002935 // Binary Operators.
2936 case lltok::kw_add:
2937 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002938 case lltok::kw_mul:
2939 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002940 bool NUW = EatIfPresent(lltok::kw_nuw);
2941 bool NSW = EatIfPresent(lltok::kw_nsw);
2942 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2943
2944 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2945
2946 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2947 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2948 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002949 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002950 case lltok::kw_fadd:
2951 case lltok::kw_fsub:
2952 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2953
Chris Lattner35bda892011-02-06 21:44:57 +00002954 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002955 case lltok::kw_udiv:
2956 case lltok::kw_lshr:
2957 case lltok::kw_ashr: {
2958 bool Exact = EatIfPresent(lltok::kw_exact);
2959
2960 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2961 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2962 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002963 }
2964
Chris Lattnerdf986172009-01-02 07:01:27 +00002965 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002966 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002967 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002968 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 case lltok::kw_and:
2970 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002971 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002972 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002973 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002974 // Casts.
2975 case lltok::kw_trunc:
2976 case lltok::kw_zext:
2977 case lltok::kw_sext:
2978 case lltok::kw_fptrunc:
2979 case lltok::kw_fpext:
2980 case lltok::kw_bitcast:
2981 case lltok::kw_uitofp:
2982 case lltok::kw_sitofp:
2983 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002985 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002986 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002987 // Other.
2988 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002989 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002990 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2991 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2992 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2993 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002994 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002995 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2996 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2997 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002998 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerfbe910e2011-11-27 06:56:53 +00002999 case lltok::kw_load: return ParseLoad(Inst, PFS);
3000 case lltok::kw_store: return ParseStore(Inst, PFS);
Eli Friedmanf03bb262011-08-12 22:50:01 +00003001 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3002 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
Eli Friedman47f35132011-07-25 23:16:38 +00003003 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003004 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3005 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3006 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3007 }
3008}
3009
3010/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3011bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003012 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003013 switch (Lex.getKind()) {
3014 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3015 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3016 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3017 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3018 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3019 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3020 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3021 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3022 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3023 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3024 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3025 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3026 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3027 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3028 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3029 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3030 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3031 }
3032 } else {
3033 switch (Lex.getKind()) {
3034 default: TokError("expected icmp predicate (e.g. 'eq')");
3035 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3036 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3037 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3038 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3039 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3040 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3041 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3042 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3043 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3044 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3045 }
3046 }
3047 Lex.Lex();
3048 return false;
3049}
3050
3051//===----------------------------------------------------------------------===//
3052// Terminator Instructions.
3053//===----------------------------------------------------------------------===//
3054
3055/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003056/// ::= 'ret' void (',' !dbg, !1)*
3057/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003058bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003059 PerFunctionState &PFS) {
3060 SMLoc TypeLoc = Lex.getLoc();
3061 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003062 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003063
Chris Lattner1afcace2011-07-09 17:41:24 +00003064 Type *ResType = PFS.getFunction().getReturnType();
3065
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003066 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003067 if (!ResType->isVoidTy())
3068 return Error(TypeLoc, "value doesn't match function result type '" +
3069 getTypeString(ResType) + "'");
3070
Owen Anderson1d0be152009-08-13 21:58:54 +00003071 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003072 return false;
3073 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003074
Chris Lattnerdf986172009-01-02 07:01:27 +00003075 Value *RV;
3076 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003077
Chris Lattner1afcace2011-07-09 17:41:24 +00003078 if (ResType != RV->getType())
3079 return Error(TypeLoc, "value doesn't match function result type '" +
3080 getTypeString(ResType) + "'");
3081
Owen Anderson1d0be152009-08-13 21:58:54 +00003082 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003083 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003084}
3085
3086
3087/// ParseBr
3088/// ::= 'br' TypeAndValue
3089/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3090bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3091 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003092 Value *Op0;
3093 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003094 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003095
Chris Lattnerdf986172009-01-02 07:01:27 +00003096 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3097 Inst = BranchInst::Create(BB);
3098 return false;
3099 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003100
Owen Anderson1d0be152009-08-13 21:58:54 +00003101 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003102 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003105 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003106 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003107 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003108 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003109
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003110 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003111 return false;
3112}
3113
3114/// ParseSwitch
3115/// Instruction
3116/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3117/// JumpTable
3118/// ::= (TypeAndValue ',' TypeAndValue)*
3119bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3120 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003121 Value *Cond;
3122 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003123 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3124 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003125 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003126 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3127 return true;
3128
Duncan Sands1df98592010-02-16 11:11:14 +00003129 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003130 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003131
Chris Lattnerdf986172009-01-02 07:01:27 +00003132 // Parse the jump table pairs.
3133 SmallPtrSet<Value*, 32> SeenCases;
3134 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3135 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003136 Value *Constant;
3137 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003138
Chris Lattnerdf986172009-01-02 07:01:27 +00003139 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3140 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003141 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003142 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003143
Chris Lattnerdf986172009-01-02 07:01:27 +00003144 if (!SeenCases.insert(Constant))
3145 return Error(CondLoc, "duplicate case value in switch");
3146 if (!isa<ConstantInt>(Constant))
3147 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003148
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003149 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003151
Chris Lattnerdf986172009-01-02 07:01:27 +00003152 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003153
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003154 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003155 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3156 SI->addCase(Table[i].first, Table[i].second);
3157 Inst = SI;
3158 return false;
3159}
3160
Chris Lattnerab21db72009-10-28 00:19:10 +00003161/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003162/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003163/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3164bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003165 LocTy AddrLoc;
3166 Value *Address;
3167 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003168 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3169 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003170 return true;
3171
Duncan Sands1df98592010-02-16 11:11:14 +00003172 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003173 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003174
3175 // Parse the destination list.
3176 SmallVector<BasicBlock*, 16> DestList;
3177
3178 if (Lex.getKind() != lltok::rsquare) {
3179 BasicBlock *DestBB;
3180 if (ParseTypeAndBasicBlock(DestBB, PFS))
3181 return true;
3182 DestList.push_back(DestBB);
3183
3184 while (EatIfPresent(lltok::comma)) {
3185 if (ParseTypeAndBasicBlock(DestBB, PFS))
3186 return true;
3187 DestList.push_back(DestBB);
3188 }
3189 }
3190
3191 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3192 return true;
3193
Chris Lattnerab21db72009-10-28 00:19:10 +00003194 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003195 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3196 IBI->addDestination(DestList[i]);
3197 Inst = IBI;
3198 return false;
3199}
3200
3201
Chris Lattnerdf986172009-01-02 07:01:27 +00003202/// ParseInvoke
3203/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3204/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3205bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3206 LocTy CallLoc = Lex.getLoc();
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003207 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003208 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003209 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003210 LocTy RetTypeLoc;
3211 ValID CalleeID;
3212 SmallVector<ParamInfo, 16> ArgList;
3213
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003214 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 if (ParseOptionalCallingConv(CC) ||
3216 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003217 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003218 ParseValID(CalleeID) ||
3219 ParseParameterList(ArgList, PFS) ||
3220 ParseOptionalAttrs(FnAttrs, 2) ||
3221 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003222 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003223 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003224 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003225 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003226
Chris Lattnerdf986172009-01-02 07:01:27 +00003227 // If RetType is a non-function pointer type, then this is the short syntax
3228 // for the call, which means that RetType is just the return type. Infer the
3229 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003230 PointerType *PFTy = 0;
3231 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003232 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3233 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3234 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003235 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003236 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3237 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003238
Chris Lattnerdf986172009-01-02 07:01:27 +00003239 if (!FunctionType::isValidReturnType(RetType))
3240 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Owen Andersondebcb012009-07-29 22:17:13 +00003242 Ty = FunctionType::get(RetType, ParamTypes, false);
3243 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003244 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003245
Chris Lattnerdf986172009-01-02 07:01:27 +00003246 // Look up the callee.
3247 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003248 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Chris Lattnerdf986172009-01-02 07:01:27 +00003250 // Set up the Attributes for the function.
3251 SmallVector<AttributeWithIndex, 8> Attrs;
3252 if (RetAttrs != Attribute::None)
3253 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003254
Chris Lattnerdf986172009-01-02 07:01:27 +00003255 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Chris Lattnerdf986172009-01-02 07:01:27 +00003257 // Loop through FunctionType's arguments and ensure they are specified
3258 // correctly. Also, gather any parameter attributes.
3259 FunctionType::param_iterator I = Ty->param_begin();
3260 FunctionType::param_iterator E = Ty->param_end();
3261 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003262 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003263 if (I != E) {
3264 ExpectedTy = *I++;
3265 } else if (!Ty->isVarArg()) {
3266 return Error(ArgList[i].Loc, "too many arguments specified");
3267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003268
Chris Lattnerdf986172009-01-02 07:01:27 +00003269 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3270 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003271 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003272 Args.push_back(ArgList[i].V);
3273 if (ArgList[i].Attrs != Attribute::None)
3274 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3275 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003276
Chris Lattnerdf986172009-01-02 07:01:27 +00003277 if (I != E)
3278 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003279
Chris Lattnerdf986172009-01-02 07:01:27 +00003280 if (FnAttrs != Attribute::None)
3281 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003282
Chris Lattnerdf986172009-01-02 07:01:27 +00003283 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003284 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003285
Jay Foada3efbb12011-07-15 08:37:34 +00003286 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003287 II->setCallingConv(CC);
3288 II->setAttributes(PAL);
3289 Inst = II;
3290 return false;
3291}
3292
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003293/// ParseResume
3294/// ::= 'resume' TypeAndValue
3295bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3296 Value *Exn; LocTy ExnLoc;
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003297 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3298 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003299
Bill Wendlingdccc03b2011-07-31 06:30:59 +00003300 ResumeInst *RI = ResumeInst::Create(Exn);
3301 Inst = RI;
3302 return false;
3303}
Chris Lattnerdf986172009-01-02 07:01:27 +00003304
3305//===----------------------------------------------------------------------===//
3306// Binary Operators.
3307//===----------------------------------------------------------------------===//
3308
3309/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003310/// ::= ArithmeticOps TypeAndValue ',' Value
3311///
3312/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3313/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003314bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003315 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003316 LocTy Loc; Value *LHS, *RHS;
3317 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3318 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3319 ParseValue(LHS->getType(), RHS, PFS))
3320 return true;
3321
Chris Lattnere914b592009-01-05 08:24:46 +00003322 bool Valid;
3323 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003324 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003325 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003326 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3327 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003328 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003329 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3330 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003332
Chris Lattnere914b592009-01-05 08:24:46 +00003333 if (!Valid)
3334 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003335
Chris Lattnerdf986172009-01-02 07:01:27 +00003336 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3337 return false;
3338}
3339
3340/// ParseLogical
3341/// ::= ArithmeticOps TypeAndValue ',' Value {
3342bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3343 unsigned Opc) {
3344 LocTy Loc; Value *LHS, *RHS;
3345 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3346 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3347 ParseValue(LHS->getType(), RHS, PFS))
3348 return true;
3349
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003350 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003351 return Error(Loc,"instruction requires integer or integer vector operands");
3352
3353 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3354 return false;
3355}
3356
3357
3358/// ParseCompare
3359/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3360/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003361bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3362 unsigned Opc) {
3363 // Parse the integer/fp comparison predicate.
3364 LocTy Loc;
3365 unsigned Pred;
3366 Value *LHS, *RHS;
3367 if (ParseCmpPredicate(Pred, Opc) ||
3368 ParseTypeAndValue(LHS, Loc, PFS) ||
3369 ParseToken(lltok::comma, "expected ',' after compare value") ||
3370 ParseValue(LHS->getType(), RHS, PFS))
3371 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003372
Chris Lattnerdf986172009-01-02 07:01:27 +00003373 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003374 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003375 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003376 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003377 } else {
3378 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003379 if (!LHS->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00003380 !LHS->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003381 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003382 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003383 }
3384 return false;
3385}
3386
3387//===----------------------------------------------------------------------===//
3388// Other Instructions.
3389//===----------------------------------------------------------------------===//
3390
3391
3392/// ParseCast
3393/// ::= CastOpc TypeAndValue 'to' Type
3394bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3395 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003396 LocTy Loc;
3397 Value *Op;
3398 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003399 if (ParseTypeAndValue(Op, Loc, PFS) ||
3400 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3401 ParseType(DestTy))
3402 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003403
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003404 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3405 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003406 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003407 getTypeString(Op->getType()) + "' to '" +
3408 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003409 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003410 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3411 return false;
3412}
3413
3414/// ParseSelect
3415/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3416bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3417 LocTy Loc;
3418 Value *Op0, *Op1, *Op2;
3419 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after select condition") ||
3421 ParseTypeAndValue(Op1, PFS) ||
3422 ParseToken(lltok::comma, "expected ',' after select value") ||
3423 ParseTypeAndValue(Op2, PFS))
3424 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003425
Chris Lattnerdf986172009-01-02 07:01:27 +00003426 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3427 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003428
Chris Lattnerdf986172009-01-02 07:01:27 +00003429 Inst = SelectInst::Create(Op0, Op1, Op2);
3430 return false;
3431}
3432
Chris Lattner0088a5c2009-01-05 08:18:44 +00003433/// ParseVA_Arg
3434/// ::= 'va_arg' TypeAndValue ',' Type
3435bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003436 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003437 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003438 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003439 if (ParseTypeAndValue(Op, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003441 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003442 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003443
Chris Lattner0088a5c2009-01-05 08:18:44 +00003444 if (!EltTy->isFirstClassType())
3445 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003446
3447 Inst = new VAArgInst(Op, EltTy);
3448 return false;
3449}
3450
3451/// ParseExtractElement
3452/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3453bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3454 LocTy Loc;
3455 Value *Op0, *Op1;
3456 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3457 ParseToken(lltok::comma, "expected ',' after extract value") ||
3458 ParseTypeAndValue(Op1, PFS))
3459 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003460
Chris Lattnerdf986172009-01-02 07:01:27 +00003461 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3462 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003463
Eric Christophera3500da2009-07-25 02:28:41 +00003464 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003465 return false;
3466}
3467
3468/// ParseInsertElement
3469/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3470bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3471 LocTy Loc;
3472 Value *Op0, *Op1, *Op2;
3473 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3474 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3475 ParseTypeAndValue(Op1, PFS) ||
3476 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3477 ParseTypeAndValue(Op2, PFS))
3478 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003479
Chris Lattnerdf986172009-01-02 07:01:27 +00003480 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003481 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003482
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3484 return false;
3485}
3486
3487/// ParseShuffleVector
3488/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3489bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3490 LocTy Loc;
3491 Value *Op0, *Op1, *Op2;
3492 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3493 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3494 ParseTypeAndValue(Op1, PFS) ||
3495 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3496 ParseTypeAndValue(Op2, PFS))
3497 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003498
Chris Lattnerdf986172009-01-02 07:01:27 +00003499 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
Pete Cooperaf393682012-02-01 23:43:12 +00003500 return Error(Loc, "invalid shufflevector operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003501
Chris Lattnerdf986172009-01-02 07:01:27 +00003502 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3503 return false;
3504}
3505
3506/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003507/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003508int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003509 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003510 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003511
Chris Lattner1afcace2011-07-09 17:41:24 +00003512 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003513 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3514 ParseValue(Ty, Op0, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003516 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003517 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3518 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003519
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003520 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003521 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3522 while (1) {
3523 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003524
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003525 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003526 break;
3527
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003528 if (Lex.getKind() == lltok::MetadataVar) {
3529 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003530 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003531 }
Devang Patela43d46f2009-10-16 18:45:49 +00003532
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003533 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003534 ParseValue(Ty, Op0, PFS) ||
3535 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003536 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003537 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3538 return true;
3539 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003540
Chris Lattnerdf986172009-01-02 07:01:27 +00003541 if (!Ty->isFirstClassType())
3542 return Error(TypeLoc, "phi node must have first class type");
3543
Jay Foad3ecfc862011-03-30 11:28:46 +00003544 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003545 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3546 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3547 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003548 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003549}
3550
Bill Wendlinge6e88262011-08-12 20:24:12 +00003551/// ParseLandingPad
3552/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3553/// Clause
3554/// ::= 'catch' TypeAndValue
3555/// ::= 'filter'
3556/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3557bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3558 Type *Ty = 0; LocTy TyLoc;
3559 Value *PersFn; LocTy PersFnLoc;
Bill Wendlinge6e88262011-08-12 20:24:12 +00003560
3561 if (ParseType(Ty, TyLoc) ||
3562 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3563 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3564 return true;
3565
3566 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3567 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3568
3569 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3570 LandingPadInst::ClauseType CT;
3571 if (EatIfPresent(lltok::kw_catch))
3572 CT = LandingPadInst::Catch;
3573 else if (EatIfPresent(lltok::kw_filter))
3574 CT = LandingPadInst::Filter;
3575 else
3576 return TokError("expected 'catch' or 'filter' clause type");
3577
3578 Value *V; LocTy VLoc;
3579 if (ParseTypeAndValue(V, VLoc, PFS)) {
3580 delete LP;
3581 return true;
3582 }
3583
Bill Wendling746c8822011-08-12 20:52:25 +00003584 // A 'catch' type expects a non-array constant. A filter clause expects an
3585 // array constant.
3586 if (CT == LandingPadInst::Catch) {
3587 if (isa<ArrayType>(V->getType()))
3588 Error(VLoc, "'catch' clause has an invalid type");
3589 } else {
3590 if (!isa<ArrayType>(V->getType()))
3591 Error(VLoc, "'filter' clause has an invalid type");
3592 }
3593
Bill Wendlinge6e88262011-08-12 20:24:12 +00003594 LP->addClause(V);
3595 }
3596
3597 Inst = LP;
3598 return false;
3599}
3600
Chris Lattnerdf986172009-01-02 07:01:27 +00003601/// ParseCall
3602/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3603/// ParameterList OptionalAttrs
3604bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3605 bool isTail) {
Kostya Serebryany164b86b2012-01-20 17:56:17 +00003606 Attributes RetAttrs, FnAttrs;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003607 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003608 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003609 LocTy RetTypeLoc;
3610 ValID CalleeID;
3611 SmallVector<ParamInfo, 16> ArgList;
3612 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003613
Chris Lattnerdf986172009-01-02 07:01:27 +00003614 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3615 ParseOptionalCallingConv(CC) ||
3616 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003617 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003618 ParseValID(CalleeID) ||
3619 ParseParameterList(ArgList, PFS) ||
3620 ParseOptionalAttrs(FnAttrs, 2))
3621 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003622
Chris Lattnerdf986172009-01-02 07:01:27 +00003623 // If RetType is a non-function pointer type, then this is the short syntax
3624 // for the call, which means that RetType is just the return type. Infer the
3625 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003626 PointerType *PFTy = 0;
3627 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003628 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3629 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3630 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003631 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003632 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3633 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003634
Chris Lattnerdf986172009-01-02 07:01:27 +00003635 if (!FunctionType::isValidReturnType(RetType))
3636 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003637
Owen Andersondebcb012009-07-29 22:17:13 +00003638 Ty = FunctionType::get(RetType, ParamTypes, false);
3639 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003641
Chris Lattnerdf986172009-01-02 07:01:27 +00003642 // Look up the callee.
3643 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003644 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003645
Chris Lattnerdf986172009-01-02 07:01:27 +00003646 // Set up the Attributes for the function.
3647 SmallVector<AttributeWithIndex, 8> Attrs;
3648 if (RetAttrs != Attribute::None)
3649 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003650
Chris Lattnerdf986172009-01-02 07:01:27 +00003651 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003652
Chris Lattnerdf986172009-01-02 07:01:27 +00003653 // Loop through FunctionType's arguments and ensure they are specified
3654 // correctly. Also, gather any parameter attributes.
3655 FunctionType::param_iterator I = Ty->param_begin();
3656 FunctionType::param_iterator E = Ty->param_end();
3657 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003658 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003659 if (I != E) {
3660 ExpectedTy = *I++;
3661 } else if (!Ty->isVarArg()) {
3662 return Error(ArgList[i].Loc, "too many arguments specified");
3663 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003664
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3666 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003667 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003668 Args.push_back(ArgList[i].V);
3669 if (ArgList[i].Attrs != Attribute::None)
3670 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3671 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003672
Chris Lattnerdf986172009-01-02 07:01:27 +00003673 if (I != E)
3674 return Error(CallLoc, "not enough parameters specified for call");
3675
3676 if (FnAttrs != Attribute::None)
3677 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3678
3679 // Finish off the Attributes and check them
Chris Lattnerd509d0b2012-05-28 01:47:44 +00003680 AttrListPtr PAL = AttrListPtr::get(Attrs);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003681
Jay Foada3efbb12011-07-15 08:37:34 +00003682 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003683 CI->setTailCall(isTail);
3684 CI->setCallingConv(CC);
3685 CI->setAttributes(PAL);
3686 Inst = CI;
3687 return false;
3688}
3689
3690//===----------------------------------------------------------------------===//
3691// Memory Instructions.
3692//===----------------------------------------------------------------------===//
3693
3694/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003695/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003696int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003697 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003698 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003699 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003700 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003701 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003702
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003703 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003704 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003705 if (Lex.getKind() == lltok::kw_align) {
3706 if (ParseOptionalAlignment(Alignment)) return true;
3707 } else if (Lex.getKind() == lltok::MetadataVar) {
3708 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003709 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003710 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3711 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3712 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003713 }
3714 }
3715
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003716 if (Size && !Size->getType()->isIntegerTy())
3717 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003718
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003719 Inst = new AllocaInst(Ty, Size, Alignment);
3720 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003721}
3722
3723/// ParseLoad
Eli Friedmanf03bb262011-08-12 22:50:01 +00003724/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3725/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3726/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003727int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003728 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003729 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003730 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003731 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003732 AtomicOrdering Ordering = NotAtomic;
3733 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003734
3735 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003736 isAtomic = true;
3737 Lex.Lex();
3738 }
3739
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003740 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003741 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003742 isVolatile = true;
3743 Lex.Lex();
3744 }
3745
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003746 if (ParseTypeAndValue(Val, Loc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003747 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003748 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3749 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003750
Duncan Sands1df98592010-02-16 11:11:14 +00003751 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003752 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3753 return Error(Loc, "load operand must be a pointer to a first class type");
Eli Friedman21006d42011-08-09 23:02:53 +00003754 if (isAtomic && !Alignment)
3755 return Error(Loc, "atomic load must have explicit non-zero alignment");
3756 if (Ordering == Release || Ordering == AcquireRelease)
3757 return Error(Loc, "atomic load cannot use Release ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003758
Eli Friedman21006d42011-08-09 23:02:53 +00003759 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003760 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003761}
3762
3763/// ParseStore
Eli Friedmanf03bb262011-08-12 22:50:01 +00003764
3765/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3766/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
Eli Friedman21006d42011-08-09 23:02:53 +00003767/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003768int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003769 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003770 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003771 bool AteExtraComma = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003772 bool isAtomic = false;
Eli Friedman21006d42011-08-09 23:02:53 +00003773 AtomicOrdering Ordering = NotAtomic;
3774 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003775
3776 if (Lex.getKind() == lltok::kw_atomic) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003777 isAtomic = true;
3778 Lex.Lex();
3779 }
3780
Chris Lattnerfbe910e2011-11-27 06:56:53 +00003781 bool isVolatile = false;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003782 if (Lex.getKind() == lltok::kw_volatile) {
Eli Friedmanf03bb262011-08-12 22:50:01 +00003783 isVolatile = true;
3784 Lex.Lex();
3785 }
3786
Chris Lattnerdf986172009-01-02 07:01:27 +00003787 if (ParseTypeAndValue(Val, Loc, PFS) ||
3788 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003789 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
Eli Friedman21006d42011-08-09 23:02:53 +00003790 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003791 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003792 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003793
Duncan Sands1df98592010-02-16 11:11:14 +00003794 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003795 return Error(PtrLoc, "store operand must be a pointer");
3796 if (!Val->getType()->isFirstClassType())
3797 return Error(Loc, "store operand must be a first class value");
3798 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3799 return Error(Loc, "stored value and pointer type do not match");
Eli Friedman21006d42011-08-09 23:02:53 +00003800 if (isAtomic && !Alignment)
3801 return Error(Loc, "atomic store must have explicit non-zero alignment");
3802 if (Ordering == Acquire || Ordering == AcquireRelease)
3803 return Error(Loc, "atomic store cannot use Acquire ordering");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003804
Eli Friedman21006d42011-08-09 23:02:53 +00003805 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003806 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003807}
3808
Eli Friedmanff030482011-07-28 21:48:00 +00003809/// ParseCmpXchg
Eli Friedmanf03bb262011-08-12 22:50:01 +00003810/// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3811/// 'singlethread'? AtomicOrdering
3812int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003813 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3814 bool AteExtraComma = false;
3815 AtomicOrdering Ordering = NotAtomic;
3816 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003817 bool isVolatile = false;
3818
3819 if (EatIfPresent(lltok::kw_volatile))
3820 isVolatile = true;
3821
Eli Friedmanff030482011-07-28 21:48:00 +00003822 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3823 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3824 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3825 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3826 ParseTypeAndValue(New, NewLoc, PFS) ||
3827 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3828 return true;
3829
3830 if (Ordering == Unordered)
3831 return TokError("cmpxchg cannot be unordered");
3832 if (!Ptr->getType()->isPointerTy())
3833 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3834 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3835 return Error(CmpLoc, "compare value and pointer type do not match");
3836 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3837 return Error(NewLoc, "new value and pointer type do not match");
3838 if (!New->getType()->isIntegerTy())
3839 return Error(NewLoc, "cmpxchg operand must be an integer");
3840 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3841 if (Size < 8 || (Size & (Size - 1)))
3842 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3843 " integer");
3844
3845 AtomicCmpXchgInst *CXI =
3846 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3847 CXI->setVolatile(isVolatile);
3848 Inst = CXI;
3849 return AteExtraComma ? InstExtraComma : InstNormal;
3850}
3851
3852/// ParseAtomicRMW
Eli Friedmanf03bb262011-08-12 22:50:01 +00003853/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3854/// 'singlethread'? AtomicOrdering
3855int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
Eli Friedmanff030482011-07-28 21:48:00 +00003856 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3857 bool AteExtraComma = false;
3858 AtomicOrdering Ordering = NotAtomic;
3859 SynchronizationScope Scope = CrossThread;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003860 bool isVolatile = false;
Eli Friedmanff030482011-07-28 21:48:00 +00003861 AtomicRMWInst::BinOp Operation;
Eli Friedmanf03bb262011-08-12 22:50:01 +00003862
3863 if (EatIfPresent(lltok::kw_volatile))
3864 isVolatile = true;
3865
Eli Friedmanff030482011-07-28 21:48:00 +00003866 switch (Lex.getKind()) {
3867 default: return TokError("expected binary operation in atomicrmw");
3868 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3869 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3870 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3871 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3872 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3873 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3874 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3875 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3876 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3877 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3878 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3879 }
3880 Lex.Lex(); // Eat the operation.
3881
3882 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3883 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3884 ParseTypeAndValue(Val, ValLoc, PFS) ||
3885 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3886 return true;
3887
3888 if (Ordering == Unordered)
3889 return TokError("atomicrmw cannot be unordered");
3890 if (!Ptr->getType()->isPointerTy())
3891 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3892 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3893 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3894 if (!Val->getType()->isIntegerTy())
3895 return Error(ValLoc, "atomicrmw operand must be an integer");
3896 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3897 if (Size < 8 || (Size & (Size - 1)))
3898 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3899 " integer");
3900
3901 AtomicRMWInst *RMWI =
3902 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3903 RMWI->setVolatile(isVolatile);
3904 Inst = RMWI;
3905 return AteExtraComma ? InstExtraComma : InstNormal;
3906}
3907
Eli Friedman47f35132011-07-25 23:16:38 +00003908/// ParseFence
3909/// ::= 'fence' 'singlethread'? AtomicOrdering
3910int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3911 AtomicOrdering Ordering = NotAtomic;
3912 SynchronizationScope Scope = CrossThread;
3913 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3914 return true;
3915
3916 if (Ordering == Unordered)
3917 return TokError("fence cannot be unordered");
3918 if (Ordering == Monotonic)
3919 return TokError("fence cannot be monotonic");
3920
3921 Inst = new FenceInst(Context, Ordering, Scope);
3922 return InstNormal;
3923}
3924
Chris Lattnerdf986172009-01-02 07:01:27 +00003925/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003926/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003927int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Nadav Rotem16087692011-12-05 06:29:09 +00003928 Value *Ptr = 0;
3929 Value *Val = 0;
3930 LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003931
Dan Gohmandcb40a32009-07-29 15:58:36 +00003932 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003933
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003934 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003935
Nadav Rotem16087692011-12-05 06:29:09 +00003936 if (!Ptr->getType()->getScalarType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003937 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003938
Chris Lattnerdf986172009-01-02 07:01:27 +00003939 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003940 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003941 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003942 if (Lex.getKind() == lltok::MetadataVar) {
3943 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003944 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003945 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003946 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Nadav Rotem16087692011-12-05 06:29:09 +00003947 if (!Val->getType()->getScalarType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003948 return Error(EltLoc, "getelementptr index must be an integer");
Nadav Rotem16087692011-12-05 06:29:09 +00003949 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
3950 return Error(EltLoc, "getelementptr index type missmatch");
3951 if (Val->getType()->isVectorTy()) {
3952 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
3953 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
3954 if (ValNumEl != PtrNumEl)
3955 return Error(EltLoc,
3956 "getelementptr vector index has a wrong number of elements");
3957 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003958 Indices.push_back(Val);
3959 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003960
Nadav Rotem16087692011-12-05 06:29:09 +00003961 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
3962 return Error(EltLoc, "vector getelementptrs must have a single index");
3963
Jay Foada9203102011-07-25 09:48:08 +00003964 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003965 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00003966 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003967 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003968 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003969 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003970}
3971
3972/// ParseExtractValue
3973/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003974int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003975 Value *Val; LocTy Loc;
3976 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003977 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003978 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003979 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003980 return true;
3981
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003982 if (!Val->getType()->isAggregateType())
3983 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003984
Jay Foadfc6d3a42011-07-13 10:26:04 +00003985 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003986 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003987 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003988 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003989}
3990
3991/// ParseInsertValue
3992/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003993int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003994 Value *Val0, *Val1; LocTy Loc0, Loc1;
3995 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003996 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003997 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3998 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3999 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004000 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00004001 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00004002
Chris Lattnerfdfeb692010-02-12 20:49:41 +00004003 if (!Val0->getType()->isAggregateType())
4004 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00004005
Jay Foadfc6d3a42011-07-13 10:26:04 +00004006 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00004007 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00004008 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00004009 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00004010}
Nick Lewycky21cc4462009-04-04 07:22:01 +00004011
4012//===----------------------------------------------------------------------===//
4013// Embedded metadata.
4014//===----------------------------------------------------------------------===//
4015
4016/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00004017/// ::= Element (',' Element)*
4018/// Element
4019/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00004020bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00004021 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00004022 // Check for an empty list.
4023 if (Lex.getKind() == lltok::rbrace)
4024 return false;
4025
Nick Lewycky21cc4462009-04-04 07:22:01 +00004026 do {
Chris Lattnera7352392009-12-30 04:42:57 +00004027 // Null is a special case since it is typeless.
4028 if (EatIfPresent(lltok::kw_null)) {
4029 Elts.push_back(0);
4030 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00004031 }
Chris Lattnera7352392009-12-30 04:42:57 +00004032
4033 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00004034 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00004035 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00004036 } while (EatIfPresent(lltok::comma));
4037
4038 return false;
4039}