blob: f412c1c89aa66745048f0ae9b9b863304111628c [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
Devang Patele4b27562009-08-28 23:24:31 +0000123 // Check debug info intrinsics.
124 CheckDebugInfoIntrinsics(M);
Chris Lattnerdf986172009-01-02 07:01:27 +0000125 return false;
126}
127
Chris Lattner09d9ef42009-10-28 03:39:23 +0000128bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
129 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
130 PerFunctionState *PFS) {
131 // Loop over all the references, resolving them.
132 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 BasicBlock *Res;
Chris Lattnercdfc9402009-11-01 01:27:45 +0000134 if (PFS) {
Chris Lattner09d9ef42009-10-28 03:39:23 +0000135 if (Refs[i].first.Kind == ValID::t_LocalName)
136 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
Chris Lattnercdfc9402009-11-01 01:27:45 +0000137 else
Chris Lattner09d9ef42009-10-28 03:39:23 +0000138 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
139 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
140 return Error(Refs[i].first.Loc,
Chris Lattneree7644d2009-11-02 18:28:45 +0000141 "cannot take address of numeric label after the function is defined");
Chris Lattner09d9ef42009-10-28 03:39:23 +0000142 } else {
143 Res = dyn_cast_or_null<BasicBlock>(
144 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
145 }
146
Chris Lattnercdfc9402009-11-01 01:27:45 +0000147 if (Res == 0)
Chris Lattner09d9ef42009-10-28 03:39:23 +0000148 return Error(Refs[i].first.Loc,
149 "referenced value is not a basic block");
150
151 // Get the BlockAddress for this and update references to use it.
152 BlockAddress *BA = BlockAddress::get(TheFn, Res);
153 Refs[i].second->replaceAllUsesWith(BA);
154 Refs[i].second->eraseFromParent();
155 }
156 return false;
157}
158
159
Chris Lattnerdf986172009-01-02 07:01:27 +0000160//===----------------------------------------------------------------------===//
161// Top-Level Entities
162//===----------------------------------------------------------------------===//
163
164bool LLParser::ParseTopLevelEntities() {
Chris Lattnerdf986172009-01-02 07:01:27 +0000165 while (1) {
166 switch (Lex.getKind()) {
167 default: return TokError("expected top-level entity");
168 case lltok::Eof: return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000169 case lltok::kw_declare: if (ParseDeclare()) return true; break;
170 case lltok::kw_define: if (ParseDefine()) return true; break;
171 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
172 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
173 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000174 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
Dan Gohman3845e502009-08-12 23:32:33 +0000176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
Chris Lattnere434d272009-12-30 04:56:59 +0000178 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
Chris Lattner1d928312009-12-30 05:02:06 +0000179 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000180
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000184 // OptionalAddrSpace OptionalUnNammedAddr
185 // ('constant'|'global') ...
Bill Wendling5e721d72010-07-01 21:55:59 +0000186 case lltok::kw_private: // OptionalLinkage
187 case lltok::kw_linker_private: // OptionalLinkage
188 case lltok::kw_linker_private_weak: // OptionalLinkage
Bill Wendling55ae5152010-08-20 22:05:50 +0000189 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
Bill Wendling5e721d72010-07-01 21:55:59 +0000190 case lltok::kw_internal: // OptionalLinkage
191 case lltok::kw_weak: // OptionalLinkage
192 case lltok::kw_weak_odr: // OptionalLinkage
193 case lltok::kw_linkonce: // OptionalLinkage
194 case lltok::kw_linkonce_odr: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
Chris Lattnerdf986172009-01-02 07:01:27 +0000201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000205 return true;
206 break;
207 }
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
211 unsigned Visibility;
212 if (ParseOptionalVisibility(Visibility) ||
Chris Lattnereeb4a842009-07-02 23:08:13 +0000213 ParseGlobal("", SMLoc(), 0, false, Visibility))
Chris Lattnerdf986172009-01-02 07:01:27 +0000214 return true;
215 break;
216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
Chris Lattnerdf986172009-01-02 07:01:27 +0000218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
Chris Lattnereeb4a842009-07-02 23:08:13 +0000222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000223 break;
224 }
225 }
226}
227
228
229/// toplevelentity
230/// ::= 'module' 'asm' STRINGCONSTANT
231bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
233 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
235 std::string AsmStr;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000238
Rafael Espindola38c4e532011-03-02 04:14:42 +0000239 M->appendModuleInlineAsm(AsmStr);
Chris Lattnerdf986172009-01-02 07:01:27 +0000240 return false;
241}
242
243/// toplevelentity
244/// ::= 'target' 'triple' '=' STRINGCONSTANT
245/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
246bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000248 std::string Str;
Chris Lattnerdf986172009-01-02 07:01:27 +0000249 switch (Lex.Lex()) {
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
252 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000255 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000256 M->setTargetTriple(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000257 return false;
258 case lltok::kw_datalayout:
259 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
Chris Lattnerdf986172009-01-02 07:01:27 +0000262 return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000263 M->setDataLayout(Str);
Chris Lattnerdf986172009-01-02 07:01:27 +0000264 return false;
265 }
266}
267
268/// toplevelentity
269/// ::= 'deplibs' '=' '[' ']'
270/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
271bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
Chris Lattnerdf986172009-01-02 07:01:27 +0000273 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
276 return true;
277
278 if (EatIfPresent(lltok::rsquare))
279 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000281 std::string Str;
282 if (ParseStringConstant(Str)) return true;
283 M->addLibrary(Str);
284
285 while (EatIfPresent(lltok::comma)) {
286 if (ParseStringConstant(Str)) return true;
287 M->addLibrary(Str);
288 }
289
290 return ParseToken(lltok::rsquare, "expected ']' at end of list");
Chris Lattnerdf986172009-01-02 07:01:27 +0000291}
292
Dan Gohman3845e502009-08-12 23:32:33 +0000293/// ParseUnnamedType:
Dan Gohman3845e502009-08-12 23:32:33 +0000294/// ::= LocalVarID '=' 'type' type
Chris Lattnerdf986172009-01-02 07:01:27 +0000295bool LLParser::ParseUnnamedType() {
Chris Lattneredcaca82011-06-18 23:51:31 +0000296 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +0000297 unsigned TypeID = Lex.getUIntVal();
Chris Lattnera53616d2011-06-19 00:03:46 +0000298 Lex.Lex(); // eat LocalVarID;
299
300 if (ParseToken(lltok::equal, "expected '=' after name") ||
301 ParseToken(lltok::kw_type, "expected 'type' after '='"))
302 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +0000303
Chris Lattner1afcace2011-07-09 17:41:24 +0000304 if (TypeID >= NumberedTypes.size())
305 NumberedTypes.resize(TypeID+1);
306
307 Type *Result = 0;
308 if (ParseStructDefinition(TypeLoc, "",
309 NumberedTypes[TypeID], Result)) return true;
310
311 if (!isa<StructType>(Result)) {
312 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
313 if (Entry.first)
314 return Error(TypeLoc, "non-struct types may not be recursive");
315 Entry.first = Result;
316 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000317 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000318
Chris Lattnerdf986172009-01-02 07:01:27 +0000319 return false;
320}
321
Chris Lattner1afcace2011-07-09 17:41:24 +0000322
Chris Lattnerdf986172009-01-02 07:01:27 +0000323/// toplevelentity
324/// ::= LocalVar '=' 'type' type
325bool LLParser::ParseNamedType() {
326 std::string Name = Lex.getStrVal();
327 LocTy NameLoc = Lex.getLoc();
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000328 Lex.Lex(); // eat LocalVar.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000330 if (ParseToken(lltok::equal, "expected '=' after name") ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000331 ParseToken(lltok::kw_type, "expected 'type' after name"))
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000332 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000333
334 Type *Result = 0;
335 if (ParseStructDefinition(NameLoc, Name,
336 NamedTypes[Name], Result)) return true;
337
338 if (!isa<StructType>(Result)) {
339 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
340 if (Entry.first)
341 return Error(NameLoc, "non-struct types may not be recursive");
342 Entry.first = Result;
343 Entry.second = SMLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +0000344 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000345
346 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000347}
348
349
350/// toplevelentity
351/// ::= 'declare' FunctionHeader
352bool LLParser::ParseDeclare() {
353 assert(Lex.getKind() == lltok::kw_declare);
354 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Chris Lattnerdf986172009-01-02 07:01:27 +0000356 Function *F;
357 return ParseFunctionHeader(F, false);
358}
359
360/// toplevelentity
361/// ::= 'define' FunctionHeader '{' ...
362bool LLParser::ParseDefine() {
363 assert(Lex.getKind() == lltok::kw_define);
364 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000365
Chris Lattnerdf986172009-01-02 07:01:27 +0000366 Function *F;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000367 return ParseFunctionHeader(F, true) ||
368 ParseFunctionBody(*F);
Chris Lattnerdf986172009-01-02 07:01:27 +0000369}
370
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000371/// ParseGlobalType
372/// ::= 'constant'
373/// ::= 'global'
Chris Lattnerdf986172009-01-02 07:01:27 +0000374bool LLParser::ParseGlobalType(bool &IsConstant) {
375 if (Lex.getKind() == lltok::kw_constant)
376 IsConstant = true;
377 else if (Lex.getKind() == lltok::kw_global)
378 IsConstant = false;
Duncan Sands35b51072009-02-10 16:24:55 +0000379 else {
380 IsConstant = false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000381 return TokError("expected 'global' or 'constant'");
Duncan Sands35b51072009-02-10 16:24:55 +0000382 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000383 Lex.Lex();
384 return false;
385}
386
Dan Gohman3845e502009-08-12 23:32:33 +0000387/// ParseUnnamedGlobal:
388/// OptionalVisibility ALIAS ...
389/// OptionalLinkage OptionalVisibility ... -> global variable
390/// GlobalID '=' OptionalVisibility ALIAS ...
391/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
392bool LLParser::ParseUnnamedGlobal() {
393 unsigned VarID = NumberedVals.size();
394 std::string Name;
395 LocTy NameLoc = Lex.getLoc();
396
397 // Handle the GlobalID form.
398 if (Lex.getKind() == lltok::GlobalID) {
399 if (Lex.getUIntVal() != VarID)
400 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000401 Twine(VarID) + "'");
Dan Gohman3845e502009-08-12 23:32:33 +0000402 Lex.Lex(); // eat GlobalID;
403
404 if (ParseToken(lltok::equal, "expected '=' after name"))
405 return true;
406 }
407
408 bool HasLinkage;
409 unsigned Linkage, Visibility;
410 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
411 ParseOptionalVisibility(Visibility))
412 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000413
Dan Gohman3845e502009-08-12 23:32:33 +0000414 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
415 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
416 return ParseAlias(Name, NameLoc, Visibility);
417}
418
Chris Lattnerdf986172009-01-02 07:01:27 +0000419/// ParseNamedGlobal:
420/// GlobalVar '=' OptionalVisibility ALIAS ...
421/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
422bool LLParser::ParseNamedGlobal() {
423 assert(Lex.getKind() == lltok::GlobalVar);
424 LocTy NameLoc = Lex.getLoc();
425 std::string Name = Lex.getStrVal();
426 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000427
Chris Lattnerdf986172009-01-02 07:01:27 +0000428 bool HasLinkage;
429 unsigned Linkage, Visibility;
430 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
431 ParseOptionalLinkage(Linkage, HasLinkage) ||
432 ParseOptionalVisibility(Visibility))
433 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000434
Chris Lattnerdf986172009-01-02 07:01:27 +0000435 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
436 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
437 return ParseAlias(Name, NameLoc, Visibility);
438}
439
Devang Patel256be962009-07-20 19:00:08 +0000440// MDString:
441// ::= '!' STRINGCONSTANT
Chris Lattner442ffa12009-12-29 21:53:55 +0000442bool LLParser::ParseMDString(MDString *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000443 std::string Str;
444 if (ParseStringConstant(Str)) return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000445 Result = MDString::get(Context, Str);
Devang Patel256be962009-07-20 19:00:08 +0000446 return false;
447}
448
449// MDNode:
450// ::= '!' MDNodeNumber
Chris Lattner449c3102010-04-01 05:14:45 +0000451//
452/// This version of ParseMDNodeID returns the slot number and null in the case
453/// of a forward reference.
454bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
455 // !{ ..., !42, ... }
456 if (ParseUInt32(SlotNo)) return true;
457
458 // Check existing MDNode.
459 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
460 Result = NumberedMetadata[SlotNo];
461 else
462 Result = 0;
463 return false;
464}
465
Chris Lattner4a72efc2009-12-30 04:15:23 +0000466bool LLParser::ParseMDNodeID(MDNode *&Result) {
Devang Patel256be962009-07-20 19:00:08 +0000467 // !{ ..., !42, ... }
468 unsigned MID = 0;
Chris Lattner449c3102010-04-01 05:14:45 +0000469 if (ParseMDNodeID(Result, MID)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000470
Chris Lattner449c3102010-04-01 05:14:45 +0000471 // If not a forward reference, just return it now.
472 if (Result) return false;
Devang Patel256be962009-07-20 19:00:08 +0000473
Chris Lattner449c3102010-04-01 05:14:45 +0000474 // Otherwise, create MDNode forward reference.
Jay Foadec9186b2011-04-21 19:59:31 +0000475 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Patel256be962009-07-20 19:00:08 +0000476 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
Chris Lattner0834e6a2009-12-30 04:51:58 +0000477
478 if (NumberedMetadata.size() <= MID)
479 NumberedMetadata.resize(MID+1);
480 NumberedMetadata[MID] = FwdNode;
Chris Lattner442ffa12009-12-29 21:53:55 +0000481 Result = FwdNode;
Devang Patel256be962009-07-20 19:00:08 +0000482 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000483}
Devang Patel256be962009-07-20 19:00:08 +0000484
Chris Lattner84d03b12009-12-29 22:35:39 +0000485/// ParseNamedMetadata:
Devang Pateleff2ab62009-07-29 00:34:02 +0000486/// !foo = !{ !1, !2 }
487bool LLParser::ParseNamedMetadata() {
Chris Lattner1d928312009-12-30 05:02:06 +0000488 assert(Lex.getKind() == lltok::MetadataVar);
Devang Pateleff2ab62009-07-29 00:34:02 +0000489 std::string Name = Lex.getStrVal();
Chris Lattner1d928312009-12-30 05:02:06 +0000490 Lex.Lex();
Devang Pateleff2ab62009-07-29 00:34:02 +0000491
Chris Lattner84d03b12009-12-29 22:35:39 +0000492 if (ParseToken(lltok::equal, "expected '=' here") ||
Chris Lattnere434d272009-12-30 04:56:59 +0000493 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner84d03b12009-12-29 22:35:39 +0000494 ParseToken(lltok::lbrace, "Expected '{' here"))
Devang Pateleff2ab62009-07-29 00:34:02 +0000495 return true;
496
Dan Gohman17aa92c2010-07-21 23:38:33 +0000497 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000498 if (Lex.getKind() != lltok::rbrace)
499 do {
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000500 if (ParseToken(lltok::exclaim, "Expected '!' here"))
501 return true;
Chris Lattner442ffa12009-12-29 21:53:55 +0000502
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000503 MDNode *N = 0;
504 if (ParseMDNodeID(N)) return true;
Dan Gohman17aa92c2010-07-21 23:38:33 +0000505 NMD->addOperand(N);
Dan Gohman9dc8ae12010-07-13 19:42:44 +0000506 } while (EatIfPresent(lltok::comma));
Devang Pateleff2ab62009-07-29 00:34:02 +0000507
508 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
509 return true;
510
Devang Pateleff2ab62009-07-29 00:34:02 +0000511 return false;
512}
513
Devang Patel923078c2009-07-01 19:21:12 +0000514/// ParseStandaloneMetadata:
Daniel Dunbara279bc32009-09-20 02:20:51 +0000515/// !42 = !{...}
Devang Patel923078c2009-07-01 19:21:12 +0000516bool LLParser::ParseStandaloneMetadata() {
Chris Lattnere434d272009-12-30 04:56:59 +0000517 assert(Lex.getKind() == lltok::exclaim);
Devang Patel923078c2009-07-01 19:21:12 +0000518 Lex.Lex();
519 unsigned MetadataID = 0;
Devang Patel923078c2009-07-01 19:21:12 +0000520
521 LocTy TyLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +0000522 Type *Ty = 0;
Devang Patel104cf9e2009-07-23 01:07:34 +0000523 SmallVector<Value *, 16> Elts;
Chris Lattner3f5132a2009-12-29 22:40:21 +0000524 if (ParseUInt32(MetadataID) ||
525 ParseToken(lltok::equal, "expected '=' here") ||
526 ParseType(Ty, TyLoc) ||
Chris Lattnere434d272009-12-30 04:56:59 +0000527 ParseToken(lltok::exclaim, "Expected '!' here") ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000528 ParseToken(lltok::lbrace, "Expected '{' here") ||
Victor Hernandez24e64df2010-01-10 07:14:18 +0000529 ParseMDNodeVector(Elts, NULL) ||
Chris Lattner3f5132a2009-12-29 22:40:21 +0000530 ParseToken(lltok::rbrace, "expected end of metadata node"))
Devang Patel104cf9e2009-07-23 01:07:34 +0000531 return true;
532
Jay Foadec9186b2011-04-21 19:59:31 +0000533 MDNode *Init = MDNode::get(Context, Elts);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000534
535 // See if this was forward referenced, if so, handle it.
Chris Lattnere80250e2009-12-29 21:43:58 +0000536 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
Devang Patel1c7eea62009-07-08 19:23:54 +0000537 FI = ForwardRefMDNodes.find(MetadataID);
538 if (FI != ForwardRefMDNodes.end()) {
Dan Gohman489b29b2010-08-20 22:02:26 +0000539 MDNode *Temp = FI->second.first;
540 Temp->replaceAllUsesWith(Init);
541 MDNode::deleteTemporary(Temp);
Devang Patel1c7eea62009-07-08 19:23:54 +0000542 ForwardRefMDNodes.erase(FI);
Chris Lattner0834e6a2009-12-30 04:51:58 +0000543
544 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
545 } else {
546 if (MetadataID >= NumberedMetadata.size())
547 NumberedMetadata.resize(MetadataID+1);
548
549 if (NumberedMetadata[MetadataID] != 0)
550 return TokError("Metadata id is already used");
551 NumberedMetadata[MetadataID] = Init;
Devang Patel1c7eea62009-07-08 19:23:54 +0000552 }
553
Devang Patel923078c2009-07-01 19:21:12 +0000554 return false;
555}
556
Chris Lattnerdf986172009-01-02 07:01:27 +0000557/// ParseAlias:
558/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
559/// Aliasee
Chris Lattner040f7582009-04-25 21:26:00 +0000560/// ::= TypeAndValue
561/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
Dan Gohmandd8004d2009-07-27 21:53:46 +0000562/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
Chris Lattnerdf986172009-01-02 07:01:27 +0000563///
564/// Everything through visibility has already been parsed.
565///
566bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
567 unsigned Visibility) {
568 assert(Lex.getKind() == lltok::kw_alias);
569 Lex.Lex();
570 unsigned Linkage;
571 LocTy LinkageLoc = Lex.getLoc();
572 if (ParseOptionalLinkage(Linkage))
573 return true;
574
575 if (Linkage != GlobalValue::ExternalLinkage &&
Duncan Sands667d4b82009-03-07 15:45:40 +0000576 Linkage != GlobalValue::WeakAnyLinkage &&
577 Linkage != GlobalValue::WeakODRLinkage &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000578 Linkage != GlobalValue::InternalLinkage &&
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000579 Linkage != GlobalValue::PrivateLinkage &&
Bill Wendling5e721d72010-07-01 21:55:59 +0000580 Linkage != GlobalValue::LinkerPrivateLinkage &&
Bill Wendling55ae5152010-08-20 22:05:50 +0000581 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
582 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
Chris Lattnerdf986172009-01-02 07:01:27 +0000583 return Error(LinkageLoc, "invalid linkage type for alias");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000584
Chris Lattnerdf986172009-01-02 07:01:27 +0000585 Constant *Aliasee;
586 LocTy AliaseeLoc = Lex.getLoc();
Chris Lattner040f7582009-04-25 21:26:00 +0000587 if (Lex.getKind() != lltok::kw_bitcast &&
588 Lex.getKind() != lltok::kw_getelementptr) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000589 if (ParseGlobalTypeAndValue(Aliasee)) return true;
590 } else {
591 // The bitcast dest type is not present, it is implied by the dest type.
592 ValID ID;
593 if (ParseValID(ID)) return true;
594 if (ID.Kind != ValID::t_Constant)
595 return Error(AliaseeLoc, "invalid aliasee");
596 Aliasee = ID.ConstantVal;
597 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000598
Duncan Sands1df98592010-02-16 11:11:14 +0000599 if (!Aliasee->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +0000600 return Error(AliaseeLoc, "alias must have pointer type");
601
602 // Okay, create the alias but do not insert it into the module yet.
603 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
604 (GlobalValue::LinkageTypes)Linkage, Name,
605 Aliasee);
606 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000607
Chris Lattnerdf986172009-01-02 07:01:27 +0000608 // See if this value already exists in the symbol table. If so, it is either
609 // a redefinition or a definition of a forward reference.
Chris Lattner1d871c52009-10-25 23:22:50 +0000610 if (GlobalValue *Val = M->getNamedValue(Name)) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000611 // See if this was a redefinition. If so, there is no entry in
612 // ForwardRefVals.
613 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
614 I = ForwardRefVals.find(Name);
615 if (I == ForwardRefVals.end())
616 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
617
618 // Otherwise, this was a definition of forward ref. Verify that types
619 // agree.
620 if (Val->getType() != GA->getType())
621 return Error(NameLoc,
622 "forward reference and definition of alias have different types");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000623
Chris Lattnerdf986172009-01-02 07:01:27 +0000624 // If they agree, just RAUW the old value with the alias and remove the
625 // forward ref info.
626 Val->replaceAllUsesWith(GA);
627 Val->eraseFromParent();
628 ForwardRefVals.erase(I);
629 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000630
Chris Lattnerdf986172009-01-02 07:01:27 +0000631 // Insert into the module, we know its name won't collide now.
632 M->getAliasList().push_back(GA);
Benjamin Krameraf812352010-10-16 11:28:23 +0000633 assert(GA->getName() == Name && "Should not be a name conflict!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000634
Chris Lattnerdf986172009-01-02 07:01:27 +0000635 return false;
636}
637
638/// ParseGlobal
639/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000640/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000641/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
Rafael Espindolabea46262011-01-08 16:42:36 +0000642/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
Chris Lattnerdf986172009-01-02 07:01:27 +0000643///
644/// Everything through visibility has been parsed already.
645///
646bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
647 unsigned Linkage, bool HasLinkage,
648 unsigned Visibility) {
649 unsigned AddrSpace;
Rafael Espindolabea46262011-01-08 16:42:36 +0000650 bool ThreadLocal, IsConstant, UnnamedAddr;
Rafael Espindolad72479c2011-01-13 01:30:30 +0000651 LocTy UnnamedAddrLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +0000652 LocTy TyLoc;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653
Chris Lattner1afcace2011-07-09 17:41:24 +0000654 Type *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +0000655 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
656 ParseOptionalAddrSpace(AddrSpace) ||
Rafael Espindolad72479c2011-01-13 01:30:30 +0000657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 &UnnamedAddrLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000659 ParseGlobalType(IsConstant) ||
660 ParseType(Ty, TyLoc))
661 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000662
Chris Lattnerdf986172009-01-02 07:01:27 +0000663 // If the linkage is specified and is external, then no initializer is
664 // present.
665 Constant *Init = 0;
666 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000667 Linkage != GlobalValue::ExternalWeakLinkage &&
Chris Lattnerdf986172009-01-02 07:01:27 +0000668 Linkage != GlobalValue::ExternalLinkage)) {
669 if (ParseGlobalValue(Ty, Init))
670 return true;
671 }
672
Duncan Sands1df98592010-02-16 11:11:14 +0000673 if (Ty->isFunctionTy() || Ty->isLabelTy())
Chris Lattner4a2f1122009-02-08 20:00:15 +0000674 return Error(TyLoc, "invalid type for global variable");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Chris Lattnerdf986172009-01-02 07:01:27 +0000676 GlobalVariable *GV = 0;
677
678 // See if the global was forward referenced, if so, use the global.
Chris Lattner91dad872009-02-02 07:24:28 +0000679 if (!Name.empty()) {
Chris Lattner1d871c52009-10-25 23:22:50 +0000680 if (GlobalValue *GVal = M->getNamedValue(Name)) {
681 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
682 return Error(NameLoc, "redefinition of global '@" + Name + "'");
683 GV = cast<GlobalVariable>(GVal);
684 }
Chris Lattnerdf986172009-01-02 07:01:27 +0000685 } else {
686 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefValIDs.find(NumberedVals.size());
688 if (I != ForwardRefValIDs.end()) {
689 GV = cast<GlobalVariable>(I->second.first);
690 ForwardRefValIDs.erase(I);
691 }
692 }
693
694 if (GV == 0) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000695 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000696 Name, 0, false, 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);
715 GV->setThreadLocal(ThreadLocal);
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
863
864/// ParseOptionalAddrSpace
865/// := /*empty*/
866/// := 'addrspace' '(' uint32 ')'
867bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
868 AddrSpace = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000869 if (!EatIfPresent(lltok::kw_addrspace))
Chris Lattnerdf986172009-01-02 07:01:27 +0000870 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +0000871 return ParseToken(lltok::lparen, "expected '(' in address space") ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +0000872 ParseUInt32(AddrSpace) ||
Chris Lattnerdf986172009-01-02 07:01:27 +0000873 ParseToken(lltok::rparen, "expected ')' in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000874}
Chris Lattnerdf986172009-01-02 07:01:27 +0000875
876/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
877/// indicates what kind of attribute list this is: 0: function arg, 1: result,
878/// 2: function attr.
879bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
880 Attrs = Attribute::None;
881 LocTy AttrLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000882
Chris Lattnerdf986172009-01-02 07:01:27 +0000883 while (1) {
884 switch (Lex.getKind()) {
Chris Lattnerdf986172009-01-02 07:01:27 +0000885 default: // End of attributes.
886 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
887 return Error(AttrLoc, "invalid use of function-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000888
Chris Lattnerf3a789d2011-06-17 03:16:47 +0000889 // As a hack, we allow "align 2" on functions as a synonym for
890 // "alignstack 2".
891 if (AttrKind == 2 &&
892 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
893 return Error(AttrLoc, "invalid use of attribute on a function");
894
895 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
Chris Lattnerdf986172009-01-02 07:01:27 +0000896 return Error(AttrLoc, "invalid use of parameter-only attribute");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000897
Chris Lattnerdf986172009-01-02 07:01:27 +0000898 return false;
Devang Patel578efa92009-06-05 21:57:13 +0000899 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
900 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
901 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
902 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
903 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
904 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
905 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
906 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000907
Devang Patel578efa92009-06-05 21:57:13 +0000908 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
909 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000910 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
Devang Patel578efa92009-06-05 21:57:13 +0000911 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
912 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
913 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000914 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
Devang Patel578efa92009-06-05 21:57:13 +0000915 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
916 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
917 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
918 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
919 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
920 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
Anton Korobeynikovc5ec8a72009-07-17 18:07:26 +0000921 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
Charles Davis970bfcc2010-10-25 15:37:09 +0000922 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
John McCall3a3465b2011-06-15 20:36:13 +0000923 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000924
Charles Davis1e063d12010-02-12 00:31:15 +0000925 case lltok::kw_alignstack: {
926 unsigned Alignment;
927 if (ParseOptionalStackAlignment(Alignment))
928 return true;
929 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
930 continue;
931 }
932
Chris Lattnerdf986172009-01-02 07:01:27 +0000933 case lltok::kw_align: {
934 unsigned Alignment;
935 if (ParseOptionalAlignment(Alignment))
936 return true;
937 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
938 continue;
939 }
Charles Davis1e063d12010-02-12 00:31:15 +0000940
Chris Lattnerdf986172009-01-02 07:01:27 +0000941 }
942 Lex.Lex();
943 }
944}
945
946/// ParseOptionalLinkage
947/// ::= /*empty*/
Rafael Espindolabb46f522009-01-15 20:18:42 +0000948/// ::= 'private'
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000949/// ::= 'linker_private'
Bill Wendling5e721d72010-07-01 21:55:59 +0000950/// ::= 'linker_private_weak'
Bill Wendling55ae5152010-08-20 22:05:50 +0000951/// ::= 'linker_private_weak_def_auto'
Chris Lattnerdf986172009-01-02 07:01:27 +0000952/// ::= 'internal'
953/// ::= 'weak'
Duncan Sands667d4b82009-03-07 15:45:40 +0000954/// ::= 'weak_odr'
Chris Lattnerdf986172009-01-02 07:01:27 +0000955/// ::= 'linkonce'
Duncan Sands667d4b82009-03-07 15:45:40 +0000956/// ::= 'linkonce_odr'
Bill Wendling5e721d72010-07-01 21:55:59 +0000957/// ::= 'available_externally'
Chris Lattnerdf986172009-01-02 07:01:27 +0000958/// ::= 'appending'
959/// ::= 'dllexport'
960/// ::= 'common'
961/// ::= 'dllimport'
962/// ::= 'extern_weak'
963/// ::= 'external'
964bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
965 HasLinkage = false;
966 switch (Lex.getKind()) {
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000967 default: Res=GlobalValue::ExternalLinkage; return false;
968 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
969 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000970 case lltok::kw_linker_private_weak:
971 Res = GlobalValue::LinkerPrivateWeakLinkage;
972 break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000973 case lltok::kw_linker_private_weak_def_auto:
974 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
975 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000976 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
977 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
978 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
979 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
980 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000981 case lltok::kw_available_externally:
982 Res = GlobalValue::AvailableExternallyLinkage;
983 break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000984 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
985 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
986 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
987 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
988 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
989 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
Chris Lattnerdf986172009-01-02 07:01:27 +0000990 }
991 Lex.Lex();
992 HasLinkage = true;
993 return false;
994}
995
996/// ParseOptionalVisibility
997/// ::= /*empty*/
998/// ::= 'default'
999/// ::= 'hidden'
1000/// ::= 'protected'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001001///
Chris Lattnerdf986172009-01-02 07:01:27 +00001002bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1003 switch (Lex.getKind()) {
1004 default: Res = GlobalValue::DefaultVisibility; return false;
1005 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1006 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1007 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1008 }
1009 Lex.Lex();
1010 return false;
1011}
1012
1013/// ParseOptionalCallingConv
1014/// ::= /*empty*/
1015/// ::= 'ccc'
1016/// ::= 'fastcc'
1017/// ::= 'coldcc'
1018/// ::= 'x86_stdcallcc'
1019/// ::= 'x86_fastcallcc'
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001020/// ::= 'x86_thiscallcc'
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001021/// ::= 'arm_apcscc'
1022/// ::= 'arm_aapcscc'
1023/// ::= 'arm_aapcs_vfpcc'
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001024/// ::= 'msp430_intrcc'
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001025/// ::= 'ptx_kernel'
1026/// ::= 'ptx_device'
Chris Lattnerdf986172009-01-02 07:01:27 +00001027/// ::= 'cc' UINT
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001028///
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001029bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001030 switch (Lex.getKind()) {
1031 default: CC = CallingConv::C; return false;
1032 case lltok::kw_ccc: CC = CallingConv::C; break;
1033 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1034 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1035 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1036 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
Anton Korobeynikovded05e32010-05-16 09:08:45 +00001037 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
Anton Korobeynikov385f5a92009-06-16 18:50:49 +00001038 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1039 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1040 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
Anton Korobeynikov211a14e2009-12-07 02:27:35 +00001041 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
Che-Liang Chiouf9930da2010-09-25 07:46:17 +00001042 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1043 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001044 case lltok::kw_cc: {
1045 unsigned ArbitraryCC;
1046 Lex.Lex();
1047 if (ParseUInt32(ArbitraryCC)) {
1048 return true;
1049 } else
1050 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1051 return false;
1052 }
1053 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001054 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001055
Chris Lattnerdf986172009-01-02 07:01:27 +00001056 Lex.Lex();
1057 return false;
1058}
1059
Chris Lattnerb8c46862009-12-30 05:31:19 +00001060/// ParseInstructionMetadata
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001061/// ::= !dbg !42 (',' !dbg !57)*
Dan Gohman9d072f52010-08-24 02:05:17 +00001062bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1063 PerFunctionState *PFS) {
Chris Lattnerb8c46862009-12-30 05:31:19 +00001064 do {
1065 if (Lex.getKind() != lltok::MetadataVar)
1066 return TokError("expected metadata after comma");
Devang Patel0475c912009-09-29 00:01:14 +00001067
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001068 std::string Name = Lex.getStrVal();
Dan Gohman309b3af2010-08-24 02:24:03 +00001069 unsigned MDK = M->getMDKindID(Name.c_str());
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001070 Lex.Lex();
Chris Lattner52e20312009-10-19 05:31:10 +00001071
Chris Lattner442ffa12009-12-29 21:53:55 +00001072 MDNode *Node;
Chris Lattner449c3102010-04-01 05:14:45 +00001073 SMLoc Loc = Lex.getLoc();
Dan Gohman309b3af2010-08-24 02:24:03 +00001074
1075 if (ParseToken(lltok::exclaim, "expected '!' here"))
Chris Lattnere434d272009-12-30 04:56:59 +00001076 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001077
Dan Gohman68261142010-08-24 14:35:45 +00001078 // This code is similar to that of ParseMetadataValue, however it needs to
1079 // have special-case code for a forward reference; see the comments on
1080 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1081 // at the top level here.
Dan Gohman309b3af2010-08-24 02:24:03 +00001082 if (Lex.getKind() == lltok::lbrace) {
1083 ValID ID;
1084 if (ParseMetadataListValue(ID, PFS))
1085 return true;
1086 assert(ID.Kind == ValID::t_MDNode);
1087 Inst->setMetadata(MDK, ID.MDNodeVal);
Chris Lattner449c3102010-04-01 05:14:45 +00001088 } else {
Nick Lewyckyc6877b42010-09-30 21:04:13 +00001089 unsigned NodeID = 0;
Dan Gohman309b3af2010-08-24 02:24:03 +00001090 if (ParseMDNodeID(Node, NodeID))
1091 return true;
1092 if (Node) {
1093 // If we got the node, add it to the instruction.
1094 Inst->setMetadata(MDK, Node);
1095 } else {
1096 MDRef R = { Loc, MDK, NodeID };
1097 // Otherwise, remember that this should be resolved later.
1098 ForwardRefInstMetadata[Inst].push_back(R);
1099 }
Chris Lattner449c3102010-04-01 05:14:45 +00001100 }
Chris Lattner3f3a0f62009-12-29 21:25:40 +00001101
1102 // If this is the end of the list, we're done.
Chris Lattnerb8c46862009-12-30 05:31:19 +00001103 } while (EatIfPresent(lltok::comma));
1104 return false;
Devang Patelf633a062009-09-17 23:04:48 +00001105}
1106
Chris Lattnerdf986172009-01-02 07:01:27 +00001107/// ParseOptionalAlignment
1108/// ::= /* empty */
1109/// ::= 'align' 4
1110bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1111 Alignment = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001112 if (!EatIfPresent(lltok::kw_align))
1113 return false;
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001114 LocTy AlignLoc = Lex.getLoc();
1115 if (ParseUInt32(Alignment)) return true;
1116 if (!isPowerOf2_32(Alignment))
1117 return Error(AlignLoc, "alignment is not a power of two");
Dan Gohmane16829b2010-07-30 21:07:05 +00001118 if (Alignment > Value::MaximumAlignment)
Dan Gohman138aa2a2010-07-28 20:12:04 +00001119 return Error(AlignLoc, "huge alignments are not supported yet");
Chris Lattner3fbb3ab2009-01-05 07:46:05 +00001120 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001121}
1122
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001123/// ParseOptionalCommaAlign
1124/// ::=
1125/// ::= ',' align 4
1126///
1127/// This returns with AteExtraComma set to true if it ate an excess comma at the
1128/// end.
1129bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1130 bool &AteExtraComma) {
1131 AteExtraComma = false;
1132 while (EatIfPresent(lltok::comma)) {
1133 // Metadata at the end is an early exit.
Chris Lattner1d928312009-12-30 05:02:06 +00001134 if (Lex.getKind() == lltok::MetadataVar) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001135 AteExtraComma = true;
1136 return false;
1137 }
1138
Chris Lattner093eed12010-04-23 00:50:50 +00001139 if (Lex.getKind() != lltok::kw_align)
1140 return Error(Lex.getLoc(), "expected metadata or 'align'");
Duncan Sandsbf9fc532010-10-21 16:07:10 +00001141
Chris Lattner093eed12010-04-23 00:50:50 +00001142 if (ParseOptionalAlignment(Alignment)) return true;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00001143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001144
Devang Patelf633a062009-09-17 23:04:48 +00001145 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001146}
1147
Eli Friedman47f35132011-07-25 23:16:38 +00001148/// ParseScopeAndOrdering
1149/// if isAtomic: ::= 'singlethread'? AtomicOrdering
1150/// else: ::=
1151///
1152/// This sets Scope and Ordering to the parsed values.
1153bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1154 AtomicOrdering &Ordering) {
1155 if (!isAtomic)
1156 return false;
1157
1158 Scope = CrossThread;
1159 if (EatIfPresent(lltok::kw_singlethread))
1160 Scope = SingleThread;
1161 switch (Lex.getKind()) {
1162 default: return TokError("Expected ordering on atomic instruction");
1163 case lltok::kw_unordered: Ordering = Unordered; break;
1164 case lltok::kw_monotonic: Ordering = Monotonic; break;
1165 case lltok::kw_acquire: Ordering = Acquire; break;
1166 case lltok::kw_release: Ordering = Release; break;
1167 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1168 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1169 }
1170 Lex.Lex();
1171 return false;
1172}
1173
Charles Davis1e063d12010-02-12 00:31:15 +00001174/// ParseOptionalStackAlignment
1175/// ::= /* empty */
1176/// ::= 'alignstack' '(' 4 ')'
1177bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1178 Alignment = 0;
1179 if (!EatIfPresent(lltok::kw_alignstack))
1180 return false;
1181 LocTy ParenLoc = Lex.getLoc();
1182 if (!EatIfPresent(lltok::lparen))
1183 return Error(ParenLoc, "expected '('");
1184 LocTy AlignLoc = Lex.getLoc();
1185 if (ParseUInt32(Alignment)) return true;
1186 ParenLoc = Lex.getLoc();
1187 if (!EatIfPresent(lltok::rparen))
1188 return Error(ParenLoc, "expected ')'");
1189 if (!isPowerOf2_32(Alignment))
1190 return Error(AlignLoc, "stack alignment is not a power of two");
1191 return false;
1192}
Devang Patelf633a062009-09-17 23:04:48 +00001193
Chris Lattner628c13a2009-12-30 05:14:00 +00001194/// ParseIndexList - This parses the index list for an insert/extractvalue
1195/// instruction. This sets AteExtraComma in the case where we eat an extra
1196/// comma at the end of the line and find that it is followed by metadata.
1197/// Clients that don't allow metadata can call the version of this function that
1198/// only takes one argument.
1199///
Chris Lattnerdf986172009-01-02 07:01:27 +00001200/// ParseIndexList
1201/// ::= (',' uint32)+
Chris Lattner628c13a2009-12-30 05:14:00 +00001202///
1203bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1204 bool &AteExtraComma) {
1205 AteExtraComma = false;
1206
Chris Lattnerdf986172009-01-02 07:01:27 +00001207 if (Lex.getKind() != lltok::comma)
1208 return TokError("expected ',' as start of index list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001209
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001210 while (EatIfPresent(lltok::comma)) {
Chris Lattner628c13a2009-12-30 05:14:00 +00001211 if (Lex.getKind() == lltok::MetadataVar) {
1212 AteExtraComma = true;
1213 return false;
1214 }
Nick Lewycky28815c42010-09-29 23:32:20 +00001215 unsigned Idx = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001216 if (ParseUInt32(Idx)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001217 Indices.push_back(Idx);
1218 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219
Chris Lattnerdf986172009-01-02 07:01:27 +00001220 return false;
1221}
1222
1223//===----------------------------------------------------------------------===//
1224// Type Parsing.
1225//===----------------------------------------------------------------------===//
1226
Chris Lattner1afcace2011-07-09 17:41:24 +00001227/// ParseType - Parse a type.
1228bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1229 SMLoc TypeLoc = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001230 switch (Lex.getKind()) {
1231 default:
1232 return TokError("expected type");
1233 case lltok::Type:
Chris Lattner1afcace2011-07-09 17:41:24 +00001234 // Type ::= 'float' | 'void' (etc)
Chris Lattnerdf986172009-01-02 07:01:27 +00001235 Result = Lex.getTyVal();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001236 Lex.Lex();
Chris Lattnerdf986172009-01-02 07:01:27 +00001237 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001238 case lltok::lbrace:
Chris Lattner1afcace2011-07-09 17:41:24 +00001239 // Type ::= StructType
1240 if (ParseAnonStructType(Result, false))
Chris Lattnerdf986172009-01-02 07:01:27 +00001241 return true;
1242 break;
1243 case lltok::lsquare:
Chris Lattner1afcace2011-07-09 17:41:24 +00001244 // Type ::= '[' ... ']'
Chris Lattnerdf986172009-01-02 07:01:27 +00001245 Lex.Lex(); // eat the lsquare.
1246 if (ParseArrayVectorType(Result, false))
1247 return true;
1248 break;
1249 case lltok::less: // Either vector or packed struct.
Chris Lattner1afcace2011-07-09 17:41:24 +00001250 // Type ::= '<' ... '>'
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001251 Lex.Lex();
1252 if (Lex.getKind() == lltok::lbrace) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001253 if (ParseAnonStructType(Result, true) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001254 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
Chris Lattnerdf986172009-01-02 07:01:27 +00001255 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001256 } else if (ParseArrayVectorType(Result, true))
1257 return true;
1258 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001259 case lltok::LocalVar: {
1260 // Type ::= %foo
1261 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1262
1263 // If the type hasn't been defined yet, create a forward definition and
1264 // remember where that forward def'n was seen (in case it never is defined).
1265 if (Entry.first == 0) {
1266 Entry.first = StructType::createNamed(Context, Lex.getStrVal());
1267 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001268 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001269 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001270 Lex.Lex();
1271 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001272 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001273
Chris Lattner1afcace2011-07-09 17:41:24 +00001274 case lltok::LocalVarID: {
1275 // Type ::= %4
1276 if (Lex.getUIntVal() >= NumberedTypes.size())
1277 NumberedTypes.resize(Lex.getUIntVal()+1);
1278 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1279
1280 // If the type hasn't been defined yet, create a forward definition and
1281 // remember where that forward def'n was seen (in case it never is defined).
1282 if (Entry.first == 0) {
1283 Entry.first = StructType::createNamed(Context, "");
1284 Entry.second = Lex.getLoc();
Chris Lattnerdf986172009-01-02 07:01:27 +00001285 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001286 Result = Entry.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001287 Lex.Lex();
1288 break;
Chris Lattnerdf986172009-01-02 07:01:27 +00001289 }
1290 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
1292 // Parse the type suffixes.
Chris Lattnerdf986172009-01-02 07:01:27 +00001293 while (1) {
1294 switch (Lex.getKind()) {
1295 // End of type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001296 default:
1297 if (!AllowVoid && Result->isVoidTy())
1298 return Error(TypeLoc, "void type only allowed for function results");
1299 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001300
Chris Lattner1afcace2011-07-09 17:41:24 +00001301 // Type ::= Type '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001302 case lltok::star:
Chris Lattner1afcace2011-07-09 17:41:24 +00001303 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001304 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001305 if (Result->isVoidTy())
1306 return TokError("pointers to void are invalid - use i8* instead");
1307 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001308 return TokError("pointer to this type is invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001309 Result = PointerType::getUnqual(Result);
Chris Lattnerdf986172009-01-02 07:01:27 +00001310 Lex.Lex();
1311 break;
1312
Chris Lattner1afcace2011-07-09 17:41:24 +00001313 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
Chris Lattnerdf986172009-01-02 07:01:27 +00001314 case lltok::kw_addrspace: {
Chris Lattner1afcace2011-07-09 17:41:24 +00001315 if (Result->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001316 return TokError("basic block pointers are invalid");
Chris Lattner1afcace2011-07-09 17:41:24 +00001317 if (Result->isVoidTy())
Dan Gohmanb9070d32009-02-09 17:41:21 +00001318 return TokError("pointers to void are invalid; use i8* instead");
Chris Lattner1afcace2011-07-09 17:41:24 +00001319 if (!PointerType::isValidElementType(Result))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001320 return TokError("pointer to this type is invalid");
Chris Lattnerdf986172009-01-02 07:01:27 +00001321 unsigned AddrSpace;
1322 if (ParseOptionalAddrSpace(AddrSpace) ||
1323 ParseToken(lltok::star, "expected '*' in address space"))
1324 return true;
1325
Chris Lattner1afcace2011-07-09 17:41:24 +00001326 Result = PointerType::get(Result, AddrSpace);
Chris Lattnerdf986172009-01-02 07:01:27 +00001327 break;
1328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnerdf986172009-01-02 07:01:27 +00001330 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1331 case lltok::lparen:
1332 if (ParseFunctionType(Result))
1333 return true;
1334 break;
1335 }
1336 }
1337}
1338
1339/// ParseParameterList
1340/// ::= '(' ')'
1341/// ::= '(' Arg (',' Arg)* ')'
1342/// Arg
1343/// ::= Type OptionalAttributes Value OptionalAttributes
1344bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1345 PerFunctionState &PFS) {
1346 if (ParseToken(lltok::lparen, "expected '(' in call"))
1347 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001348
Chris Lattnerdf986172009-01-02 07:01:27 +00001349 while (Lex.getKind() != lltok::rparen) {
1350 // If this isn't the first argument, we need a comma.
1351 if (!ArgList.empty() &&
1352 ParseToken(lltok::comma, "expected ',' in argument list"))
1353 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001354
Chris Lattnerdf986172009-01-02 07:01:27 +00001355 // Parse the argument.
1356 LocTy ArgLoc;
Chris Lattner1afcace2011-07-09 17:41:24 +00001357 Type *ArgTy = 0;
Victor Hernandez19715562009-12-03 23:40:58 +00001358 unsigned ArgAttrs1 = Attribute::None;
1359 unsigned ArgAttrs2 = Attribute::None;
Chris Lattnerdf986172009-01-02 07:01:27 +00001360 Value *V;
Victor Hernandez19715562009-12-03 23:40:58 +00001361 if (ParseType(ArgTy, ArgLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00001362 return true;
Victor Hernandez19715562009-12-03 23:40:58 +00001363
Chris Lattner287881d2009-12-30 02:11:14 +00001364 // Otherwise, handle normal operands.
Chris Lattnerf3a789d2011-06-17 03:16:47 +00001365 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
Chris Lattner287881d2009-12-30 02:11:14 +00001366 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001367 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1368 }
1369
1370 Lex.Lex(); // Lex the ')'.
1371 return false;
1372}
1373
1374
1375
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001376/// ParseArgumentList - Parse the argument list for a function type or function
Chris Lattner1afcace2011-07-09 17:41:24 +00001377/// prototype.
Chris Lattnerdf986172009-01-02 07:01:27 +00001378/// ::= '(' ArgTypeListI ')'
1379/// ArgTypeListI
1380/// ::= /*empty*/
1381/// ::= '...'
1382/// ::= ArgTypeList ',' '...'
1383/// ::= ArgType (',' ArgType)*
Chris Lattnerdfd19dd2009-01-05 18:34:07 +00001384///
Chris Lattner1afcace2011-07-09 17:41:24 +00001385bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1386 bool &isVarArg){
Chris Lattnerdf986172009-01-02 07:01:27 +00001387 isVarArg = false;
1388 assert(Lex.getKind() == lltok::lparen);
1389 Lex.Lex(); // eat the (.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001390
Chris Lattnerdf986172009-01-02 07:01:27 +00001391 if (Lex.getKind() == lltok::rparen) {
1392 // empty
1393 } else if (Lex.getKind() == lltok::dotdotdot) {
1394 isVarArg = true;
1395 Lex.Lex();
1396 } else {
1397 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001398 Type *ArgTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00001399 unsigned Attrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00001400 std::string Name;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001401
Chris Lattner1afcace2011-07-09 17:41:24 +00001402 if (ParseType(ArgTy) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001403 ParseOptionalAttrs(Attrs, 0)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001405 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001406 return Error(TypeLoc, "argument can not have void type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001407
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001408 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001409 Name = Lex.getStrVal();
1410 Lex.Lex();
1411 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001412
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001413 if (!FunctionType::isValidArgumentType(ArgTy))
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001414 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001415
Chris Lattnerdf986172009-01-02 07:01:27 +00001416 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001417
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001418 while (EatIfPresent(lltok::comma)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001419 // Handle ... at end of arg list.
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001420 if (EatIfPresent(lltok::dotdotdot)) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001421 isVarArg = true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001422 break;
1423 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001424
Chris Lattnerdf986172009-01-02 07:01:27 +00001425 // Otherwise must be an argument type.
1426 TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001427 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001428
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001429 if (ArgTy->isVoidTy())
Chris Lattnera9a9e072009-03-09 04:49:14 +00001430 return Error(TypeLoc, "argument can not have void type");
1431
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00001432 if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001433 Name = Lex.getStrVal();
1434 Lex.Lex();
1435 } else {
1436 Name = "";
1437 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001438
Chris Lattner1afcace2011-07-09 17:41:24 +00001439 if (!ArgTy->isFirstClassType())
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001440 return Error(TypeLoc, "invalid type for function argument");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001441
Chris Lattnerdf986172009-01-02 07:01:27 +00001442 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1443 }
1444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001445
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001446 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
Chris Lattnerdf986172009-01-02 07:01:27 +00001447}
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattnerdf986172009-01-02 07:01:27 +00001449/// ParseFunctionType
1450/// ::= Type ArgumentList OptionalAttrs
Chris Lattner1afcace2011-07-09 17:41:24 +00001451bool LLParser::ParseFunctionType(Type *&Result) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001452 assert(Lex.getKind() == lltok::lparen);
1453
Chris Lattnerd77d04c2009-01-05 08:04:33 +00001454 if (!FunctionType::isValidReturnType(Result))
1455 return TokError("invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattner1afcace2011-07-09 17:41:24 +00001457 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00001458 bool isVarArg;
Chris Lattner1afcace2011-07-09 17:41:24 +00001459 if (ParseArgumentList(ArgList, isVarArg))
Chris Lattnerdf986172009-01-02 07:01:27 +00001460 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattnerdf986172009-01-02 07:01:27 +00001462 // Reject names on the arguments lists.
1463 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1464 if (!ArgList[i].Name.empty())
1465 return Error(ArgList[i].Loc, "argument name invalid in function type");
Chris Lattnera16546a2011-06-17 17:37:13 +00001466 if (ArgList[i].Attrs != 0)
1467 return Error(ArgList[i].Loc,
1468 "argument attributes invalid in function type");
Chris Lattnerdf986172009-01-02 07:01:27 +00001469 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001470
Jay Foad5fdd6c82011-07-12 14:06:48 +00001471 SmallVector<Type*, 16> ArgListTy;
Chris Lattnerdf986172009-01-02 07:01:27 +00001472 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
Chris Lattner1afcace2011-07-09 17:41:24 +00001473 ArgListTy.push_back(ArgList[i].Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001474
Chris Lattner1afcace2011-07-09 17:41:24 +00001475 Result = FunctionType::get(Result, ArgListTy, isVarArg);
Chris Lattnerdf986172009-01-02 07:01:27 +00001476 return false;
1477}
1478
Chris Lattner1afcace2011-07-09 17:41:24 +00001479/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1480/// other structs.
1481bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1482 SmallVector<Type*, 8> Elts;
1483 if (ParseStructBody(Elts)) return true;
1484
1485 Result = StructType::get(Context, Elts, Packed);
1486 return false;
1487}
1488
1489/// ParseStructDefinition - Parse a struct in a 'type' definition.
1490bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1491 std::pair<Type*, LocTy> &Entry,
1492 Type *&ResultTy) {
1493 // If the type was already defined, diagnose the redefinition.
1494 if (Entry.first && !Entry.second.isValid())
1495 return Error(TypeLoc, "redefinition of type");
1496
1497 // If we have opaque, just return without filling in the definition for the
1498 // struct. This counts as a definition as far as the .ll file goes.
1499 if (EatIfPresent(lltok::kw_opaque)) {
1500 // This type is being defined, so clear the location to indicate this.
1501 Entry.second = SMLoc();
1502
1503 // If this type number has never been uttered, create it.
1504 if (Entry.first == 0)
1505 Entry.first = StructType::createNamed(Context, Name);
1506 ResultTy = Entry.first;
1507 return false;
1508 }
1509
1510 // If the type starts with '<', then it is either a packed struct or a vector.
1511 bool isPacked = EatIfPresent(lltok::less);
1512
1513 // If we don't have a struct, then we have a random type alias, which we
1514 // accept for compatibility with old files. These types are not allowed to be
1515 // forward referenced and not allowed to be recursive.
1516 if (Lex.getKind() != lltok::lbrace) {
1517 if (Entry.first)
1518 return Error(TypeLoc, "forward references to non-struct type");
1519
1520 ResultTy = 0;
1521 if (isPacked)
1522 return ParseArrayVectorType(ResultTy, true);
1523 return ParseType(ResultTy);
1524 }
1525
1526 // This type is being defined, so clear the location to indicate this.
1527 Entry.second = SMLoc();
1528
1529 // If this type number has never been uttered, create it.
1530 if (Entry.first == 0)
1531 Entry.first = StructType::createNamed(Context, Name);
1532
1533 StructType *STy = cast<StructType>(Entry.first);
1534
1535 SmallVector<Type*, 8> Body;
1536 if (ParseStructBody(Body) ||
1537 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1538 return true;
1539
1540 STy->setBody(Body, isPacked);
1541 ResultTy = STy;
1542 return false;
1543}
1544
1545
Chris Lattnerdf986172009-01-02 07:01:27 +00001546/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
Chris Lattner1afcace2011-07-09 17:41:24 +00001547/// StructType
Chris Lattnerdf986172009-01-02 07:01:27 +00001548/// ::= '{' '}'
Chris Lattner1afcace2011-07-09 17:41:24 +00001549/// ::= '{' Type (',' Type)* '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00001550/// ::= '<' '{' '}' '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001551/// ::= '<' '{' Type (',' Type)* '}' '>'
1552bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001553 assert(Lex.getKind() == lltok::lbrace);
1554 Lex.Lex(); // Consume the '{'
Daniel Dunbara279bc32009-09-20 02:20:51 +00001555
Chris Lattner1afcace2011-07-09 17:41:24 +00001556 // Handle the empty struct.
1557 if (EatIfPresent(lltok::rbrace))
Chris Lattnerdf986172009-01-02 07:01:27 +00001558 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00001559
Chris Lattnera9a9e072009-03-09 04:49:14 +00001560 LocTy EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001561 Type *Ty = 0;
1562 if (ParseType(Ty)) return true;
1563 Body.push_back(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner1afcace2011-07-09 17:41:24 +00001565 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001566 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001567
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001568 while (EatIfPresent(lltok::comma)) {
Chris Lattnera9a9e072009-03-09 04:49:14 +00001569 EltTyLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001570 if (ParseType(Ty)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001571
Chris Lattner1afcace2011-07-09 17:41:24 +00001572 if (!StructType::isValidElementType(Ty))
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001573 return Error(EltTyLoc, "invalid element type for struct");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001574
Chris Lattner1afcace2011-07-09 17:41:24 +00001575 Body.push_back(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00001576 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001577
Chris Lattner1afcace2011-07-09 17:41:24 +00001578 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
Chris Lattnerdf986172009-01-02 07:01:27 +00001579}
1580
1581/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1582/// token has already been consumed.
Chris Lattner1afcace2011-07-09 17:41:24 +00001583/// Type
Chris Lattnerdf986172009-01-02 07:01:27 +00001584/// ::= '[' APSINTVAL 'x' Types ']'
1585/// ::= '<' APSINTVAL 'x' Types '>'
Chris Lattner1afcace2011-07-09 17:41:24 +00001586bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001587 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1588 Lex.getAPSIntVal().getBitWidth() > 64)
1589 return TokError("expected number in address space");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001590
Chris Lattnerdf986172009-01-02 07:01:27 +00001591 LocTy SizeLoc = Lex.getLoc();
1592 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001593 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001595 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1596 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00001597
1598 LocTy TypeLoc = Lex.getLoc();
Chris Lattner1afcace2011-07-09 17:41:24 +00001599 Type *EltTy = 0;
1600 if (ParseType(EltTy)) return true;
Chris Lattnera9a9e072009-03-09 04:49:14 +00001601
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001602 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1603 "expected end of sequential type"))
1604 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001605
Chris Lattnerdf986172009-01-02 07:01:27 +00001606 if (isVector) {
Chris Lattner452e2622009-02-28 18:12:41 +00001607 if (Size == 0)
1608 return Error(SizeLoc, "zero element vector is illegal");
Chris Lattnerdf986172009-01-02 07:01:27 +00001609 if ((unsigned)Size != Size)
1610 return Error(SizeLoc, "size too large for vector");
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001611 if (!VectorType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001612 return Error(TypeLoc, "vector element type must be fp or integer");
Owen Andersondebcb012009-07-29 22:17:13 +00001613 Result = VectorType::get(EltTy, unsigned(Size));
Chris Lattnerdf986172009-01-02 07:01:27 +00001614 } else {
Nick Lewyckya5f54a02009-06-07 07:26:46 +00001615 if (!ArrayType::isValidElementType(EltTy))
Chris Lattnerdf986172009-01-02 07:01:27 +00001616 return Error(TypeLoc, "invalid array element type");
Chris Lattner1afcace2011-07-09 17:41:24 +00001617 Result = ArrayType::get(EltTy, Size);
Chris Lattnerdf986172009-01-02 07:01:27 +00001618 }
1619 return false;
1620}
1621
1622//===----------------------------------------------------------------------===//
1623// Function Semantic Analysis.
1624//===----------------------------------------------------------------------===//
1625
Chris Lattner09d9ef42009-10-28 03:39:23 +00001626LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1627 int functionNumber)
1628 : P(p), F(f), FunctionNumber(functionNumber) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001629
1630 // Insert unnamed arguments into the NumberedVals list.
1631 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1632 AI != E; ++AI)
1633 if (!AI->hasName())
1634 NumberedVals.push_back(AI);
1635}
1636
1637LLParser::PerFunctionState::~PerFunctionState() {
1638 // If there were any forward referenced non-basicblock values, delete them.
1639 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1640 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1641 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001642 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001643 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001644 delete I->second.first;
1645 I->second.first = 0;
1646 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnerdf986172009-01-02 07:01:27 +00001648 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1649 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1650 if (!isa<BasicBlock>(I->second.first)) {
Owen Andersonb43eae72009-07-02 17:04:01 +00001651 I->second.first->replaceAllUsesWith(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001652 UndefValue::get(I->second.first->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00001653 delete I->second.first;
1654 I->second.first = 0;
1655 }
1656}
1657
Chris Lattner09d9ef42009-10-28 03:39:23 +00001658bool LLParser::PerFunctionState::FinishFunction() {
1659 // Check to see if someone took the address of labels in this block.
1660 if (!P.ForwardRefBlockAddresses.empty()) {
1661 ValID FunctionID;
1662 if (!F.getName().empty()) {
1663 FunctionID.Kind = ValID::t_GlobalName;
1664 FunctionID.StrVal = F.getName();
1665 } else {
1666 FunctionID.Kind = ValID::t_GlobalID;
1667 FunctionID.UIntVal = FunctionNumber;
1668 }
1669
1670 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1671 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1672 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1673 // Resolve all these references.
1674 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1675 return true;
1676
1677 P.ForwardRefBlockAddresses.erase(FRBAI);
1678 }
1679 }
1680
Chris Lattnerdf986172009-01-02 07:01:27 +00001681 if (!ForwardRefVals.empty())
1682 return P.Error(ForwardRefVals.begin()->second.second,
1683 "use of undefined value '%" + ForwardRefVals.begin()->first +
1684 "'");
1685 if (!ForwardRefValIDs.empty())
1686 return P.Error(ForwardRefValIDs.begin()->second.second,
1687 "use of undefined value '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001688 Twine(ForwardRefValIDs.begin()->first) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001689 return false;
1690}
1691
1692
1693/// GetVal - Get a value with the specified name or ID, creating a
1694/// forward reference record if needed. This can return null if the value
1695/// exists but does not have the right type.
1696Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001697 Type *Ty, LocTy Loc) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001698 // Look this name up in the normal function symbol table.
1699 Value *Val = F.getValueSymbolTable().lookup(Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattnerdf986172009-01-02 07:01:27 +00001701 // If this is a forward reference for the value, see if we already created a
1702 // forward ref record.
1703 if (Val == 0) {
1704 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1705 I = ForwardRefVals.find(Name);
1706 if (I != ForwardRefVals.end())
1707 Val = I->second.first;
1708 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerdf986172009-01-02 07:01:27 +00001710 // If we have the value in the symbol table or fwd-ref table, return it.
1711 if (Val) {
1712 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001713 if (Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001714 P.Error(Loc, "'%" + Name + "' is not a basic block");
1715 else
1716 P.Error(Loc, "'%" + Name + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001717 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001718 return 0;
1719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnerdf986172009-01-02 07:01:27 +00001721 // Don't make placeholders with invalid type.
Chris Lattner1afcace2011-07-09 17:41:24 +00001722 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001723 P.Error(Loc, "invalid use of a non-first-class type");
1724 return 0;
1725 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001726
Chris Lattnerdf986172009-01-02 07:01:27 +00001727 // Otherwise, create a new forward reference for this value and remember it.
1728 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001729 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001730 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001731 else
1732 FwdVal = new Argument(Ty, Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001733
Chris Lattnerdf986172009-01-02 07:01:27 +00001734 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1735 return FwdVal;
1736}
1737
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001738Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
Chris Lattnerdf986172009-01-02 07:01:27 +00001739 LocTy Loc) {
1740 // Look this name up in the normal function symbol table.
1741 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnerdf986172009-01-02 07:01:27 +00001743 // If this is a forward reference for the value, see if we already created a
1744 // forward ref record.
1745 if (Val == 0) {
1746 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1747 I = ForwardRefValIDs.find(ID);
1748 if (I != ForwardRefValIDs.end())
1749 Val = I->second.first;
1750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnerdf986172009-01-02 07:01:27 +00001752 // If we have the value in the symbol table or fwd-ref table, return it.
1753 if (Val) {
1754 if (Val->getType() == Ty) return Val;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001755 if (Ty->isLabelTy())
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001756 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
Chris Lattnerdf986172009-01-02 07:01:27 +00001757 else
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001758 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001759 getTypeString(Val->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001760 return 0;
1761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattner1afcace2011-07-09 17:41:24 +00001763 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001764 P.Error(Loc, "invalid use of a non-first-class type");
1765 return 0;
1766 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001767
Chris Lattnerdf986172009-01-02 07:01:27 +00001768 // Otherwise, create a new forward reference for this value and remember it.
1769 Value *FwdVal;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001770 if (Ty->isLabelTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001771 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
Chris Lattnerdf986172009-01-02 07:01:27 +00001772 else
1773 FwdVal = new Argument(Ty);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001774
Chris Lattnerdf986172009-01-02 07:01:27 +00001775 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1776 return FwdVal;
1777}
1778
1779/// SetInstName - After an instruction is parsed and inserted into its
1780/// basic block, this installs its name.
1781bool LLParser::PerFunctionState::SetInstName(int NameID,
1782 const std::string &NameStr,
1783 LocTy NameLoc, Instruction *Inst) {
1784 // If this instruction has void type, it cannot have a name or ID specified.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001785 if (Inst->getType()->isVoidTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001786 if (NameID != -1 || !NameStr.empty())
1787 return P.Error(NameLoc, "instructions returning void cannot have a name");
1788 return false;
1789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001790
Chris Lattnerdf986172009-01-02 07:01:27 +00001791 // If this was a numbered instruction, verify that the instruction is the
1792 // expected value and resolve any forward references.
1793 if (NameStr.empty()) {
1794 // If neither a name nor an ID was specified, just use the next ID.
1795 if (NameID == -1)
1796 NameID = NumberedVals.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001797
Chris Lattnerdf986172009-01-02 07:01:27 +00001798 if (unsigned(NameID) != NumberedVals.size())
1799 return P.Error(NameLoc, "instruction expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001800 Twine(NumberedVals.size()) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001801
Chris Lattnerdf986172009-01-02 07:01:27 +00001802 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1803 ForwardRefValIDs.find(NameID);
1804 if (FI != ForwardRefValIDs.end()) {
1805 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001806 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001807 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001808 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes2b4f28e2009-09-02 15:02:57 +00001809 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001810 ForwardRefValIDs.erase(FI);
1811 }
1812
1813 NumberedVals.push_back(Inst);
1814 return false;
1815 }
1816
1817 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1818 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1819 FI = ForwardRefVals.find(NameStr);
1820 if (FI != ForwardRefVals.end()) {
1821 if (FI->second.first->getType() != Inst->getType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001822 return P.Error(NameLoc, "instruction forward referenced with type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001823 getTypeString(FI->second.first->getType()) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00001824 FI->second.first->replaceAllUsesWith(Inst);
Nuno Lopes531552a2009-09-02 14:22:03 +00001825 delete FI->second.first;
Chris Lattnerdf986172009-01-02 07:01:27 +00001826 ForwardRefVals.erase(FI);
1827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Chris Lattnerdf986172009-01-02 07:01:27 +00001829 // Set the name on the instruction.
1830 Inst->setName(NameStr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Benjamin Krameraf812352010-10-16 11:28:23 +00001832 if (Inst->getName() != NameStr)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001833 return P.Error(NameLoc, "multiple definition of local value named '" +
Chris Lattnerdf986172009-01-02 07:01:27 +00001834 NameStr + "'");
1835 return false;
1836}
1837
1838/// GetBB - Get a basic block with the specified name or ID, creating a
1839/// forward reference record if needed.
1840BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1841 LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001842 return cast_or_null<BasicBlock>(GetVal(Name,
1843 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001844}
1845
1846BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001847 return cast_or_null<BasicBlock>(GetVal(ID,
1848 Type::getLabelTy(F.getContext()), Loc));
Chris Lattnerdf986172009-01-02 07:01:27 +00001849}
1850
1851/// DefineBB - Define the specified basic block, which is either named or
1852/// unnamed. If there is an error, this returns null otherwise it returns
1853/// the block being defined.
1854BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1855 LocTy Loc) {
1856 BasicBlock *BB;
1857 if (Name.empty())
1858 BB = GetBB(NumberedVals.size(), Loc);
1859 else
1860 BB = GetBB(Name, Loc);
1861 if (BB == 0) return 0; // Already diagnosed error.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerdf986172009-01-02 07:01:27 +00001863 // Move the block to the end of the function. Forward ref'd blocks are
1864 // inserted wherever they happen to be referenced.
1865 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnerdf986172009-01-02 07:01:27 +00001867 // Remove the block from forward ref sets.
1868 if (Name.empty()) {
1869 ForwardRefValIDs.erase(NumberedVals.size());
1870 NumberedVals.push_back(BB);
1871 } else {
1872 // BB forward references are already in the function symbol table.
1873 ForwardRefVals.erase(Name);
1874 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875
Chris Lattnerdf986172009-01-02 07:01:27 +00001876 return BB;
1877}
1878
1879//===----------------------------------------------------------------------===//
1880// Constants.
1881//===----------------------------------------------------------------------===//
1882
1883/// ParseValID - Parse an abstract value that doesn't necessarily have a
1884/// type implied. For example, if we parse "4" we don't know what integer type
1885/// it has. The value will later be combined with its type and checked for
Victor Hernandez24e64df2010-01-10 07:14:18 +00001886/// sanity. PFS is used to convert function-local operands of metadata (since
1887/// metadata operands are not just parsed here but also converted to values).
1888/// PFS can be null when we are not parsing metadata values inside a function.
Victor Hernandezbf170d42010-01-05 22:22:14 +00001889bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00001890 ID.Loc = Lex.getLoc();
1891 switch (Lex.getKind()) {
1892 default: return TokError("expected value token");
1893 case lltok::GlobalID: // @42
1894 ID.UIntVal = Lex.getUIntVal();
1895 ID.Kind = ValID::t_GlobalID;
1896 break;
1897 case lltok::GlobalVar: // @foo
1898 ID.StrVal = Lex.getStrVal();
1899 ID.Kind = ValID::t_GlobalName;
1900 break;
1901 case lltok::LocalVarID: // %42
1902 ID.UIntVal = Lex.getUIntVal();
1903 ID.Kind = ValID::t_LocalID;
1904 break;
1905 case lltok::LocalVar: // %foo
Chris Lattnerdf986172009-01-02 07:01:27 +00001906 ID.StrVal = Lex.getStrVal();
1907 ID.Kind = ValID::t_LocalName;
1908 break;
Dan Gohman83448032010-07-14 18:26:50 +00001909 case lltok::exclaim: // !42, !{...}, or !"foo"
1910 return ParseMetadataValue(ID, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00001911 case lltok::APSInt:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912 ID.APSIntVal = Lex.getAPSIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00001913 ID.Kind = ValID::t_APSInt;
1914 break;
1915 case lltok::APFloat:
1916 ID.APFloatVal = Lex.getAPFloatVal();
1917 ID.Kind = ValID::t_APFloat;
1918 break;
1919 case lltok::kw_true:
Owen Anderson5defacc2009-07-31 17:39:07 +00001920 ID.ConstantVal = ConstantInt::getTrue(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001921 ID.Kind = ValID::t_Constant;
1922 break;
1923 case lltok::kw_false:
Owen Anderson5defacc2009-07-31 17:39:07 +00001924 ID.ConstantVal = ConstantInt::getFalse(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00001925 ID.Kind = ValID::t_Constant;
1926 break;
1927 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1928 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1929 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Chris Lattnerdf986172009-01-02 07:01:27 +00001931 case lltok::lbrace: {
1932 // ValID ::= '{' ConstVector '}'
1933 Lex.Lex();
1934 SmallVector<Constant*, 16> Elts;
1935 if (ParseGlobalValueVector(Elts) ||
1936 ParseToken(lltok::rbrace, "expected end of struct constant"))
1937 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001938
Chris Lattner1afcace2011-07-09 17:41:24 +00001939 ID.ConstantStructElts = new Constant*[Elts.size()];
1940 ID.UIntVal = Elts.size();
1941 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1942 ID.Kind = ValID::t_ConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001943 return false;
1944 }
1945 case lltok::less: {
1946 // ValID ::= '<' ConstVector '>' --> Vector.
1947 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1948 Lex.Lex();
Chris Lattner3ed88ef2009-01-02 08:05:26 +00001949 bool isPackedStruct = EatIfPresent(lltok::lbrace);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001950
Chris Lattnerdf986172009-01-02 07:01:27 +00001951 SmallVector<Constant*, 16> Elts;
1952 LocTy FirstEltLoc = Lex.getLoc();
1953 if (ParseGlobalValueVector(Elts) ||
1954 (isPackedStruct &&
1955 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1956 ParseToken(lltok::greater, "expected end of constant"))
1957 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattnerdf986172009-01-02 07:01:27 +00001959 if (isPackedStruct) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001960 ID.ConstantStructElts = new Constant*[Elts.size()];
1961 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1962 ID.UIntVal = Elts.size();
1963 ID.Kind = ValID::t_PackedConstantStruct;
Chris Lattnerdf986172009-01-02 07:01:27 +00001964 return false;
1965 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001966
Chris Lattnerdf986172009-01-02 07:01:27 +00001967 if (Elts.empty())
1968 return Error(ID.Loc, "constant vector must not be empty");
1969
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001970 if (!Elts[0]->getType()->isIntegerTy() &&
1971 !Elts[0]->getType()->isFloatingPointTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00001972 return Error(FirstEltLoc,
1973 "vector elements must have integer or floating point type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974
Chris Lattnerdf986172009-01-02 07:01:27 +00001975 // Verify that all the vector elements have the same type.
1976 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1977 if (Elts[i]->getType() != Elts[0]->getType())
1978 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00001979 "vector element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00001980 " is not of type '" + getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattner2ca5c862011-02-15 00:14:00 +00001982 ID.ConstantVal = ConstantVector::get(Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00001983 ID.Kind = ValID::t_Constant;
1984 return false;
1985 }
1986 case lltok::lsquare: { // Array Constant
1987 Lex.Lex();
1988 SmallVector<Constant*, 16> Elts;
1989 LocTy FirstEltLoc = Lex.getLoc();
1990 if (ParseGlobalValueVector(Elts) ||
1991 ParseToken(lltok::rsquare, "expected end of array constant"))
1992 return true;
1993
1994 // Handle empty element.
1995 if (Elts.empty()) {
1996 // Use undef instead of an array because it's inconvenient to determine
1997 // the element type at this point, there being no elements to examine.
Chris Lattner081b5052009-01-05 07:52:51 +00001998 ID.Kind = ValID::t_EmptyArray;
Chris Lattnerdf986172009-01-02 07:01:27 +00001999 return false;
2000 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002001
Chris Lattnerdf986172009-01-02 07:01:27 +00002002 if (!Elts[0]->getType()->isFirstClassType())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002003 return Error(FirstEltLoc, "invalid array element type: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002004 getTypeString(Elts[0]->getType()));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002005
Owen Andersondebcb012009-07-29 22:17:13 +00002006 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002007
Chris Lattnerdf986172009-01-02 07:01:27 +00002008 // Verify all elements are correct type!
Chris Lattner6d6b3cc2009-01-02 08:49:06 +00002009 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002010 if (Elts[i]->getType() != Elts[0]->getType())
2011 return Error(FirstEltLoc,
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002012 "array element #" + Twine(i) +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002013 " is not of type '" + getTypeString(Elts[0]->getType()));
Chris Lattnerdf986172009-01-02 07:01:27 +00002014 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002015
Jay Foad26701082011-06-22 09:24:39 +00002016 ID.ConstantVal = ConstantArray::get(ATy, Elts);
Chris Lattnerdf986172009-01-02 07:01:27 +00002017 ID.Kind = ValID::t_Constant;
2018 return false;
2019 }
2020 case lltok::kw_c: // c "foo"
2021 Lex.Lex();
Owen Anderson1d0be152009-08-13 21:58:54 +00002022 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
Chris Lattnerdf986172009-01-02 07:01:27 +00002023 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2024 ID.Kind = ValID::t_Constant;
2025 return false;
2026
2027 case lltok::kw_asm: {
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002028 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2029 bool HasSideEffect, AlignStack;
Chris Lattnerdf986172009-01-02 07:01:27 +00002030 Lex.Lex();
2031 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00002032 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002033 ParseStringConstant(ID.StrVal) ||
2034 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002035 ParseToken(lltok::StringConstant, "expected constraint string"))
2036 return true;
2037 ID.StrVal2 = Lex.getStrVal();
Daniel Dunbarf0bb41c2009-11-07 23:51:55 +00002038 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002039 ID.Kind = ValID::t_InlineAsm;
2040 return false;
2041 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002042
Chris Lattner09d9ef42009-10-28 03:39:23 +00002043 case lltok::kw_blockaddress: {
2044 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2045 Lex.Lex();
2046
2047 ValID Fn, Label;
2048 LocTy FnLoc, LabelLoc;
2049
2050 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2051 ParseValID(Fn) ||
2052 ParseToken(lltok::comma, "expected comma in block address expression")||
2053 ParseValID(Label) ||
2054 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2055 return true;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002056
Chris Lattner09d9ef42009-10-28 03:39:23 +00002057 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2058 return Error(Fn.Loc, "expected function name in blockaddress");
Chris Lattnercdfc9402009-11-01 01:27:45 +00002059 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
Chris Lattner09d9ef42009-10-28 03:39:23 +00002060 return Error(Label.Loc, "expected basic block name in blockaddress");
2061
2062 // Make a global variable as a placeholder for this reference.
2063 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2064 false, GlobalValue::InternalLinkage,
2065 0, "");
2066 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2067 ID.ConstantVal = FwdRef;
2068 ID.Kind = ValID::t_Constant;
2069 return false;
2070 }
2071
Chris Lattnerdf986172009-01-02 07:01:27 +00002072 case lltok::kw_trunc:
2073 case lltok::kw_zext:
2074 case lltok::kw_sext:
2075 case lltok::kw_fptrunc:
2076 case lltok::kw_fpext:
2077 case lltok::kw_bitcast:
2078 case lltok::kw_uitofp:
2079 case lltok::kw_sitofp:
2080 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002081 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002082 case lltok::kw_inttoptr:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002083 case lltok::kw_ptrtoint: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002084 unsigned Opc = Lex.getUIntVal();
Chris Lattner1afcace2011-07-09 17:41:24 +00002085 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002086 Constant *SrcVal;
2087 Lex.Lex();
2088 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2089 ParseGlobalTypeAndValue(SrcVal) ||
Dan Gohman24b108b2009-06-15 21:52:11 +00002090 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002091 ParseType(DestTy) ||
2092 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2093 return true;
2094 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2095 return Error(ID.Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002096 getTypeString(SrcVal->getType()) + "' to '" +
2097 getTypeString(DestTy) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
Owen Andersonfba933c2009-07-01 23:57:11 +00002099 SrcVal, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00002100 ID.Kind = ValID::t_Constant;
2101 return false;
2102 }
2103 case lltok::kw_extractvalue: {
2104 Lex.Lex();
2105 Constant *Val;
2106 SmallVector<unsigned, 4> Indices;
2107 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2108 ParseGlobalTypeAndValue(Val) ||
2109 ParseIndexList(Indices) ||
2110 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2111 return true;
Devang Patele8bc45a2009-11-03 19:06:07 +00002112
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002113 if (!Val->getType()->isAggregateType())
2114 return Error(ID.Loc, "extractvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002115 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002116 return Error(ID.Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002117 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002118 ID.Kind = ValID::t_Constant;
2119 return false;
2120 }
2121 case lltok::kw_insertvalue: {
2122 Lex.Lex();
2123 Constant *Val0, *Val1;
2124 SmallVector<unsigned, 4> Indices;
2125 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2126 ParseGlobalTypeAndValue(Val0) ||
2127 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2128 ParseGlobalTypeAndValue(Val1) ||
2129 ParseIndexList(Indices) ||
2130 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2131 return true;
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002132 if (!Val0->getType()->isAggregateType())
2133 return Error(ID.Loc, "insertvalue operand must be aggregate type");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002134 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002135 return Error(ID.Loc, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00002136 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
Chris Lattnerdf986172009-01-02 07:01:27 +00002137 ID.Kind = ValID::t_Constant;
2138 return false;
2139 }
2140 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002141 case lltok::kw_fcmp: {
Chris Lattnerdf986172009-01-02 07:01:27 +00002142 unsigned PredVal, Opc = Lex.getUIntVal();
2143 Constant *Val0, *Val1;
2144 Lex.Lex();
2145 if (ParseCmpPredicate(PredVal, Opc) ||
2146 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2147 ParseGlobalTypeAndValue(Val0) ||
2148 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2149 ParseGlobalTypeAndValue(Val1) ||
2150 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2151 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002152
Chris Lattnerdf986172009-01-02 07:01:27 +00002153 if (Val0->getType() != Val1->getType())
2154 return Error(ID.Loc, "compare operands must have the same type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002155
Chris Lattnerdf986172009-01-02 07:01:27 +00002156 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157
Chris Lattnerdf986172009-01-02 07:01:27 +00002158 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002159 if (!Val0->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002160 return Error(ID.Loc, "fcmp requires floating point operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002161 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002162 } else {
2163 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002164 if (!Val0->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00002165 !Val0->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002166 return Error(ID.Loc, "icmp requires pointer or integer operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002167 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002168 }
2169 ID.Kind = ValID::t_Constant;
2170 return false;
2171 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002172
Chris Lattnerdf986172009-01-02 07:01:27 +00002173 // Binary Operators.
2174 case lltok::kw_add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002175 case lltok::kw_fadd:
Chris Lattnerdf986172009-01-02 07:01:27 +00002176 case lltok::kw_sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002177 case lltok::kw_fsub:
Chris Lattnerdf986172009-01-02 07:01:27 +00002178 case lltok::kw_mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002179 case lltok::kw_fmul:
Chris Lattnerdf986172009-01-02 07:01:27 +00002180 case lltok::kw_udiv:
2181 case lltok::kw_sdiv:
2182 case lltok::kw_fdiv:
2183 case lltok::kw_urem:
2184 case lltok::kw_srem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002185 case lltok::kw_frem:
2186 case lltok::kw_shl:
2187 case lltok::kw_lshr:
2188 case lltok::kw_ashr: {
Dan Gohman59858cf2009-07-27 16:11:46 +00002189 bool NUW = false;
2190 bool NSW = false;
2191 bool Exact = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002192 unsigned Opc = Lex.getUIntVal();
2193 Constant *Val0, *Val1;
2194 Lex.Lex();
Dan Gohman59858cf2009-07-27 16:11:46 +00002195 LocTy ModifierLoc = Lex.getLoc();
Chris Lattnerf067d582011-02-07 16:40:21 +00002196 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2197 Opc == Instruction::Mul || Opc == Instruction::Shl) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002198 if (EatIfPresent(lltok::kw_nuw))
2199 NUW = true;
2200 if (EatIfPresent(lltok::kw_nsw)) {
2201 NSW = true;
2202 if (EatIfPresent(lltok::kw_nuw))
2203 NUW = true;
2204 }
Chris Lattnerf067d582011-02-07 16:40:21 +00002205 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2206 Opc == Instruction::LShr || Opc == Instruction::AShr) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002207 if (EatIfPresent(lltok::kw_exact))
2208 Exact = true;
2209 }
Chris Lattnerdf986172009-01-02 07:01:27 +00002210 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2211 ParseGlobalTypeAndValue(Val0) ||
2212 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2213 ParseGlobalTypeAndValue(Val1) ||
2214 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2215 return true;
2216 if (Val0->getType() != Val1->getType())
2217 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002218 if (!Val0->getType()->isIntOrIntVectorTy()) {
Dan Gohman59858cf2009-07-27 16:11:46 +00002219 if (NUW)
2220 return Error(ModifierLoc, "nuw only applies to integer operations");
2221 if (NSW)
2222 return Error(ModifierLoc, "nsw only applies to integer operations");
2223 }
Dan Gohman1eaac532010-05-03 22:44:19 +00002224 // Check that the type is valid for the operator.
2225 switch (Opc) {
2226 case Instruction::Add:
2227 case Instruction::Sub:
2228 case Instruction::Mul:
2229 case Instruction::UDiv:
2230 case Instruction::SDiv:
2231 case Instruction::URem:
2232 case Instruction::SRem:
Chris Lattnerf067d582011-02-07 16:40:21 +00002233 case Instruction::Shl:
2234 case Instruction::AShr:
2235 case Instruction::LShr:
Dan Gohman1eaac532010-05-03 22:44:19 +00002236 if (!Val0->getType()->isIntOrIntVectorTy())
2237 return Error(ID.Loc, "constexpr requires integer operands");
2238 break;
2239 case Instruction::FAdd:
2240 case Instruction::FSub:
2241 case Instruction::FMul:
2242 case Instruction::FDiv:
2243 case Instruction::FRem:
2244 if (!Val0->getType()->isFPOrFPVectorTy())
2245 return Error(ID.Loc, "constexpr requires fp operands");
2246 break;
2247 default: llvm_unreachable("Unknown binary operator!");
2248 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002249 unsigned Flags = 0;
2250 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2251 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00002252 if (Exact) Flags |= PossiblyExactOperator::IsExact;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002253 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
Dan Gohman59858cf2009-07-27 16:11:46 +00002254 ID.ConstantVal = C;
Chris Lattnerdf986172009-01-02 07:01:27 +00002255 ID.Kind = ValID::t_Constant;
2256 return false;
2257 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002258
Chris Lattnerdf986172009-01-02 07:01:27 +00002259 // Logical Operations
Chris Lattnerdf986172009-01-02 07:01:27 +00002260 case lltok::kw_and:
2261 case lltok::kw_or:
2262 case lltok::kw_xor: {
2263 unsigned Opc = Lex.getUIntVal();
2264 Constant *Val0, *Val1;
2265 Lex.Lex();
2266 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2267 ParseGlobalTypeAndValue(Val0) ||
2268 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2269 ParseGlobalTypeAndValue(Val1) ||
2270 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2271 return true;
2272 if (Val0->getType() != Val1->getType())
2273 return Error(ID.Loc, "operands of constexpr must have same type");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002274 if (!Val0->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002275 return Error(ID.Loc,
2276 "constexpr requires integer or integer vector operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002277 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
Chris Lattnerdf986172009-01-02 07:01:27 +00002278 ID.Kind = ValID::t_Constant;
2279 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002280 }
2281
Chris Lattnerdf986172009-01-02 07:01:27 +00002282 case lltok::kw_getelementptr:
2283 case lltok::kw_shufflevector:
2284 case lltok::kw_insertelement:
2285 case lltok::kw_extractelement:
2286 case lltok::kw_select: {
2287 unsigned Opc = Lex.getUIntVal();
2288 SmallVector<Constant*, 16> Elts;
Dan Gohmandd8004d2009-07-27 21:53:46 +00002289 bool InBounds = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002290 Lex.Lex();
Dan Gohmandd8004d2009-07-27 21:53:46 +00002291 if (Opc == Instruction::GetElementPtr)
Dan Gohmandcb40a32009-07-29 15:58:36 +00002292 InBounds = EatIfPresent(lltok::kw_inbounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002293 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2294 ParseGlobalValueVector(Elts) ||
2295 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2296 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002297
Chris Lattnerdf986172009-01-02 07:01:27 +00002298 if (Opc == Instruction::GetElementPtr) {
Duncan Sands1df98592010-02-16 11:11:14 +00002299 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002300 return Error(ID.Loc, "getelementptr requires pointer operand");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002301
Jay Foaddab3d292011-07-21 14:31:17 +00002302 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foada9203102011-07-25 09:48:08 +00002303 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00002304 return Error(ID.Loc, "invalid indices for getelementptr");
Jay Foad4b5e2072011-07-21 15:15:37 +00002305 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2306 InBounds);
Chris Lattnerdf986172009-01-02 07:01:27 +00002307 } else if (Opc == Instruction::Select) {
2308 if (Elts.size() != 3)
2309 return Error(ID.Loc, "expected three operands to select");
2310 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2311 Elts[2]))
2312 return Error(ID.Loc, Reason);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002313 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002314 } else if (Opc == Instruction::ShuffleVector) {
2315 if (Elts.size() != 3)
2316 return Error(ID.Loc, "expected three operands to shufflevector");
2317 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2318 return Error(ID.Loc, "invalid operands to shufflevector");
Owen Andersonfba933c2009-07-01 23:57:11 +00002319 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002320 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002321 } else if (Opc == Instruction::ExtractElement) {
2322 if (Elts.size() != 2)
2323 return Error(ID.Loc, "expected two operands to extractelement");
2324 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2325 return Error(ID.Loc, "invalid extractelement operands");
Owen Andersonbaf3c402009-07-29 18:55:55 +00002326 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002327 } else {
2328 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2329 if (Elts.size() != 3)
2330 return Error(ID.Loc, "expected three operands to insertelement");
2331 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2332 return Error(ID.Loc, "invalid insertelement operands");
Owen Andersonfba933c2009-07-01 23:57:11 +00002333 ID.ConstantVal =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002334 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
Chris Lattnerdf986172009-01-02 07:01:27 +00002335 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002336
Chris Lattnerdf986172009-01-02 07:01:27 +00002337 ID.Kind = ValID::t_Constant;
2338 return false;
2339 }
2340 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002341
Chris Lattnerdf986172009-01-02 07:01:27 +00002342 Lex.Lex();
2343 return false;
2344}
2345
2346/// ParseGlobalValue - Parse a global value with the specified type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002347bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
Victor Hernandez92f238d2010-01-11 22:31:58 +00002348 C = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002349 ValID ID;
Victor Hernandez92f238d2010-01-11 22:31:58 +00002350 Value *V = NULL;
2351 bool Parsed = ParseValID(ID) ||
2352 ConvertValIDToValue(Ty, ID, V, NULL);
2353 if (V && !(C = dyn_cast<Constant>(V)))
2354 return Error(ID.Loc, "global values must be constants");
2355 return Parsed;
Chris Lattnerdf986172009-01-02 07:01:27 +00002356}
2357
Victor Hernandez92f238d2010-01-11 22:31:58 +00002358bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002359 Type *Ty = 0;
2360 return ParseType(Ty) ||
2361 ParseGlobalValue(Ty, V);
Victor Hernandez92f238d2010-01-11 22:31:58 +00002362}
2363
2364/// ParseGlobalValueVector
2365/// ::= /*empty*/
2366/// ::= TypeAndValue (',' TypeAndValue)*
2367bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2368 // Empty list.
2369 if (Lex.getKind() == lltok::rbrace ||
2370 Lex.getKind() == lltok::rsquare ||
2371 Lex.getKind() == lltok::greater ||
2372 Lex.getKind() == lltok::rparen)
2373 return false;
2374
2375 Constant *C;
2376 if (ParseGlobalTypeAndValue(C)) return true;
2377 Elts.push_back(C);
2378
2379 while (EatIfPresent(lltok::comma)) {
2380 if (ParseGlobalTypeAndValue(C)) return true;
2381 Elts.push_back(C);
2382 }
2383
2384 return false;
2385}
2386
Dan Gohman309b3af2010-08-24 02:24:03 +00002387bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2388 assert(Lex.getKind() == lltok::lbrace);
2389 Lex.Lex();
2390
2391 SmallVector<Value*, 16> Elts;
2392 if (ParseMDNodeVector(Elts, PFS) ||
2393 ParseToken(lltok::rbrace, "expected end of metadata node"))
2394 return true;
2395
Jay Foadec9186b2011-04-21 19:59:31 +00002396 ID.MDNodeVal = MDNode::get(Context, Elts);
Dan Gohman309b3af2010-08-24 02:24:03 +00002397 ID.Kind = ValID::t_MDNode;
2398 return false;
2399}
2400
Dan Gohman83448032010-07-14 18:26:50 +00002401/// ParseMetadataValue
2402/// ::= !42
2403/// ::= !{...}
2404/// ::= !"string"
2405bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2406 assert(Lex.getKind() == lltok::exclaim);
2407 Lex.Lex();
2408
2409 // MDNode:
2410 // !{ ... }
Dan Gohman309b3af2010-08-24 02:24:03 +00002411 if (Lex.getKind() == lltok::lbrace)
2412 return ParseMetadataListValue(ID, PFS);
Dan Gohman83448032010-07-14 18:26:50 +00002413
2414 // Standalone metadata reference
2415 // !42
2416 if (Lex.getKind() == lltok::APSInt) {
2417 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2418 ID.Kind = ValID::t_MDNode;
2419 return false;
2420 }
2421
2422 // MDString:
2423 // ::= '!' STRINGCONSTANT
2424 if (ParseMDString(ID.MDStringVal)) return true;
2425 ID.Kind = ValID::t_MDString;
2426 return false;
2427}
2428
Victor Hernandez92f238d2010-01-11 22:31:58 +00002429
2430//===----------------------------------------------------------------------===//
2431// Function Parsing.
2432//===----------------------------------------------------------------------===//
2433
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002434bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
Victor Hernandez92f238d2010-01-11 22:31:58 +00002435 PerFunctionState *PFS) {
Duncan Sands1df98592010-02-16 11:11:14 +00002436 if (Ty->isFunctionTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002437 return Error(ID.Loc, "functions are not values, refer to them as pointers");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002438
Chris Lattnerdf986172009-01-02 07:01:27 +00002439 switch (ID.Kind) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002440 default: llvm_unreachable("Unknown ValID!");
Chris Lattnerdf986172009-01-02 07:01:27 +00002441 case ValID::t_LocalID:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002442 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2443 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2444 return (V == 0);
Chris Lattnerdf986172009-01-02 07:01:27 +00002445 case ValID::t_LocalName:
Victor Hernandez92f238d2010-01-11 22:31:58 +00002446 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2447 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2448 return (V == 0);
2449 case ValID::t_InlineAsm: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002450 PointerType *PTy = dyn_cast<PointerType>(Ty);
2451 FunctionType *FTy =
Victor Hernandez92f238d2010-01-11 22:31:58 +00002452 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2453 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2454 return Error(ID.Loc, "invalid type for inline asm constraint string");
2455 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2456 return false;
2457 }
2458 case ValID::t_MDNode:
2459 if (!Ty->isMetadataTy())
2460 return Error(ID.Loc, "metadata value must have metadata type");
2461 V = ID.MDNodeVal;
2462 return false;
2463 case ValID::t_MDString:
2464 if (!Ty->isMetadataTy())
2465 return Error(ID.Loc, "metadata value must have metadata type");
2466 V = ID.MDStringVal;
2467 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002468 case ValID::t_GlobalName:
2469 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2470 return V == 0;
2471 case ValID::t_GlobalID:
2472 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2473 return V == 0;
2474 case ValID::t_APSInt:
Duncan Sands1df98592010-02-16 11:11:14 +00002475 if (!Ty->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002476 return Error(ID.Loc, "integer constant must have integer type");
Jay Foad40f8f622010-12-07 08:25:19 +00002477 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
Owen Andersoneed707b2009-07-24 23:12:02 +00002478 V = ConstantInt::get(Context, ID.APSIntVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002479 return false;
2480 case ValID::t_APFloat:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002481 if (!Ty->isFloatingPointTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00002482 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2483 return Error(ID.Loc, "floating point constant invalid for type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002484
Chris Lattnerdf986172009-01-02 07:01:27 +00002485 // The lexer has no type info, so builds all float and double FP constants
2486 // as double. Fix this here. Long double does not need this.
2487 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002488 Ty->isFloatTy()) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002489 bool Ignored;
2490 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2491 &Ignored);
2492 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002493 V = ConstantFP::get(Context, ID.APFloatVal);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002494
Chris Lattner959873d2009-01-05 18:24:23 +00002495 if (V->getType() != Ty)
2496 return Error(ID.Loc, "floating point constant does not have type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00002497 getTypeString(Ty) + "'");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002498
Chris Lattnerdf986172009-01-02 07:01:27 +00002499 return false;
2500 case ValID::t_Null:
Duncan Sands1df98592010-02-16 11:11:14 +00002501 if (!Ty->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002502 return Error(ID.Loc, "null must be a pointer type");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002503 V = ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattnerdf986172009-01-02 07:01:27 +00002504 return false;
2505 case ValID::t_Undef:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002506 // FIXME: LabelTy should not be a first-class type.
Chris Lattner1afcace2011-07-09 17:41:24 +00002507 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002508 return Error(ID.Loc, "invalid type for undef constant");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002509 V = UndefValue::get(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002510 return false;
Chris Lattner081b5052009-01-05 07:52:51 +00002511 case ValID::t_EmptyArray:
Duncan Sands1df98592010-02-16 11:11:14 +00002512 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
Chris Lattner081b5052009-01-05 07:52:51 +00002513 return Error(ID.Loc, "invalid empty array initializer");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002514 V = UndefValue::get(Ty);
Chris Lattner081b5052009-01-05 07:52:51 +00002515 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002516 case ValID::t_Zero:
Chris Lattnere67c1aa2009-01-05 08:13:38 +00002517 // FIXME: LabelTy should not be a first-class type.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00002518 if (!Ty->isFirstClassType() || Ty->isLabelTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00002519 return Error(ID.Loc, "invalid type for null constant");
Owen Andersona7235ea2009-07-31 20:28:14 +00002520 V = Constant::getNullValue(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002521 return false;
2522 case ValID::t_Constant:
Chris Lattner61c70e92010-08-28 04:09:24 +00002523 if (ID.ConstantVal->getType() != Ty)
Chris Lattnerdf986172009-01-02 07:01:27 +00002524 return Error(ID.Loc, "constant expression type mismatch");
Chris Lattnerfdfeb692010-02-12 20:49:41 +00002525
Chris Lattnerdf986172009-01-02 07:01:27 +00002526 V = ID.ConstantVal;
2527 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +00002528 case ValID::t_ConstantStruct:
2529 case ValID::t_PackedConstantStruct:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002530 if (StructType *ST = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002531 if (ST->getNumElements() != ID.UIntVal)
2532 return Error(ID.Loc,
2533 "initializer with struct type has wrong # elements");
2534 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2535 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2536
2537 // Verify that the elements are compatible with the structtype.
2538 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2539 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2540 return Error(ID.Loc, "element " + Twine(i) +
2541 " of struct initializer doesn't match struct element type");
2542
Frits van Bommel39b5abf2011-07-18 12:00:32 +00002543 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2544 ID.UIntVal));
Chris Lattner1afcace2011-07-09 17:41:24 +00002545 } else
2546 return Error(ID.Loc, "constant expression type mismatch");
2547 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002548 }
2549}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002550
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002551bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002552 V = 0;
2553 ValID ID;
Chris Lattner1afcace2011-07-09 17:41:24 +00002554 return ParseValID(ID, PFS) ||
2555 ConvertValIDToValue(Ty, ID, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002556}
2557
Chris Lattner1afcace2011-07-09 17:41:24 +00002558bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2559 Type *Ty = 0;
2560 return ParseType(Ty) ||
2561 ParseValue(Ty, V, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002562}
2563
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002564bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2565 PerFunctionState &PFS) {
2566 Value *V;
2567 Loc = Lex.getLoc();
2568 if (ParseTypeAndValue(V, PFS)) return true;
2569 if (!isa<BasicBlock>(V))
2570 return Error(Loc, "expected a basic block");
2571 BB = cast<BasicBlock>(V);
2572 return false;
2573}
2574
2575
Chris Lattnerdf986172009-01-02 07:01:27 +00002576/// FunctionHeader
2577/// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
Rafael Espindolabea46262011-01-08 16:42:36 +00002578/// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
Chris Lattnerdf986172009-01-02 07:01:27 +00002579/// OptionalAlign OptGC
2580bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2581 // Parse the linkage.
2582 LocTy LinkageLoc = Lex.getLoc();
2583 unsigned Linkage;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002585 unsigned Visibility, RetAttrs;
2586 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00002587 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00002588 LocTy RetTypeLoc = Lex.getLoc();
2589 if (ParseOptionalLinkage(Linkage) ||
2590 ParseOptionalVisibility(Visibility) ||
2591 ParseOptionalCallingConv(CC) ||
2592 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00002593 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
Chris Lattnerdf986172009-01-02 07:01:27 +00002594 return true;
2595
2596 // Verify that the linkage is ok.
2597 switch ((GlobalValue::LinkageTypes)Linkage) {
2598 case GlobalValue::ExternalLinkage:
2599 break; // always ok.
2600 case GlobalValue::DLLImportLinkage:
Duncan Sands5f4ee1f2009-03-11 08:08:06 +00002601 case GlobalValue::ExternalWeakLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002602 if (isDefine)
2603 return Error(LinkageLoc, "invalid linkage for function definition");
2604 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002605 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +00002606 case GlobalValue::LinkerPrivateLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +00002607 case GlobalValue::LinkerPrivateWeakLinkage:
Bill Wendling55ae5152010-08-20 22:05:50 +00002608 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002609 case GlobalValue::InternalLinkage:
Nick Lewycky55f64db2009-04-13 07:02:02 +00002610 case GlobalValue::AvailableExternallyLinkage:
Duncan Sands667d4b82009-03-07 15:45:40 +00002611 case GlobalValue::LinkOnceAnyLinkage:
2612 case GlobalValue::LinkOnceODRLinkage:
2613 case GlobalValue::WeakAnyLinkage:
2614 case GlobalValue::WeakODRLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002615 case GlobalValue::DLLExportLinkage:
2616 if (!isDefine)
2617 return Error(LinkageLoc, "invalid linkage for function declaration");
2618 break;
2619 case GlobalValue::AppendingLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +00002620 case GlobalValue::CommonLinkage:
Chris Lattnerdf986172009-01-02 07:01:27 +00002621 return Error(LinkageLoc, "invalid function linkage type");
2622 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002623
Chris Lattner1afcace2011-07-09 17:41:24 +00002624 if (!FunctionType::isValidReturnType(RetType))
Chris Lattnerdf986172009-01-02 07:01:27 +00002625 return Error(RetTypeLoc, "invalid function return type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdf986172009-01-02 07:01:27 +00002627 LocTy NameLoc = Lex.getLoc();
Chris Lattnerf570e622009-02-18 21:48:13 +00002628
2629 std::string FunctionName;
2630 if (Lex.getKind() == lltok::GlobalVar) {
2631 FunctionName = Lex.getStrVal();
2632 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2633 unsigned NameID = Lex.getUIntVal();
2634
2635 if (NameID != NumberedVals.size())
2636 return TokError("function expected to be numbered '%" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002637 Twine(NumberedVals.size()) + "'");
Chris Lattnerf570e622009-02-18 21:48:13 +00002638 } else {
2639 return TokError("expected function name");
2640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002642 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002643
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002644 if (Lex.getKind() != lltok::lparen)
Chris Lattnerdf986172009-01-02 07:01:27 +00002645 return TokError("expected '(' in function argument list");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Chris Lattner1afcace2011-07-09 17:41:24 +00002647 SmallVector<ArgInfo, 8> ArgList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002648 bool isVarArg;
Chris Lattnerdf986172009-01-02 07:01:27 +00002649 unsigned FuncAttrs;
Chris Lattnerdf986172009-01-02 07:01:27 +00002650 std::string Section;
Chris Lattnerdf986172009-01-02 07:01:27 +00002651 unsigned Alignment;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002652 std::string GC;
Rafael Espindola3971df52011-01-25 19:09:56 +00002653 bool UnnamedAddr;
2654 LocTy UnnamedAddrLoc;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002655
Chris Lattner1afcace2011-07-09 17:41:24 +00002656 if (ParseArgumentList(ArgList, isVarArg) ||
Rafael Espindola3971df52011-01-25 19:09:56 +00002657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2658 &UnnamedAddrLoc) ||
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002659 ParseOptionalAttrs(FuncAttrs, 2) ||
2660 (EatIfPresent(lltok::kw_section) &&
2661 ParseStringConstant(Section)) ||
2662 ParseOptionalAlignment(Alignment) ||
2663 (EatIfPresent(lltok::kw_gc) &&
2664 ParseStringConstant(GC)))
2665 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00002666
2667 // If the alignment was parsed as an attribute, move to the alignment field.
2668 if (FuncAttrs & Attribute::Alignment) {
2669 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2670 FuncAttrs &= ~Attribute::Alignment;
2671 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002672
Chris Lattnerdf986172009-01-02 07:01:27 +00002673 // Okay, if we got here, the function is syntactically valid. Convert types
2674 // and do semantic checks.
Jay Foad5fdd6c82011-07-12 14:06:48 +00002675 std::vector<Type*> ParamTypeList;
Chris Lattnerdf986172009-01-02 07:01:27 +00002676 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002677
Chris Lattnerdf986172009-01-02 07:01:27 +00002678 if (RetAttrs != Attribute::None)
2679 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002680
Chris Lattnerdf986172009-01-02 07:01:27 +00002681 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002682 ParamTypeList.push_back(ArgList[i].Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00002683 if (ArgList[i].Attrs != Attribute::None)
2684 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2685 }
2686
2687 if (FuncAttrs != Attribute::None)
2688 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2689
2690 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Benjamin Kramerf0127052010-01-05 13:12:22 +00002692 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002693 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2694
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002695 FunctionType *FT =
Owen Andersondebcb012009-07-29 22:17:13 +00002696 FunctionType::get(RetType, ParamTypeList, isVarArg);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002697 PointerType *PFT = PointerType::getUnqual(FT);
Chris Lattnerdf986172009-01-02 07:01:27 +00002698
2699 Fn = 0;
2700 if (!FunctionName.empty()) {
2701 // If this was a definition of a forward reference, remove the definition
2702 // from the forward reference table and fill in the forward ref.
2703 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2704 ForwardRefVals.find(FunctionName);
2705 if (FRVI != ForwardRefVals.end()) {
2706 Fn = M->getFunction(FunctionName);
Chris Lattnerf1cfb952010-04-20 04:49:11 +00002707 if (Fn->getType() != PFT)
2708 return Error(FRVI->second.second, "invalid forward reference to "
2709 "function '" + FunctionName + "' with wrong type!");
2710
Chris Lattnerdf986172009-01-02 07:01:27 +00002711 ForwardRefVals.erase(FRVI);
2712 } else if ((Fn = M->getFunction(FunctionName))) {
Chris Lattnerd5890992011-06-17 07:06:44 +00002713 // Reject redefinitions.
2714 return Error(NameLoc, "invalid redefinition of function '" +
2715 FunctionName + "'");
Chris Lattner1d871c52009-10-25 23:22:50 +00002716 } else if (M->getNamedValue(FunctionName)) {
2717 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Dan Gohman41905542009-08-29 23:37:49 +00002720 } else {
Chris Lattnerdf986172009-01-02 07:01:27 +00002721 // If this is a definition of a forward referenced function, make sure the
2722 // types agree.
2723 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2724 = ForwardRefValIDs.find(NumberedVals.size());
2725 if (I != ForwardRefValIDs.end()) {
2726 Fn = cast<Function>(I->second.first);
2727 if (Fn->getType() != PFT)
2728 return Error(NameLoc, "type of definition and forward reference of '@" +
Benjamin Kramerd1e17032010-09-27 17:42:11 +00002729 Twine(NumberedVals.size()) + "' disagree");
Chris Lattnerdf986172009-01-02 07:01:27 +00002730 ForwardRefValIDs.erase(I);
2731 }
2732 }
2733
2734 if (Fn == 0)
2735 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2736 else // Move the forward-reference to the correct spot in the module.
2737 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2738
2739 if (FunctionName.empty())
2740 NumberedVals.push_back(Fn);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002741
Chris Lattnerdf986172009-01-02 07:01:27 +00002742 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2743 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2744 Fn->setCallingConv(CC);
2745 Fn->setAttributes(PAL);
Rafael Espindolabea46262011-01-08 16:42:36 +00002746 Fn->setUnnamedAddr(UnnamedAddr);
Chris Lattnerdf986172009-01-02 07:01:27 +00002747 Fn->setAlignment(Alignment);
2748 Fn->setSection(Section);
2749 if (!GC.empty()) Fn->setGC(GC.c_str());
Daniel Dunbara279bc32009-09-20 02:20:51 +00002750
Chris Lattnerdf986172009-01-02 07:01:27 +00002751 // Add all of the arguments we parsed to the function.
2752 Function::arg_iterator ArgIt = Fn->arg_begin();
2753 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2754 // If the argument has a name, insert it into the argument symbol table.
2755 if (ArgList[i].Name.empty()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002756
Chris Lattnerdf986172009-01-02 07:01:27 +00002757 // Set the name, if it conflicted, it will be auto-renamed.
2758 ArgIt->setName(ArgList[i].Name);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002759
Benjamin Krameraf812352010-10-16 11:28:23 +00002760 if (ArgIt->getName() != ArgList[i].Name)
Chris Lattnerdf986172009-01-02 07:01:27 +00002761 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2762 ArgList[i].Name + "'");
2763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002764
Chris Lattnerdf986172009-01-02 07:01:27 +00002765 return false;
2766}
2767
2768
2769/// ParseFunctionBody
2770/// ::= '{' BasicBlock+ '}'
Chris Lattnerdf986172009-01-02 07:01:27 +00002771///
2772bool LLParser::ParseFunctionBody(Function &Fn) {
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002773 if (Lex.getKind() != lltok::lbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002774 return TokError("expected '{' in function body");
2775 Lex.Lex(); // eat the {.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Chris Lattner09d9ef42009-10-28 03:39:23 +00002777 int FunctionNumber = -1;
2778 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2779
2780 PerFunctionState PFS(*this, Fn, FunctionNumber);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002781
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002782 // We need at least one basic block.
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002783 if (Lex.getKind() == lltok::rbrace)
Chris Lattner2fdf8db2010-01-09 19:20:07 +00002784 return TokError("function body requires at least one basic block");
2785
Chris Lattner6b7c89e2011-06-17 06:42:57 +00002786 while (Lex.getKind() != lltok::rbrace)
Chris Lattnerdf986172009-01-02 07:01:27 +00002787 if (ParseBasicBlock(PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Chris Lattnerdf986172009-01-02 07:01:27 +00002789 // Eat the }.
2790 Lex.Lex();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerdf986172009-01-02 07:01:27 +00002792 // Verify function is ok.
Chris Lattner09d9ef42009-10-28 03:39:23 +00002793 return PFS.FinishFunction();
Chris Lattnerdf986172009-01-02 07:01:27 +00002794}
2795
2796/// ParseBasicBlock
2797/// ::= LabelStr? Instruction*
2798bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2799 // If this basic block starts out with a name, remember it.
2800 std::string Name;
2801 LocTy NameLoc = Lex.getLoc();
2802 if (Lex.getKind() == lltok::LabelStr) {
2803 Name = Lex.getStrVal();
2804 Lex.Lex();
2805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Chris Lattnerdf986172009-01-02 07:01:27 +00002807 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2808 if (BB == 0) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Chris Lattnerdf986172009-01-02 07:01:27 +00002810 std::string NameStr;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Chris Lattnerdf986172009-01-02 07:01:27 +00002812 // Parse the instructions in this block until we get a terminator.
2813 Instruction *Inst;
Chris Lattner1340dd32009-12-30 05:48:36 +00002814 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
Chris Lattnerdf986172009-01-02 07:01:27 +00002815 do {
2816 // This instruction may have three possibilities for a name: a) none
2817 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2818 LocTy NameLoc = Lex.getLoc();
2819 int NameID = -1;
2820 NameStr = "";
Daniel Dunbara279bc32009-09-20 02:20:51 +00002821
Chris Lattnerdf986172009-01-02 07:01:27 +00002822 if (Lex.getKind() == lltok::LocalVarID) {
2823 NameID = Lex.getUIntVal();
2824 Lex.Lex();
2825 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2826 return true;
Chris Lattner7a1b9bd2011-06-17 06:36:20 +00002827 } else if (Lex.getKind() == lltok::LocalVar) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002828 NameStr = Lex.getStrVal();
2829 Lex.Lex();
2830 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2831 return true;
2832 }
Devang Patelf633a062009-09-17 23:04:48 +00002833
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002834 switch (ParseInstruction(Inst, BB, PFS)) {
2835 default: assert(0 && "Unknown ParseInstruction result!");
2836 case InstError: return true;
2837 case InstNormal:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002838 BB->getInstList().push_back(Inst);
2839
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002840 // With a normal result, we check to see if the instruction is followed by
2841 // a comma and metadata.
2842 if (EatIfPresent(lltok::comma))
Dan Gohman9d072f52010-08-24 02:05:17 +00002843 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002844 return true;
2845 break;
2846 case InstExtraComma:
Chris Lattner4ba9d9b2010-04-07 04:08:57 +00002847 BB->getInstList().push_back(Inst);
2848
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002849 // If the instruction parser ate an extra comma at the end of it, it
2850 // *must* be followed by metadata.
Dan Gohman9d072f52010-08-24 02:05:17 +00002851 if (ParseInstructionMetadata(Inst, &PFS))
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002852 return true;
2853 break;
2854 }
Devang Patelf633a062009-09-17 23:04:48 +00002855
Chris Lattnerdf986172009-01-02 07:01:27 +00002856 // Set the name on the instruction.
2857 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2858 } while (!isa<TerminatorInst>(Inst));
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnerdf986172009-01-02 07:01:27 +00002860 return false;
2861}
2862
2863//===----------------------------------------------------------------------===//
2864// Instruction Parsing.
2865//===----------------------------------------------------------------------===//
2866
2867/// ParseInstruction - Parse one of the many different instructions.
2868///
Chris Lattnerf1bc7ce2009-12-30 05:23:43 +00002869int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2870 PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002871 lltok::Kind Token = Lex.getKind();
2872 if (Token == lltok::Eof)
2873 return TokError("found end of file when expecting more instructions");
2874 LocTy Loc = Lex.getLoc();
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002875 unsigned KeywordVal = Lex.getUIntVal();
Chris Lattnerdf986172009-01-02 07:01:27 +00002876 Lex.Lex(); // Eat the keyword.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Chris Lattnerdf986172009-01-02 07:01:27 +00002878 switch (Token) {
2879 default: return Error(Loc, "expected instruction opcode");
2880 // Terminator Instructions.
Owen Anderson1d0be152009-08-13 21:58:54 +00002881 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2882 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00002883 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2884 case lltok::kw_br: return ParseBr(Inst, PFS);
2885 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
Chris Lattnerab21db72009-10-28 00:19:10 +00002886 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002887 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
Bill Wendling772fe172011-07-27 20:18:04 +00002888 case lltok::kw_resume: return ParseResume(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002889 // Binary Operators.
2890 case lltok::kw_add:
2891 case lltok::kw_sub:
Chris Lattnerf067d582011-02-07 16:40:21 +00002892 case lltok::kw_mul:
2893 case lltok::kw_shl: {
Chris Lattnerf067d582011-02-07 16:40:21 +00002894 bool NUW = EatIfPresent(lltok::kw_nuw);
2895 bool NSW = EatIfPresent(lltok::kw_nsw);
2896 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2897
2898 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2899
2900 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2901 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2902 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002903 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002904 case lltok::kw_fadd:
2905 case lltok::kw_fsub:
2906 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2907
Chris Lattner35bda892011-02-06 21:44:57 +00002908 case lltok::kw_sdiv:
Chris Lattnerf067d582011-02-07 16:40:21 +00002909 case lltok::kw_udiv:
2910 case lltok::kw_lshr:
2911 case lltok::kw_ashr: {
2912 bool Exact = EatIfPresent(lltok::kw_exact);
2913
2914 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2915 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2916 return false;
Dan Gohman59858cf2009-07-27 16:11:46 +00002917 }
2918
Chris Lattnerdf986172009-01-02 07:01:27 +00002919 case lltok::kw_urem:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002920 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
Chris Lattnere914b592009-01-05 08:24:46 +00002921 case lltok::kw_fdiv:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002922 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
Chris Lattnerdf986172009-01-02 07:01:27 +00002923 case lltok::kw_and:
2924 case lltok::kw_or:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002925 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002926 case lltok::kw_icmp:
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002927 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002928 // Casts.
2929 case lltok::kw_trunc:
2930 case lltok::kw_zext:
2931 case lltok::kw_sext:
2932 case lltok::kw_fptrunc:
2933 case lltok::kw_fpext:
2934 case lltok::kw_bitcast:
2935 case lltok::kw_uitofp:
2936 case lltok::kw_sitofp:
2937 case lltok::kw_fptoui:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002938 case lltok::kw_fptosi:
Chris Lattnerdf986172009-01-02 07:01:27 +00002939 case lltok::kw_inttoptr:
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00002940 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
Chris Lattnerdf986172009-01-02 07:01:27 +00002941 // Other.
2942 case lltok::kw_select: return ParseSelect(Inst, PFS);
Chris Lattner0088a5c2009-01-05 08:18:44 +00002943 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002944 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2945 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2946 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2947 case lltok::kw_phi: return ParsePHI(Inst, PFS);
Bill Wendling772fe172011-07-27 20:18:04 +00002948 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002949 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2950 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2951 // Memory.
Victor Hernandez13ad5aa2009-10-17 00:00:19 +00002952 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002953 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2954 case lltok::kw_store: return ParseStore(Inst, PFS, false);
Eli Friedmanff030482011-07-28 21:48:00 +00002955 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS, false);
2956 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS, false);
Eli Friedman47f35132011-07-25 23:16:38 +00002957 case lltok::kw_fence: return ParseFence(Inst, PFS);
Chris Lattnerdf986172009-01-02 07:01:27 +00002958 case lltok::kw_volatile:
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002959 if (EatIfPresent(lltok::kw_load))
Chris Lattnerdf986172009-01-02 07:01:27 +00002960 return ParseLoad(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002961 else if (EatIfPresent(lltok::kw_store))
Chris Lattnerdf986172009-01-02 07:01:27 +00002962 return ParseStore(Inst, PFS, true);
Eli Friedmanff030482011-07-28 21:48:00 +00002963 else if (EatIfPresent(lltok::kw_cmpxchg))
2964 return ParseCmpXchg(Inst, PFS, true);
2965 else if (EatIfPresent(lltok::kw_atomicrmw))
2966 return ParseAtomicRMW(Inst, PFS, true);
Chris Lattner3ed88ef2009-01-02 08:05:26 +00002967 else
Chris Lattnerdf986172009-01-02 07:01:27 +00002968 return TokError("expected 'load' or 'store'");
Chris Lattnerdf986172009-01-02 07:01:27 +00002969 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2970 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2971 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2972 }
2973}
2974
2975/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2976bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002977 if (Opc == Instruction::FCmp) {
Chris Lattnerdf986172009-01-02 07:01:27 +00002978 switch (Lex.getKind()) {
2979 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2980 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2981 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2982 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2983 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2984 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2985 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2986 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2987 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2988 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2989 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2990 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2991 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2992 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2993 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2994 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2995 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2996 }
2997 } else {
2998 switch (Lex.getKind()) {
2999 default: TokError("expected icmp predicate (e.g. 'eq')");
3000 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3001 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3002 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3003 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3004 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3005 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3006 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3007 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3008 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3009 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3010 }
3011 }
3012 Lex.Lex();
3013 return false;
3014}
3015
3016//===----------------------------------------------------------------------===//
3017// Terminator Instructions.
3018//===----------------------------------------------------------------------===//
3019
3020/// ParseRet - Parse a return instruction.
Chris Lattner3f3a0f62009-12-29 21:25:40 +00003021/// ::= 'ret' void (',' !dbg, !1)*
3022/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
Chris Lattner437544f2011-06-17 06:49:41 +00003023bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
Chris Lattner1afcace2011-07-09 17:41:24 +00003024 PerFunctionState &PFS) {
3025 SMLoc TypeLoc = Lex.getLoc();
3026 Type *Ty = 0;
Chris Lattnera9a9e072009-03-09 04:49:14 +00003027 if (ParseType(Ty, true /*void allowed*/)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003028
Chris Lattner1afcace2011-07-09 17:41:24 +00003029 Type *ResType = PFS.getFunction().getReturnType();
3030
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00003031 if (Ty->isVoidTy()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003032 if (!ResType->isVoidTy())
3033 return Error(TypeLoc, "value doesn't match function result type '" +
3034 getTypeString(ResType) + "'");
3035
Owen Anderson1d0be152009-08-13 21:58:54 +00003036 Inst = ReturnInst::Create(Context);
Chris Lattnerdf986172009-01-02 07:01:27 +00003037 return false;
3038 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003039
Chris Lattnerdf986172009-01-02 07:01:27 +00003040 Value *RV;
3041 if (ParseValue(Ty, RV, PFS)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003042
Chris Lattner1afcace2011-07-09 17:41:24 +00003043 if (ResType != RV->getType())
3044 return Error(TypeLoc, "value doesn't match function result type '" +
3045 getTypeString(ResType) + "'");
3046
Owen Anderson1d0be152009-08-13 21:58:54 +00003047 Inst = ReturnInst::Create(Context, RV);
Chris Lattner437544f2011-06-17 06:49:41 +00003048 return false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003049}
3050
3051
3052/// ParseBr
3053/// ::= 'br' TypeAndValue
3054/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3055bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3056 LocTy Loc, Loc2;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003057 Value *Op0;
3058 BasicBlock *Op1, *Op2;
Chris Lattnerdf986172009-01-02 07:01:27 +00003059 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003060
Chris Lattnerdf986172009-01-02 07:01:27 +00003061 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3062 Inst = BranchInst::Create(BB);
3063 return false;
3064 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003065
Owen Anderson1d0be152009-08-13 21:58:54 +00003066 if (Op0->getType() != Type::getInt1Ty(Context))
Chris Lattnerdf986172009-01-02 07:01:27 +00003067 return Error(Loc, "branch condition must have 'i1' type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003068
Chris Lattnerdf986172009-01-02 07:01:27 +00003069 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003070 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003071 ParseToken(lltok::comma, "expected ',' after true destination") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003072 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003073 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003074
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003075 Inst = BranchInst::Create(Op1, Op2, Op0);
Chris Lattnerdf986172009-01-02 07:01:27 +00003076 return false;
3077}
3078
3079/// ParseSwitch
3080/// Instruction
3081/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3082/// JumpTable
3083/// ::= (TypeAndValue ',' TypeAndValue)*
3084bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3085 LocTy CondLoc, BBLoc;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003086 Value *Cond;
3087 BasicBlock *DefaultBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003088 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3089 ParseToken(lltok::comma, "expected ',' after switch condition") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003090 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003091 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3092 return true;
3093
Duncan Sands1df98592010-02-16 11:11:14 +00003094 if (!Cond->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003095 return Error(CondLoc, "switch condition must have integer type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003096
Chris Lattnerdf986172009-01-02 07:01:27 +00003097 // Parse the jump table pairs.
3098 SmallPtrSet<Value*, 32> SeenCases;
3099 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3100 while (Lex.getKind() != lltok::rsquare) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003101 Value *Constant;
3102 BasicBlock *DestBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003103
Chris Lattnerdf986172009-01-02 07:01:27 +00003104 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3105 ParseToken(lltok::comma, "expected ',' after case value") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003106 ParseTypeAndBasicBlock(DestBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003107 return true;
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003108
Chris Lattnerdf986172009-01-02 07:01:27 +00003109 if (!SeenCases.insert(Constant))
3110 return Error(CondLoc, "duplicate case value in switch");
3111 if (!isa<ConstantInt>(Constant))
3112 return Error(CondLoc, "case value is not a constant integer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003113
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003114 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
Chris Lattnerdf986172009-01-02 07:01:27 +00003115 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003116
Chris Lattnerdf986172009-01-02 07:01:27 +00003117 Lex.Lex(); // Eat the ']'.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003118
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003119 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003120 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3121 SI->addCase(Table[i].first, Table[i].second);
3122 Inst = SI;
3123 return false;
3124}
3125
Chris Lattnerab21db72009-10-28 00:19:10 +00003126/// ParseIndirectBr
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003127/// Instruction
Chris Lattnerab21db72009-10-28 00:19:10 +00003128/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3129bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003130 LocTy AddrLoc;
3131 Value *Address;
3132 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
Chris Lattnerab21db72009-10-28 00:19:10 +00003133 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3134 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003135 return true;
3136
Duncan Sands1df98592010-02-16 11:11:14 +00003137 if (!Address->getType()->isPointerTy())
Chris Lattnerab21db72009-10-28 00:19:10 +00003138 return Error(AddrLoc, "indirectbr address must have pointer type");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003139
3140 // Parse the destination list.
3141 SmallVector<BasicBlock*, 16> DestList;
3142
3143 if (Lex.getKind() != lltok::rsquare) {
3144 BasicBlock *DestBB;
3145 if (ParseTypeAndBasicBlock(DestBB, PFS))
3146 return true;
3147 DestList.push_back(DestBB);
3148
3149 while (EatIfPresent(lltok::comma)) {
3150 if (ParseTypeAndBasicBlock(DestBB, PFS))
3151 return true;
3152 DestList.push_back(DestBB);
3153 }
3154 }
3155
3156 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3157 return true;
3158
Chris Lattnerab21db72009-10-28 00:19:10 +00003159 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003160 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3161 IBI->addDestination(DestList[i]);
3162 Inst = IBI;
3163 return false;
3164}
3165
3166
Chris Lattnerdf986172009-01-02 07:01:27 +00003167/// ParseInvoke
3168/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3169/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3170bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3171 LocTy CallLoc = Lex.getLoc();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003172 unsigned RetAttrs, FnAttrs;
3173 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003174 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003175 LocTy RetTypeLoc;
3176 ValID CalleeID;
3177 SmallVector<ParamInfo, 16> ArgList;
3178
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003179 BasicBlock *NormalBB, *UnwindBB;
Chris Lattnerdf986172009-01-02 07:01:27 +00003180 if (ParseOptionalCallingConv(CC) ||
3181 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003182 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003183 ParseValID(CalleeID) ||
3184 ParseParameterList(ArgList, PFS) ||
3185 ParseOptionalAttrs(FnAttrs, 2) ||
3186 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003187 ParseTypeAndBasicBlock(NormalBB, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003188 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
Chris Lattnerf9be95f2009-10-27 19:13:16 +00003189 ParseTypeAndBasicBlock(UnwindBB, PFS))
Chris Lattnerdf986172009-01-02 07:01:27 +00003190 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003191
Chris Lattnerdf986172009-01-02 07:01:27 +00003192 // If RetType is a non-function pointer type, then this is the short syntax
3193 // for the call, which means that RetType is just the return type. Infer the
3194 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003195 PointerType *PFTy = 0;
3196 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003197 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3198 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3199 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003200 std::vector<Type*> ParamTypes;
Chris Lattnerdf986172009-01-02 07:01:27 +00003201 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3202 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003203
Chris Lattnerdf986172009-01-02 07:01:27 +00003204 if (!FunctionType::isValidReturnType(RetType))
3205 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003206
Owen Andersondebcb012009-07-29 22:17:13 +00003207 Ty = FunctionType::get(RetType, ParamTypes, false);
3208 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003210
Chris Lattnerdf986172009-01-02 07:01:27 +00003211 // Look up the callee.
3212 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003213 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003214
Chris Lattnerdf986172009-01-02 07:01:27 +00003215 // Set up the Attributes for the function.
3216 SmallVector<AttributeWithIndex, 8> Attrs;
3217 if (RetAttrs != Attribute::None)
3218 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003219
Chris Lattnerdf986172009-01-02 07:01:27 +00003220 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003221
Chris Lattnerdf986172009-01-02 07:01:27 +00003222 // Loop through FunctionType's arguments and ensure they are specified
3223 // correctly. Also, gather any parameter attributes.
3224 FunctionType::param_iterator I = Ty->param_begin();
3225 FunctionType::param_iterator E = Ty->param_end();
3226 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003227 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003228 if (I != E) {
3229 ExpectedTy = *I++;
3230 } else if (!Ty->isVarArg()) {
3231 return Error(ArgList[i].Loc, "too many arguments specified");
3232 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003233
Chris Lattnerdf986172009-01-02 07:01:27 +00003234 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3235 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003236 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003237 Args.push_back(ArgList[i].V);
3238 if (ArgList[i].Attrs != Attribute::None)
3239 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3240 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241
Chris Lattnerdf986172009-01-02 07:01:27 +00003242 if (I != E)
3243 return Error(CallLoc, "not enough parameters specified for call");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003244
Chris Lattnerdf986172009-01-02 07:01:27 +00003245 if (FnAttrs != Attribute::None)
3246 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003247
Chris Lattnerdf986172009-01-02 07:01:27 +00003248 // Finish off the Attributes and check them
3249 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003250
Jay Foada3efbb12011-07-15 08:37:34 +00003251 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003252 II->setCallingConv(CC);
3253 II->setAttributes(PAL);
3254 Inst = II;
3255 return false;
3256}
3257
Bill Wendling772fe172011-07-27 20:18:04 +00003258/// ParseResume
3259/// ::= 'resume' TypeAndValue
3260bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3261 Value *Exn; LocTy ExnLoc;
3262 LocTy Loc = Lex.getLoc();
3263 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3264 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003265
Bill Wendling772fe172011-07-27 20:18:04 +00003266 ResumeInst *RI = ResumeInst::Create(Context, Exn);
3267 Inst = RI;
3268 return false;
3269}
Chris Lattnerdf986172009-01-02 07:01:27 +00003270
3271//===----------------------------------------------------------------------===//
3272// Binary Operators.
3273//===----------------------------------------------------------------------===//
3274
3275/// ParseArithmetic
Chris Lattnere914b592009-01-05 08:24:46 +00003276/// ::= ArithmeticOps TypeAndValue ',' Value
3277///
3278/// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3279/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
Chris Lattnerdf986172009-01-02 07:01:27 +00003280bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
Chris Lattnere914b592009-01-05 08:24:46 +00003281 unsigned Opc, unsigned OperandType) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003282 LocTy Loc; Value *LHS, *RHS;
3283 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3284 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3285 ParseValue(LHS->getType(), RHS, PFS))
3286 return true;
3287
Chris Lattnere914b592009-01-05 08:24:46 +00003288 bool Valid;
3289 switch (OperandType) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003290 default: llvm_unreachable("Unknown operand type!");
Chris Lattnere914b592009-01-05 08:24:46 +00003291 case 0: // int or FP.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003292 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3293 LHS->getType()->isFPOrFPVectorTy();
Chris Lattnere914b592009-01-05 08:24:46 +00003294 break;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003295 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3296 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
Chris Lattnere914b592009-01-05 08:24:46 +00003297 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003298
Chris Lattnere914b592009-01-05 08:24:46 +00003299 if (!Valid)
3300 return Error(Loc, "invalid operand type for instruction");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003301
Chris Lattnerdf986172009-01-02 07:01:27 +00003302 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3303 return false;
3304}
3305
3306/// ParseLogical
3307/// ::= ArithmeticOps TypeAndValue ',' Value {
3308bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3309 unsigned Opc) {
3310 LocTy Loc; Value *LHS, *RHS;
3311 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3312 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3313 ParseValue(LHS->getType(), RHS, PFS))
3314 return true;
3315
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003316 if (!LHS->getType()->isIntOrIntVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003317 return Error(Loc,"instruction requires integer or integer vector operands");
3318
3319 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3320 return false;
3321}
3322
3323
3324/// ParseCompare
3325/// ::= 'icmp' IPredicates TypeAndValue ',' Value
3326/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
Chris Lattnerdf986172009-01-02 07:01:27 +00003327bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3328 unsigned Opc) {
3329 // Parse the integer/fp comparison predicate.
3330 LocTy Loc;
3331 unsigned Pred;
3332 Value *LHS, *RHS;
3333 if (ParseCmpPredicate(Pred, Opc) ||
3334 ParseTypeAndValue(LHS, Loc, PFS) ||
3335 ParseToken(lltok::comma, "expected ',' after compare value") ||
3336 ParseValue(LHS->getType(), RHS, PFS))
3337 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003338
Chris Lattnerdf986172009-01-02 07:01:27 +00003339 if (Opc == Instruction::FCmp) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003340 if (!LHS->getType()->isFPOrFPVectorTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003341 return Error(Loc, "fcmp requires floating point operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003342 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00003343 } else {
3344 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003345 if (!LHS->getType()->isIntOrIntVectorTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +00003346 !LHS->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003347 return Error(Loc, "icmp requires integer operands");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003348 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
Chris Lattnerdf986172009-01-02 07:01:27 +00003349 }
3350 return false;
3351}
3352
3353//===----------------------------------------------------------------------===//
3354// Other Instructions.
3355//===----------------------------------------------------------------------===//
3356
3357
3358/// ParseCast
3359/// ::= CastOpc TypeAndValue 'to' Type
3360bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3361 unsigned Opc) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003362 LocTy Loc;
3363 Value *Op;
3364 Type *DestTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003365 if (ParseTypeAndValue(Op, Loc, PFS) ||
3366 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3367 ParseType(DestTy))
3368 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003369
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003370 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3371 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
Chris Lattnerdf986172009-01-02 07:01:27 +00003372 return Error(Loc, "invalid cast opcode for cast from '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003373 getTypeString(Op->getType()) + "' to '" +
3374 getTypeString(DestTy) + "'");
Chris Lattnerf6f0bdf2009-03-01 00:53:13 +00003375 }
Chris Lattnerdf986172009-01-02 07:01:27 +00003376 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3377 return false;
3378}
3379
3380/// ParseSelect
3381/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3382bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3383 LocTy Loc;
3384 Value *Op0, *Op1, *Op2;
3385 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3386 ParseToken(lltok::comma, "expected ',' after select condition") ||
3387 ParseTypeAndValue(Op1, PFS) ||
3388 ParseToken(lltok::comma, "expected ',' after select value") ||
3389 ParseTypeAndValue(Op2, PFS))
3390 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003391
Chris Lattnerdf986172009-01-02 07:01:27 +00003392 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3393 return Error(Loc, Reason);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003394
Chris Lattnerdf986172009-01-02 07:01:27 +00003395 Inst = SelectInst::Create(Op0, Op1, Op2);
3396 return false;
3397}
3398
Chris Lattner0088a5c2009-01-05 08:18:44 +00003399/// ParseVA_Arg
3400/// ::= 'va_arg' TypeAndValue ',' Type
3401bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003402 Value *Op;
Chris Lattner1afcace2011-07-09 17:41:24 +00003403 Type *EltTy = 0;
Chris Lattner0088a5c2009-01-05 08:18:44 +00003404 LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003405 if (ParseTypeAndValue(Op, PFS) ||
3406 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
Chris Lattner0088a5c2009-01-05 08:18:44 +00003407 ParseType(EltTy, TypeLoc))
Chris Lattnerdf986172009-01-02 07:01:27 +00003408 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003409
Chris Lattner0088a5c2009-01-05 08:18:44 +00003410 if (!EltTy->isFirstClassType())
3411 return Error(TypeLoc, "va_arg requires operand with first class type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003412
3413 Inst = new VAArgInst(Op, EltTy);
3414 return false;
3415}
3416
3417/// ParseExtractElement
3418/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3419bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3420 LocTy Loc;
3421 Value *Op0, *Op1;
3422 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3423 ParseToken(lltok::comma, "expected ',' after extract value") ||
3424 ParseTypeAndValue(Op1, PFS))
3425 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003426
Chris Lattnerdf986172009-01-02 07:01:27 +00003427 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3428 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003429
Eric Christophera3500da2009-07-25 02:28:41 +00003430 Inst = ExtractElementInst::Create(Op0, Op1);
Chris Lattnerdf986172009-01-02 07:01:27 +00003431 return false;
3432}
3433
3434/// ParseInsertElement
3435/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3436bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3437 LocTy Loc;
3438 Value *Op0, *Op1, *Op2;
3439 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3441 ParseTypeAndValue(Op1, PFS) ||
3442 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3443 ParseTypeAndValue(Op2, PFS))
3444 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003445
Chris Lattnerdf986172009-01-02 07:01:27 +00003446 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
Eric Christopher0aaf4e92009-07-23 01:01:32 +00003447 return Error(Loc, "invalid insertelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003448
Chris Lattnerdf986172009-01-02 07:01:27 +00003449 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3450 return false;
3451}
3452
3453/// ParseShuffleVector
3454/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3455bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3456 LocTy Loc;
3457 Value *Op0, *Op1, *Op2;
3458 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3459 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3460 ParseTypeAndValue(Op1, PFS) ||
3461 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3462 ParseTypeAndValue(Op2, PFS))
3463 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003464
Chris Lattnerdf986172009-01-02 07:01:27 +00003465 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3466 return Error(Loc, "invalid extractelement operands");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003467
Chris Lattnerdf986172009-01-02 07:01:27 +00003468 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3469 return false;
3470}
3471
3472/// ParsePHI
Chris Lattnerc6e20092009-10-18 05:27:44 +00003473/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003474int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattner1afcace2011-07-09 17:41:24 +00003475 Type *Ty = 0; LocTy TypeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003476 Value *Op0, *Op1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003477
Chris Lattner1afcace2011-07-09 17:41:24 +00003478 if (ParseType(Ty, TypeLoc) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003479 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3480 ParseValue(Ty, Op0, PFS) ||
3481 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003482 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003483 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3484 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003485
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003486 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003487 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3488 while (1) {
3489 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003490
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003491 if (!EatIfPresent(lltok::comma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003492 break;
3493
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003494 if (Lex.getKind() == lltok::MetadataVar) {
3495 AteExtraComma = true;
Devang Patela43d46f2009-10-16 18:45:49 +00003496 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003497 }
Devang Patela43d46f2009-10-16 18:45:49 +00003498
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003499 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003500 ParseValue(Ty, Op0, PFS) ||
3501 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
Owen Anderson1d0be152009-08-13 21:58:54 +00003502 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003503 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3504 return true;
3505 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003506
Chris Lattnerdf986172009-01-02 07:01:27 +00003507 if (!Ty->isFirstClassType())
3508 return Error(TypeLoc, "phi node must have first class type");
3509
Jay Foad3ecfc862011-03-30 11:28:46 +00003510 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
Chris Lattnerdf986172009-01-02 07:01:27 +00003511 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3512 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3513 Inst = PN;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003514 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003515}
3516
Bill Wendling772fe172011-07-27 20:18:04 +00003517/// ParseLandingPad
3518/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'?
3519/// (ClauseID ClauseList)+
3520/// ClauseID
3521/// ::= 'catch'
3522/// ::= 'filter'
3523/// ClauseList
3524/// ::= TypeAndValue (',' TypeAndValue)*
3525bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3526 Type *Ty = 0; LocTy TyLoc;
3527 Value *PersFn; LocTy PersFnLoc;
3528 LocTy LPLoc = Lex.getLoc();
3529
3530 if (ParseType(Ty, TyLoc) ||
3531 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3532 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3533 return true;
3534
3535 bool IsCleanup = EatIfPresent(lltok::kw_cleanup);
3536
Bill Wendling28d73522011-07-28 02:27:12 +00003537 SmallVector<std::pair<LandingPadInst::ClauseType, Constant*>, 16> Clauses;
Bill Wendling772fe172011-07-27 20:18:04 +00003538 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3539 LandingPadInst::ClauseType CT;
3540 if (Lex.getKind() == lltok::kw_catch) {
3541 CT = LandingPadInst::Catch;
3542 ParseToken(lltok::kw_catch, "expected 'catch'");
3543 } else {
3544 CT = LandingPadInst::Filter;
3545 ParseToken(lltok::kw_filter, "expected 'filter'");
3546 }
3547
3548 do {
3549 Value *V; LocTy VLoc;
3550 if (ParseTypeAndValue(V, VLoc, PFS))
3551 return true;
Bill Wendling28d73522011-07-28 02:27:12 +00003552 Clauses.push_back(std::make_pair(CT, cast<Constant>(V)));
Bill Wendling772fe172011-07-27 20:18:04 +00003553 } while (EatIfPresent(lltok::comma));
3554 }
3555
Bill Wendling7379b662011-07-28 21:14:13 +00003556 LandingPadInst *LP = LandingPadInst::Create(Ty, cast<Function>(PersFn),
3557 Clauses.size());
Bill Wendling772fe172011-07-27 20:18:04 +00003558 LP->setCleanup(IsCleanup);
3559
Bill Wendling28d73522011-07-28 02:27:12 +00003560 for (SmallVectorImpl<std::pair<LandingPadInst::ClauseType,
3561 Constant*> >::iterator
Bill Wendling772fe172011-07-27 20:18:04 +00003562 I = Clauses.begin(), E = Clauses.end(); I != E; ++I)
3563 LP->addClause(I->first, I->second);
3564
3565 Inst = LP;
3566 return false;
3567}
3568
Chris Lattnerdf986172009-01-02 07:01:27 +00003569/// ParseCall
3570/// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3571/// ParameterList OptionalAttrs
3572bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3573 bool isTail) {
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00003574 unsigned RetAttrs, FnAttrs;
3575 CallingConv::ID CC;
Chris Lattner1afcace2011-07-09 17:41:24 +00003576 Type *RetType = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003577 LocTy RetTypeLoc;
3578 ValID CalleeID;
3579 SmallVector<ParamInfo, 16> ArgList;
3580 LocTy CallLoc = Lex.getLoc();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003581
Chris Lattnerdf986172009-01-02 07:01:27 +00003582 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3583 ParseOptionalCallingConv(CC) ||
3584 ParseOptionalAttrs(RetAttrs, 1) ||
Chris Lattnera9a9e072009-03-09 04:49:14 +00003585 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003586 ParseValID(CalleeID) ||
3587 ParseParameterList(ArgList, PFS) ||
3588 ParseOptionalAttrs(FnAttrs, 2))
3589 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003590
Chris Lattnerdf986172009-01-02 07:01:27 +00003591 // If RetType is a non-function pointer type, then this is the short syntax
3592 // for the call, which means that RetType is just the return type. Infer the
3593 // rest of the function argument types from the arguments that are present.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003594 PointerType *PFTy = 0;
3595 FunctionType *Ty = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003596 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3597 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3598 // Pull out the types of all of the arguments...
Jay Foad5fdd6c82011-07-12 14:06:48 +00003599 std::vector<Type*> ParamTypes;
Eli Friedman83b4a972010-07-24 23:06:59 +00003600 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3601 ParamTypes.push_back(ArgList[i].V->getType());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003602
Chris Lattnerdf986172009-01-02 07:01:27 +00003603 if (!FunctionType::isValidReturnType(RetType))
3604 return Error(RetTypeLoc, "Invalid result type for LLVM function");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003605
Owen Andersondebcb012009-07-29 22:17:13 +00003606 Ty = FunctionType::get(RetType, ParamTypes, false);
3607 PFTy = PointerType::getUnqual(Ty);
Chris Lattnerdf986172009-01-02 07:01:27 +00003608 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003609
Chris Lattnerdf986172009-01-02 07:01:27 +00003610 // Look up the callee.
3611 Value *Callee;
Victor Hernandez92f238d2010-01-11 22:31:58 +00003612 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003613
Chris Lattnerdf986172009-01-02 07:01:27 +00003614 // Set up the Attributes for the function.
3615 SmallVector<AttributeWithIndex, 8> Attrs;
3616 if (RetAttrs != Attribute::None)
3617 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbara279bc32009-09-20 02:20:51 +00003618
Chris Lattnerdf986172009-01-02 07:01:27 +00003619 SmallVector<Value*, 8> Args;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003620
Chris Lattnerdf986172009-01-02 07:01:27 +00003621 // Loop through FunctionType's arguments and ensure they are specified
3622 // correctly. Also, gather any parameter attributes.
3623 FunctionType::param_iterator I = Ty->param_begin();
3624 FunctionType::param_iterator E = Ty->param_end();
3625 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003626 Type *ExpectedTy = 0;
Chris Lattnerdf986172009-01-02 07:01:27 +00003627 if (I != E) {
3628 ExpectedTy = *I++;
3629 } else if (!Ty->isVarArg()) {
3630 return Error(ArgList[i].Loc, "too many arguments specified");
3631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003632
Chris Lattnerdf986172009-01-02 07:01:27 +00003633 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3634 return Error(ArgList[i].Loc, "argument is not of expected type '" +
Chris Lattner0cd0d882011-06-18 21:18:23 +00003635 getTypeString(ExpectedTy) + "'");
Chris Lattnerdf986172009-01-02 07:01:27 +00003636 Args.push_back(ArgList[i].V);
3637 if (ArgList[i].Attrs != Attribute::None)
3638 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3639 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003640
Chris Lattnerdf986172009-01-02 07:01:27 +00003641 if (I != E)
3642 return Error(CallLoc, "not enough parameters specified for call");
3643
3644 if (FnAttrs != Attribute::None)
3645 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3646
3647 // Finish off the Attributes and check them
3648 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +00003649
Jay Foada3efbb12011-07-15 08:37:34 +00003650 CallInst *CI = CallInst::Create(Callee, Args);
Chris Lattnerdf986172009-01-02 07:01:27 +00003651 CI->setTailCall(isTail);
3652 CI->setCallingConv(CC);
3653 CI->setAttributes(PAL);
3654 Inst = CI;
3655 return false;
3656}
3657
3658//===----------------------------------------------------------------------===//
3659// Memory Instructions.
3660//===----------------------------------------------------------------------===//
3661
3662/// ParseAlloc
Devang Patelf633a062009-09-17 23:04:48 +00003663/// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003664int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003665 Value *Size = 0;
Chris Lattnereeb4a842009-07-02 23:08:13 +00003666 LocTy SizeLoc;
Chris Lattnerdf986172009-01-02 07:01:27 +00003667 unsigned Alignment = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003668 Type *Ty = 0;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003669 if (ParseType(Ty)) return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003670
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003671 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003672 if (EatIfPresent(lltok::comma)) {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003673 if (Lex.getKind() == lltok::kw_align) {
3674 if (ParseOptionalAlignment(Alignment)) return true;
3675 } else if (Lex.getKind() == lltok::MetadataVar) {
3676 AteExtraComma = true;
Devang Patelf633a062009-09-17 23:04:48 +00003677 } else {
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003678 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3679 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3680 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003681 }
3682 }
3683
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003684 if (Size && !Size->getType()->isIntegerTy())
3685 return Error(SizeLoc, "element count must have integer type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003686
Chris Lattnerf3a789d2011-06-17 03:16:47 +00003687 Inst = new AllocaInst(Ty, Size, Alignment);
3688 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003689}
3690
3691/// ParseLoad
Devang Patelf633a062009-09-17 23:04:48 +00003692/// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003693int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3694 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003695 Value *Val; LocTy Loc;
Devang Patelf633a062009-09-17 23:04:48 +00003696 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003697 bool AteExtraComma = false;
3698 if (ParseTypeAndValue(Val, Loc, PFS) ||
3699 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3700 return true;
Chris Lattnerdf986172009-01-02 07:01:27 +00003701
Duncan Sands1df98592010-02-16 11:11:14 +00003702 if (!Val->getType()->isPointerTy() ||
Chris Lattnerdf986172009-01-02 07:01:27 +00003703 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3704 return Error(Loc, "load operand must be a pointer to a first class type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003705
Chris Lattnerdf986172009-01-02 07:01:27 +00003706 Inst = new LoadInst(Val, "", isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003707 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003708}
3709
3710/// ParseStore
Dan Gohmana119de82009-06-14 23:30:43 +00003711/// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003712int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3713 bool isVolatile) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003714 Value *Val, *Ptr; LocTy Loc, PtrLoc;
Devang Patelf633a062009-09-17 23:04:48 +00003715 unsigned Alignment = 0;
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003716 bool AteExtraComma = false;
Chris Lattnerdf986172009-01-02 07:01:27 +00003717 if (ParseTypeAndValue(Val, Loc, PFS) ||
3718 ParseToken(lltok::comma, "expected ',' after store operand") ||
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003719 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3720 ParseOptionalCommaAlign(Alignment, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003721 return true;
Devang Patelf633a062009-09-17 23:04:48 +00003722
Duncan Sands1df98592010-02-16 11:11:14 +00003723 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003724 return Error(PtrLoc, "store operand must be a pointer");
3725 if (!Val->getType()->isFirstClassType())
3726 return Error(Loc, "store operand must be a first class value");
3727 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3728 return Error(Loc, "stored value and pointer type do not match");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003729
Chris Lattnerdf986172009-01-02 07:01:27 +00003730 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
Chris Lattnerc3a6c5c2009-12-30 05:44:30 +00003731 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003732}
3733
Eli Friedmanff030482011-07-28 21:48:00 +00003734/// ParseCmpXchg
3735/// ::= 'volatile'? 'cmpxchg' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3736/// 'singlethread'? AtomicOrdering
3737int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS,
3738 bool isVolatile) {
3739 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3740 bool AteExtraComma = false;
3741 AtomicOrdering Ordering = NotAtomic;
3742 SynchronizationScope Scope = CrossThread;
3743 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3744 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3745 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3746 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3747 ParseTypeAndValue(New, NewLoc, PFS) ||
3748 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3749 return true;
3750
3751 if (Ordering == Unordered)
3752 return TokError("cmpxchg cannot be unordered");
3753 if (!Ptr->getType()->isPointerTy())
3754 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3755 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3756 return Error(CmpLoc, "compare value and pointer type do not match");
3757 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3758 return Error(NewLoc, "new value and pointer type do not match");
3759 if (!New->getType()->isIntegerTy())
3760 return Error(NewLoc, "cmpxchg operand must be an integer");
3761 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3762 if (Size < 8 || (Size & (Size - 1)))
3763 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3764 " integer");
3765
3766 AtomicCmpXchgInst *CXI =
3767 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3768 CXI->setVolatile(isVolatile);
3769 Inst = CXI;
3770 return AteExtraComma ? InstExtraComma : InstNormal;
3771}
3772
3773/// ParseAtomicRMW
3774/// ::= 'volatile'? 'atomicrmw' BinOp TypeAndValue ',' TypeAndValue
3775/// 'singlethread'? AtomicOrdering
3776int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS,
3777 bool isVolatile) {
3778 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3779 bool AteExtraComma = false;
3780 AtomicOrdering Ordering = NotAtomic;
3781 SynchronizationScope Scope = CrossThread;
3782 AtomicRMWInst::BinOp Operation;
3783 switch (Lex.getKind()) {
3784 default: return TokError("expected binary operation in atomicrmw");
3785 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3786 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3787 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3788 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3789 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3790 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3791 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3792 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3793 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3794 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3795 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3796 }
3797 Lex.Lex(); // Eat the operation.
3798
3799 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3800 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3801 ParseTypeAndValue(Val, ValLoc, PFS) ||
3802 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3803 return true;
3804
3805 if (Ordering == Unordered)
3806 return TokError("atomicrmw cannot be unordered");
3807 if (!Ptr->getType()->isPointerTy())
3808 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3809 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3810 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3811 if (!Val->getType()->isIntegerTy())
3812 return Error(ValLoc, "atomicrmw operand must be an integer");
3813 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3814 if (Size < 8 || (Size & (Size - 1)))
3815 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3816 " integer");
3817
3818 AtomicRMWInst *RMWI =
3819 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3820 RMWI->setVolatile(isVolatile);
3821 Inst = RMWI;
3822 return AteExtraComma ? InstExtraComma : InstNormal;
3823}
3824
Eli Friedman47f35132011-07-25 23:16:38 +00003825/// ParseFence
3826/// ::= 'fence' 'singlethread'? AtomicOrdering
3827int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3828 AtomicOrdering Ordering = NotAtomic;
3829 SynchronizationScope Scope = CrossThread;
3830 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3831 return true;
3832
3833 if (Ordering == Unordered)
3834 return TokError("fence cannot be unordered");
3835 if (Ordering == Monotonic)
3836 return TokError("fence cannot be monotonic");
3837
3838 Inst = new FenceInst(Context, Ordering, Scope);
3839 return InstNormal;
3840}
3841
Chris Lattnerdf986172009-01-02 07:01:27 +00003842/// ParseGetElementPtr
Dan Gohmandd8004d2009-07-27 21:53:46 +00003843/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003844int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003845 Value *Ptr, *Val; LocTy Loc, EltLoc;
Dan Gohmandd8004d2009-07-27 21:53:46 +00003846
Dan Gohmandcb40a32009-07-29 15:58:36 +00003847 bool InBounds = EatIfPresent(lltok::kw_inbounds);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003848
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003849 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003850
Duncan Sands1df98592010-02-16 11:11:14 +00003851 if (!Ptr->getType()->isPointerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003852 return Error(Loc, "base of getelementptr must be a pointer");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003853
Chris Lattnerdf986172009-01-02 07:01:27 +00003854 SmallVector<Value*, 16> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003855 bool AteExtraComma = false;
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003856 while (EatIfPresent(lltok::comma)) {
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003857 if (Lex.getKind() == lltok::MetadataVar) {
3858 AteExtraComma = true;
Devang Patel6225d642009-10-13 18:49:55 +00003859 break;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003860 }
Chris Lattner3ed88ef2009-01-02 08:05:26 +00003861 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
Duncan Sands1df98592010-02-16 11:11:14 +00003862 if (!Val->getType()->isIntegerTy())
Chris Lattnerdf986172009-01-02 07:01:27 +00003863 return Error(EltLoc, "getelementptr index must be an integer");
3864 Indices.push_back(Val);
3865 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003866
Jay Foada9203102011-07-25 09:48:08 +00003867 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003868 return Error(Loc, "invalid getelementptr indices");
Jay Foada9203102011-07-25 09:48:08 +00003869 Inst = GetElementPtrInst::Create(Ptr, Indices);
Dan Gohmandd8004d2009-07-27 21:53:46 +00003870 if (InBounds)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003871 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003872 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003873}
3874
3875/// ParseExtractValue
3876/// ::= 'extractvalue' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003877int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003878 Value *Val; LocTy Loc;
3879 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003880 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003881 if (ParseTypeAndValue(Val, Loc, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003882 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003883 return true;
3884
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003885 if (!Val->getType()->isAggregateType())
3886 return Error(Loc, "extractvalue operand must be aggregate type");
Chris Lattnerdf986172009-01-02 07:01:27 +00003887
Jay Foadfc6d3a42011-07-13 10:26:04 +00003888 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003889 return Error(Loc, "invalid indices for extractvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003890 Inst = ExtractValueInst::Create(Val, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003891 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003892}
3893
3894/// ParseInsertValue
3895/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003896int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
Chris Lattnerdf986172009-01-02 07:01:27 +00003897 Value *Val0, *Val1; LocTy Loc0, Loc1;
3898 SmallVector<unsigned, 4> Indices;
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003899 bool AteExtraComma;
Chris Lattnerdf986172009-01-02 07:01:27 +00003900 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3901 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3902 ParseTypeAndValue(Val1, Loc1, PFS) ||
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003903 ParseIndexList(Indices, AteExtraComma))
Chris Lattnerdf986172009-01-02 07:01:27 +00003904 return true;
Chris Lattner628c13a2009-12-30 05:14:00 +00003905
Chris Lattnerfdfeb692010-02-12 20:49:41 +00003906 if (!Val0->getType()->isAggregateType())
3907 return Error(Loc0, "insertvalue operand must be aggregate type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003908
Jay Foadfc6d3a42011-07-13 10:26:04 +00003909 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
Chris Lattnerdf986172009-01-02 07:01:27 +00003910 return Error(Loc0, "invalid indices for insertvalue");
Jay Foadfc6d3a42011-07-13 10:26:04 +00003911 Inst = InsertValueInst::Create(Val0, Val1, Indices);
Chris Lattnera7d7f2c2009-12-30 05:27:33 +00003912 return AteExtraComma ? InstExtraComma : InstNormal;
Chris Lattnerdf986172009-01-02 07:01:27 +00003913}
Nick Lewycky21cc4462009-04-04 07:22:01 +00003914
3915//===----------------------------------------------------------------------===//
3916// Embedded metadata.
3917//===----------------------------------------------------------------------===//
3918
3919/// ParseMDNodeVector
Nick Lewyckycb337992009-05-10 20:57:05 +00003920/// ::= Element (',' Element)*
3921/// Element
3922/// ::= 'null' | TypeAndValue
Victor Hernandezbf170d42010-01-05 22:22:14 +00003923bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
Victor Hernandez24e64df2010-01-10 07:14:18 +00003924 PerFunctionState *PFS) {
Dan Gohmanac809752010-07-13 19:33:27 +00003925 // Check for an empty list.
3926 if (Lex.getKind() == lltok::rbrace)
3927 return false;
3928
Nick Lewycky21cc4462009-04-04 07:22:01 +00003929 do {
Chris Lattnera7352392009-12-30 04:42:57 +00003930 // Null is a special case since it is typeless.
3931 if (EatIfPresent(lltok::kw_null)) {
3932 Elts.push_back(0);
3933 continue;
Nick Lewyckycb337992009-05-10 20:57:05 +00003934 }
Chris Lattnera7352392009-12-30 04:42:57 +00003935
3936 Value *V = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +00003937 if (ParseTypeAndValue(V, PFS)) return true;
Nick Lewyckycb337992009-05-10 20:57:05 +00003938 Elts.push_back(V);
Nick Lewycky21cc4462009-04-04 07:22:01 +00003939 } while (EatIfPresent(lltok::comma));
3940
3941 return false;
3942}